"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.YieldProtocolBorrowContractPositionFetcher = exports.artsQuery = exports.ilksQuery = void 0;
const common_1 = require("@nestjs/common");
const ethers_1 = require("ethers");
const utils_1 = require("ethers/lib/utils");
const graphql_request_1 = require("graphql-request");
const lodash_1 = require("lodash");
const app_toolkit_interface_1 = require("../../../app-toolkit/app-toolkit.interface");
const drill_balance_helper_1 = require("../../../app-toolkit/helpers/drill-balance.helper");
const image_present_1 = require("../../../app-toolkit/helpers/presentation/image.present");
const the_graph_helper_1 = require("../../../app-toolkit/helpers/the-graph.helper");
const contract_interface_1 = require("../../../position/contract.interface");
const position_interface_1 = require("../../../position/position.interface");
const position_utils_1 = require("../../../position/position.utils");
const custom_contract_position_template_position_fetcher_1 = require("../../../position/template/custom-contract-position.template.position-fetcher");
const contracts_1 = require("../contracts");
const yield_protocol_lend_token_fetcher_1 = require("./yield-protocol.lend.token-fetcher");
exports.ilksQuery = (0, graphql_request_1.gql) `
  {
    assets {
      id
      assetId
    }
  }
`;
exports.artsQuery = (0, graphql_request_1.gql) `
  {
    seriesEntities {
      baseAsset {
        id
        assetId
      }
    }
  }
`;
const vaultsQuery = (0, graphql_request_1.gql) `
  query ($address: ID!) {
    account(id: $address) {
      id
      vaults {
        debtAmount
        collateralAmount
        series {
          baseAsset {
            id
            assetId
          }
          fyToken {
            maturity
          }
        }
        collateral {
          asset {
            id
            assetId
          }
        }
      }
    }
  }
`;
let YieldProtocolBorrowContractPositionFetcher = class YieldProtocolBorrowContractPositionFetcher extends custom_contract_position_template_position_fetcher_1.CustomContractPositionTemplatePositionFetcher {
    constructor(appToolkit, contractFactory) {
        super(appToolkit);
        this.appToolkit = appToolkit;
        this.contractFactory = contractFactory;
    }
    getContract(address) {
        return this.contractFactory.yieldProtocolLadle({ address, network: this.network });
    }
    getDefinitions({ multicall }) {
        return __awaiter(this, void 0, void 0, function* () {
            const cauldron = this.contractFactory.yieldProtocolCauldron({
                address: this.cauldronAddress,
                network: this.network,
            });
            const { assets: ilks } = yield (0, the_graph_helper_1.gqlFetch)({ endpoint: this.subgraphUrl, query: exports.ilksQuery });
            const { seriesEntities: artsRes } = yield (0, the_graph_helper_1.gqlFetch)({ endpoint: this.subgraphUrl, query: exports.artsQuery });
            const distinctArts = (0, lodash_1.uniqWith)(artsRes, lodash_1.isEqual);
            const definitionsByIlk = yield Promise.all(ilks.map((ilk) => __awaiter(this, void 0, void 0, function* () {
                const { assetId: ilkId, id: ilkAddress } = ilk;
                if (!ilkId)
                    return [];
                return Promise.all(distinctArts.map((art) => __awaiter(this, void 0, void 0, function* () {
                    const { assetId: artId, id: artAddress } = art.baseAsset;
                    const { max: maxDebt } = yield multicall.wrap(cauldron).debt(artId, ilkId);
                    if (maxDebt.eq(ethers_1.ethers.constants.Zero))
                        return null;
                    return { address: this.ladleAddress, ilkId, artId, ilkAddress, artAddress };
                })));
            })));
            return (0, lodash_1.compact)(definitionsByIlk.flat());
        });
    }
    getTokenDefinitions({ definition, }) {
        return __awaiter(this, void 0, void 0, function* () {
            return [
                { metaType: position_interface_1.MetaType.SUPPLIED, address: definition.ilkAddress, network: this.network },
                { metaType: position_interface_1.MetaType.BORROWED, address: definition.artAddress, network: this.network },
            ];
        });
    }
    getDataProps(params) {
        const _super = Object.create(null, {
            getDataProps: { get: () => super.getDataProps }
        });
        return __awaiter(this, void 0, void 0, function* () {
            const { definition, multicall } = params;
            const cauldron = this.contractFactory.yieldProtocolCauldron({
                address: this.cauldronAddress,
                network: this.network,
            });
            const { artId, ilkId } = definition;
            const { ratio } = yield multicall.wrap(cauldron).spotOracles(artId, ilkId);
            const minCollateralizationRatio = ratio / Math.pow(10, 6);
            const defaultDataProps = yield _super.getDataProps.call(this, params);
            return Object.assign(Object.assign({}, defaultDataProps), { artId, ilkId, minCollateralizationRatio });
        });
    }
    getLabel({ contractPosition }) {
        return __awaiter(this, void 0, void 0, function* () {
            return `Yield ${(0, image_present_1.getLabelFromToken)(contractPosition.tokens[0])} Debt and ${(0, image_present_1.getLabelFromToken)(contractPosition.tokens[1])} Collateral`;
        });
    }
    getTokenBalancesPerPosition() {
        return __awaiter(this, void 0, void 0, function* () {
            throw new Error('Method not implemented.');
        });
    }
    getBalances(address) {
        return __awaiter(this, void 0, void 0, function* () {
            const multicall = this.appToolkit.getMulticall(this.network);
            const baseTokens = yield this.appToolkit.getBaseTokenPrices(this.network);
            const cauldron = this.contractFactory.yieldProtocolCauldron({
                address: this.cauldronAddress,
                network: this.network,
            });
            const data = yield (0, the_graph_helper_1.gqlFetch)({
                endpoint: this.subgraphUrl,
                query: vaultsQuery,
                variables: { address },
            });
            const account = data.account;
            if (!account)
                return [];
            const positions = yield Promise.all(account.vaults.map((vault) => __awaiter(this, void 0, void 0, function* () {
                const { debtAmount, collateralAmount, series: { baseAsset: { id: artAddress, assetId: artId }, fyToken: { maturity }, }, collateral: { asset: { id: ilkAddress, assetId: ilkId }, }, } = vault;
                const art = baseTokens.find(v => v.address === artAddress.toLowerCase());
                const ilk = baseTokens.find(v => v.address === ilkAddress.toLowerCase());
                if (!art || !ilk)
                    return null;
                const collateral = (0, drill_balance_helper_1.drillBalance)((0, position_utils_1.supplied)(ilk), (0, utils_1.parseUnits)(collateralAmount.toString(), ilk.decimals).toString());
                const debt = (0, drill_balance_helper_1.drillBalance)((0, position_utils_1.borrowed)(art), (0, utils_1.parseUnits)(debtAmount.toString(), art.decimals).toString(), {
                    isDebt: true,
                });
                const tokens = [collateral, debt];
                const balanceUSD = (0, lodash_1.sumBy)(tokens, v => v.balanceUSD);
                const collateralizationRatio = debt.balanceUSD === 0 ? 0 : (collateral.balanceUSD / Math.abs(debt.balanceUSD)) * 100;
                const { ratio } = yield multicall.wrap(cauldron).spotOracles(artId, ilkId);
                const minCollateralizationRatio = ratio / Math.pow(10, 6);
                const liquidationPrice = (debtAmount * minCollateralizationRatio) / collateralAmount;
                const yieldLabel = `Yield ${(0, image_present_1.getLabelFromToken)(art)} Debt and ${(0, image_present_1.getLabelFromToken)(ilk)} Collateral Vault`;
                const label = `${yieldLabel} - ${(0, yield_protocol_lend_token_fetcher_1.formatMaturity)(maturity)}`;
                const images = [(0, image_present_1.getImagesFromToken)(art)[0], (0, image_present_1.getImagesFromToken)(ilk)[0]];
                const positionBalance = {
                    type: contract_interface_1.ContractType.POSITION,
                    address: this.ladleAddress,
                    appId: this.appId,
                    groupId: this.groupId,
                    network: this.network,
                    tokens,
                    balanceUSD,
                    dataProps: {
                        ilkId,
                        artId,
                        minCollateralizationRatio,
                        collateralizationRatio,
                        liquidationPrice,
                    },
                    displayProps: {
                        label,
                        images,
                    },
                };
                positionBalance.key = this.appToolkit.getPositionKey(positionBalance);
                return positionBalance;
            })));
            return (0, lodash_1.compact)(positions);
        });
    }
};
YieldProtocolBorrowContractPositionFetcher = __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])
], YieldProtocolBorrowContractPositionFetcher);
exports.YieldProtocolBorrowContractPositionFetcher = YieldProtocolBorrowContractPositionFetcher;
//# sourceMappingURL=yield-protocol.borrow.contract-position-fetcher.js.map