"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.EthereumMakerVaultContractPositionFetcher = void 0;
const common_1 = require("@nestjs/common");
const bignumber_js_1 = __importDefault(require("bignumber.js"));
const ethers_1 = require("ethers");
const lodash_1 = require("lodash");
const app_toolkit_interface_1 = require("../../../app-toolkit/app-toolkit.interface");
const address_1 = require("../../../app-toolkit/constants/address");
const position_template_decorator_1 = require("../../../app-toolkit/decorators/position-template.decorator");
const drill_balance_helper_1 = require("../../../app-toolkit/helpers/drill-balance.helper");
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");
let EthereumMakerVaultContractPositionFetcher = class EthereumMakerVaultContractPositionFetcher extends custom_contract_position_template_position_fetcher_1.CustomContractPositionTemplatePositionFetcher {
    constructor(appToolkit, contractFactory) {
        super(appToolkit);
        this.appToolkit = appToolkit;
        this.contractFactory = contractFactory;
        this.groupLabel = 'Vaults';
    }
    getContract(address) {
        return this.contractFactory.makerGemJoin({ address, network: this.network });
    }
    getDefinitions({ multicall }) {
        return __awaiter(this, void 0, void 0, function* () {
            const ilkRegAddress = '0x5a464c28d19848f44199d003bef5ecc87d090f87';
            const ilkRegContract = this.contractFactory.makerIlkRegistry({ address: ilkRegAddress, network: this.network });
            const numIlks = yield ilkRegContract.count();
            const definitions = yield Promise.all((0, lodash_1.range)(0, Number(numIlks)).map((ilkIndex) => __awaiter(this, void 0, void 0, function* () {
                const ilk = yield multicall.wrap(ilkRegContract).get(ilkIndex);
                const [gem, join] = yield Promise.all([
                    multicall.wrap(ilkRegContract).gem(ilk),
                    multicall.wrap(ilkRegContract).join(ilk),
                ]);
                const ilkName = ethers_1.ethers.utils.parseBytes32String(ilk);
                const address = join.toLowerCase();
                const collateralTokenAddress = gem.toLowerCase();
                return { address, ilkName, collateralTokenAddress };
            })));
            return definitions;
        });
    }
    getTokenDefinitions({ definition, }) {
        return __awaiter(this, void 0, void 0, function* () {
            return [
                {
                    metaType: position_interface_1.MetaType.SUPPLIED,
                    address: definition.collateralTokenAddress,
                    network: this.network,
                },
                {
                    metaType: position_interface_1.MetaType.BORROWED,
                    address: '0x6b175474e89094c44da98b954eedeac495271d0f',
                    network: this.network,
                },
            ];
        });
    }
    getDataProps({ contractPosition, definition, multicall, }) {
        return __awaiter(this, void 0, void 0, function* () {
            const collateralTokenContract = this.contractFactory.erc20({
                address: definition.collateralTokenAddress,
                network: this.network,
            });
            const balanceRaw = yield (definition.collateralTokenAddress === address_1.ZERO_ADDRESS
                ? multicall.wrap(multicall.contract).getEthBalance(definition.address)
                : multicall.wrap(collateralTokenContract).balanceOf(definition.address));
            const collateralToken = contractPosition.tokens[0];
            const balance = Number(balanceRaw) / Math.pow(10, collateralToken.decimals);
            const liquidity = balance * collateralToken.price;
            return { ilkName: definition.ilkName, liquidity };
        });
    }
    getLabel({ contractPosition }) {
        return __awaiter(this, void 0, void 0, function* () {
            return `${contractPosition.dataProps.ilkName} Vault`;
        });
    }
    getTokenBalancesPerPosition(_params) {
        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 positions = yield this.appToolkit.getAppContractPositions({
                appId: this.appId,
                groupIds: [this.groupId],
                network: this.network,
            });
            const proxyRegAddress = '0x4678f0a6958e4d2bc4f1baf7bc52e8f3564f3fe4';
            const proxyRegContract = this.contractFactory.makerProxyRegistry({
                address: proxyRegAddress,
                network: this.network,
            });
            const proxyAddress = yield proxyRegContract.proxies(address);
            if (proxyAddress === address_1.ZERO_ADDRESS)
                return [];
            const cdpManagerAddress = '0x5ef30b9986345249bc32d8928b7ee64de9435e39';
            const cdpManagerContract = this.contractFactory.makerCdpManager({
                address: cdpManagerAddress,
                network: this.network,
            });
            const cdps = [];
            let next = yield cdpManagerContract.first(proxyAddress).then(v => Number(v));
            while (next !== 0) {
                cdps.push(next);
                next = yield cdpManagerContract.list(next).then(v => Number(v.next));
            }
            const allPositions = yield Promise.all(cdps.map((cdp) => __awaiter(this, void 0, void 0, function* () {
                const urn = yield cdpManagerContract.urns(cdp);
                const vatAddress = '0x35d1b3f3d7966a1dfe207aa4514c12a259a0492b';
                const vatContract = this.contractFactory.makerVat({ address: vatAddress, network: this.network });
                const balances = yield Promise.all(positions.map((position) => __awaiter(this, void 0, void 0, function* () {
                    const ilk = ethers_1.ethers.utils.formatBytes32String(position.dataProps.ilkName);
                    const { ink, art } = yield multicall.wrap(vatContract).urns(ilk, urn.toLowerCase());
                    const collateralToken = position.tokens.find(position_utils_1.isSupplied);
                    const debtToken = position.tokens.find(position_utils_1.isBorrowed);
                    if (!collateralToken || !debtToken)
                        return null;
                    const collateralRaw = new bignumber_js_1.default(ink.toString())
                        .div(Math.pow(10, 18))
                        .times(Math.pow(10, collateralToken.decimals))
                        .toFixed(0);
                    const debtRaw = new bignumber_js_1.default(art.toString())
                        .div(Math.pow(10, 18))
                        .times(Math.pow(10, debtToken.decimals))
                        .toFixed(0);
                    const collateral = (0, drill_balance_helper_1.drillBalance)(collateralToken, collateralRaw);
                    const debt = (0, drill_balance_helper_1.drillBalance)(debtToken, debtRaw, { isDebt: true });
                    const tokens = [collateral, debt];
                    const balanceUSD = (0, lodash_1.sumBy)(tokens, v => v.balanceUSD);
                    const cRatio = debt.balanceUSD === 0 ? 0 : (collateral.balanceUSD / Math.abs(debt.balanceUSD)) * 100;
                    const secondaryLabel = `C-Ratio: ${(cRatio * 100).toFixed(2)}%`;
                    const positionBalance = Object.assign(Object.assign({}, position), { tokens,
                        balanceUSD, dataProps: {
                            ilkName: position.dataProps.ilkName,
                            cdpId: cdp,
                            cRatio,
                            liquidity: position.dataProps.liquidity,
                            positionKey: `${cdp}`,
                        }, displayProps: {
                            label: position.displayProps.label,
                            secondaryLabel: secondaryLabel,
                            images: position.displayProps.images,
                        } });
                    positionBalance.key = this.appToolkit.getPositionKey(positionBalance);
                    return positionBalance;
                })));
                return (0, lodash_1.compact)(balances);
            })));
            return (0, lodash_1.compact)(allPositions.flat());
        });
    }
};
EthereumMakerVaultContractPositionFetcher = __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.MakerContractFactory)),
    __metadata("design:paramtypes", [Object, contracts_1.MakerContractFactory])
], EthereumMakerVaultContractPositionFetcher);
exports.EthereumMakerVaultContractPositionFetcher = EthereumMakerVaultContractPositionFetcher;
//# sourceMappingURL=maker.vault.contract-position-fetcher.js.map