"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.YieldProtocolLendTokenFetcher = exports.formatMaturity = void 0;
const common_1 = require("@nestjs/common");
const ethers_1 = require("ethers");
const graphql_request_1 = require("graphql-request");
const moment_1 = __importDefault(require("moment"));
const app_toolkit_interface_1 = require("../../../app-toolkit/app-toolkit.interface");
const image_present_1 = require("../../../app-toolkit/helpers/presentation/image.present");
const the_graph_helper_1 = require("../../../app-toolkit/helpers/the-graph.helper");
const multicall_ethers_1 = require("../../../multicall/multicall.ethers");
const app_token_template_position_fetcher_1 = require("../../../position/template/app-token.template.position-fetcher");
const contracts_1 = require("../contracts");
const formatMaturity = (maturity) => {
    return (0, moment_1.default)(moment_1.default.unix(maturity)).format('MMMM D, yyyy');
};
exports.formatMaturity = formatMaturity;
const query = (0, graphql_request_1.gql) `
  {
    seriesEntities {
      matured
      baseAsset {
        id
      }
      fyToken {
        id
        symbol
        decimals
        totalSupply
        maturity
      }
    }
    pools {
      id
      fyToken {
        id
      }
    }
  }
`;
let YieldProtocolLendTokenFetcher = class YieldProtocolLendTokenFetcher extends app_token_template_position_fetcher_1.AppTokenTemplatePositionFetcher {
    constructor(appToolkit, contractFactory) {
        super(appToolkit);
        this.appToolkit = appToolkit;
        this.contractFactory = contractFactory;
    }
    getContract(address) {
        return this.contractFactory.yieldProtocolLendToken({ address, network: this.network });
    }
    getDefinitions() {
        return __awaiter(this, void 0, void 0, function* () {
            const { pools, seriesEntities } = yield (0, the_graph_helper_1.gqlFetch)({
                endpoint: this.subgraphUrl,
                query,
            });
            return seriesEntities.map(entity => {
                var _a;
                return ({
                    address: entity.fyToken.id,
                    poolAddress: (_a = pools.find(v => v.fyToken.id === entity.fyToken.id)) === null || _a === void 0 ? void 0 : _a.id,
                });
            });
        });
    }
    getAddresses({ definitions }) {
        return __awaiter(this, void 0, void 0, function* () {
            return definitions.map(v => v.address);
        });
    }
    getUnderlyingTokenDefinitions({ contract }) {
        return __awaiter(this, void 0, void 0, function* () {
            return [{ address: yield contract.underlying(), network: this.network }];
        });
    }
    getPricePerShare({ appToken, definition, contract, multicall, }) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!definition.poolAddress)
                return [1];
            const pool = this.contractFactory.yieldProtocolPool({ address: definition.poolAddress, network: this.network });
            const poolBalance = yield multicall
                .wrap(pool)
                .getBaseBalance()
                .catch(err => {
                if ((0, multicall_ethers_1.isMulticallUnderlyingError)(err))
                    return ethers_1.BigNumber.from(0);
                throw err;
            });
            if (poolBalance.isZero())
                return [0];
            const maturity = yield contract.maturity();
            const isMatured = Math.floor(new Date().getTime() / 1000) > Number(maturity);
            if (isMatured)
                return [1];
            const estimateRaw = appToken.tokens[0].symbol === 'WETH'
                ? (yield multicall.wrap(pool).sellFYTokenPreview(ethers_1.ethers.utils.parseUnits('.01', appToken.decimals))).mul(100)
                : yield multicall.wrap(pool).sellFYTokenPreview(ethers_1.ethers.utils.parseUnits('1', appToken.decimals));
            return [+ethers_1.ethers.utils.formatUnits(estimateRaw, appToken.decimals)];
        });
    }
    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 maturity = yield params.contract.maturity();
            return Object.assign(Object.assign({}, defaultDataProps), { maturity: Number(maturity) });
        });
    }
    getLabel({ appToken }) {
        return __awaiter(this, void 0, void 0, function* () {
            return `fy${(0, image_present_1.getLabelFromToken)(appToken.tokens[0])}`;
        });
    }
    getSecondaryLabel({ appToken, }) {
        return __awaiter(this, void 0, void 0, function* () {
            return (0, exports.formatMaturity)(appToken.dataProps.maturity);
        });
    }
    getTertiaryLabel({ appToken, }) {
        return __awaiter(this, void 0, void 0, function* () {
            const isMatured = Math.floor(new Date().getTime() / 1000) > Number(appToken.dataProps.maturity);
            return isMatured ? 'Matured' : '';
        });
    }
};
YieldProtocolLendTokenFetcher = __decorate([
    __param(0, (0, common_1.Inject)(app_toolkit_interface_1.APP_TOOLKIT)),
    __param(1, (0, common_1.Inject)(contracts_1.YieldProtocolContractFactory)),
    __metadata("design:paramtypes", [Object, contracts_1.YieldProtocolContractFactory])
], YieldProtocolLendTokenFetcher);
exports.YieldProtocolLendTokenFetcher = YieldProtocolLendTokenFetcher;
//# sourceMappingURL=yield-protocol.lend.token-fetcher.js.map