"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.HiddenHandRewardsResolver = exports.REWARD_DISTRIBUTOR = exports.PROTOCOLS = exports.BASE_URL = void 0;
const common_1 = require("@nestjs/common");
const axios_1 = __importDefault(require("axios"));
const ethers_1 = require("ethers");
const app_toolkit_interface_1 = require("../../../app-toolkit/app-toolkit.interface");
const cache_decorator_1 = require("../../../cache/cache.decorator");
const _types_1 = require("../../../types");
const contracts_1 = require("../contracts");
exports.BASE_URL = 'https://api.github.com/repositories/601325176/contents/hidden-hand';
exports.PROTOCOLS = {
    [_types_1.Network.ETHEREUM_MAINNET]: {
        aura: { hash: '0x5e51a542c76cdda7bcb5d69b1e2bf07c1a998341e5beb4af3c5b69c005b70825', name: 'Aura Market', address: '0x642c59937a62cf7dc92f70fd78a13cee0aa2bd9c' },
        balancer: { hash: '0xb774acb85c844ceba5af7a7d2c1ae87bec3d9ae928aa7bb14ad9ece203e2880e', name: 'Balancer Market', address: '0x7cdf753b45ab0729bcfe33dc12401e55d28308a9' },
        bunni: { hash: '0x8a75c3397e6ffb49519b2146b302b17c035c5ddb56f68f446d4e9d783b627b59', name: 'Bunni Market', address: '0x78c45fbdb71e7c0fbdfe49bdefdacdcc4764336f' },
        floordao: { hash: '0xea125272d66c2905372eb5bb67f587bb1326982b752406b04f21eab88014eb5e', name: 'FloorDao Market', address: '0x20c0d06626e8b0c9f423e7f2abe26fde1910fd8c' },
        frax: { hash: '0x84f1507b912f1235ce5c9c3679acf3fc7c4d23e0bf12df6a77b304487f1be36f', name: 'Frax Market', address: '0x123683885310851ca29e83ae3ff3e2490d4420cd' },
        idlefinance: { hash: '0x2c3e88884f3181f0d8bf3fa7cc2bd22a2d1738474ad18a37b3f278e23ca9bddd', name: 'Idlefinance Market', address: '0xfe01f497552f7aef64112cf3082385eb876697ae' },
        ribbon: { hash: '0x988d53da848cb078e69126eb281e9ee771e8d4a96ff13be429f95d50b37ac195', name: 'Ribbon Market', address: '0xdc9e0f10671660148bc71c36a38647470c8f9939' },
        saddle: { hash: '0xc1e7f5e342317dd9db36fe2a84a5218b1dbbc1357eb3d71a8e20c32aa73ce43c', name: 'Saddle Market', address: '0x13aebf77f51fa3d3c091d2ab5e1a736aeb6551f9' },
        tokemak: { hash: '0x58f03fb76e1ff5dff3ee4fd620e274794abedbf6393dc5900fbee85f701a3705', name: 'Tokemak Market', address: '0x7816b3d0935d668bcfc9a4aab5a84ebc7ff320cf' },
    },
    [_types_1.Network.OPTIMISM_MAINNET]: {
        aura: { hash: '0x5e51a542c76cdda7bcb5d69b1e2bf07c1a998341e5beb4af3c5b69c005b70825', name: 'Aura Market', address: '0x054d189225e66438a4d88441507cfa3193fa34a2' },
    },
};
exports.REWARD_DISTRIBUTOR = {
    [_types_1.Network.ETHEREUM_MAINNET]: '0x0b139682d5c9df3e735063f46fb98c689540cf3a',
    [_types_1.Network.OPTIMISM_MAINNET]: '0x0b139682d5c9df3e735063f46fb98c689540cf3a',
};
let HiddenHandRewardsResolver = class HiddenHandRewardsResolver {
    constructor(appToolkit, contractFactory) {
        this.appToolkit = appToolkit;
        this.contractFactory = contractFactory;
    }
    getRawData() {
        return __awaiter(this, void 0, void 0, function* () {
            const response = yield axios_1.default.get(exports.BASE_URL);
            const markets = response.data.filter((d) => d.type === 'dir');
            const tokenRewards = {};
            for (const market of markets) {
                if (!tokenRewards[market.name]) {
                    tokenRewards[market.name] = {};
                }
                const networksResponse = yield axios_1.default.get(market.url);
                const networks = networksResponse.data;
                for (const network of networks) {
                    const networkName = network.name;
                    const url = network.url.split('?')[0];
                    const filesResponse = yield axios_1.default.get(`${url}/latest`);
                    const tokens = filesResponse.data.filter(file => file.type === 'file');
                    if (!tokenRewards[market.name][networkName]) {
                        tokenRewards[market.name][networkName] = {};
                    }
                    for (const token of tokens) {
                        const tokenAddress = token.name.split('.')[0];
                        const tokenDistribution = yield axios_1.default.get(token.download_url);
                        if (!tokenRewards[market.name][networkName]) {
                            tokenRewards[market.name][networkName] = {};
                        }
                        tokenRewards[market.name][networkName][tokenAddress] = tokenDistribution.data;
                    }
                }
            }
            return tokenRewards;
        });
    }
    getData() {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.getRawData();
        });
    }
    getClaimableDistribution(address, network) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            const claimableDistribution = {};
            const distribution = yield this.getTotalRewards(address, network);
            const networkId = _types_1.NETWORK_IDS[network] || '';
            for (const market in distribution) {
                const protocol = (_a = exports.PROTOCOLS[network]) === null || _a === void 0 ? void 0 : _a[market];
                if (!protocol)
                    continue;
                for (const token in distribution[market][networkId]) {
                    const rewards = distribution[market][networkId][token];
                    const rewardIdentifier = ethers_1.ethers.utils.solidityKeccak256(['bytes32', 'address'], [protocol.hash, token]);
                    const claimedAmount = yield this.getClaimedRewards(address, rewardIdentifier, network);
                    const netRewards = rewards.map(reward => {
                        const netAmount = ethers_1.BigNumber.from(reward.amount).sub(claimedAmount).toString();
                        return Object.assign(Object.assign({}, reward), { amount: netAmount });
                    });
                    if (!claimableDistribution[market]) {
                        claimableDistribution[market] = {};
                    }
                    if (!claimableDistribution[market][networkId]) {
                        claimableDistribution[market][networkId] = {};
                    }
                    claimableDistribution[market][networkId][token] = netRewards;
                }
            }
            return claimableDistribution;
        });
    }
    getTotalRewards(address, network) {
        return __awaiter(this, void 0, void 0, function* () {
            const distribution = yield this.getRawData();
            const filteredDistribution = {};
            const networkId = _types_1.NETWORK_IDS[network] || '';
            for (const market in distribution) {
                const filteredMarket = {};
                for (const tokenAddress in distribution[market][networkId]) {
                    const rewards = distribution[market][networkId][tokenAddress];
                    const filteredRewards = rewards.filter(reward => reward.account === address);
                    if (filteredRewards.length > 0) {
                        filteredMarket[tokenAddress] = filteredRewards;
                    }
                }
                if (Object.keys(filteredMarket).length > 0) {
                    if (!filteredDistribution[market]) {
                        filteredDistribution[market] = {};
                    }
                    filteredDistribution[market][networkId] = filteredMarket;
                }
            }
            return filteredDistribution;
        });
    }
    getClaimedRewards(address, rewardsIdentifier, network) {
        return __awaiter(this, void 0, void 0, function* () {
            const distributor = exports.REWARD_DISTRIBUTOR[network] || '';
            const contract = this.contractFactory.hiddenHandRewardDistributor({ address: distributor, network });
            try {
                const claimedAmount = yield contract.claimed(rewardsIdentifier, address);
                return claimedAmount;
            }
            catch (error) {
                console.log(error);
                return ethers_1.BigNumber.from(0);
            }
        });
    }
};
__decorate([
    (0, cache_decorator_1.Cache)({
        key: `studio:hidden-hand:claimable-raw-data`,
        ttl: 60 * 60 * 24,
    }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Promise)
], HiddenHandRewardsResolver.prototype, "getRawData", null);
HiddenHandRewardsResolver = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, common_1.Inject)(app_toolkit_interface_1.APP_TOOLKIT)),
    __param(1, (0, common_1.Inject)(contracts_1.HiddenHandContractFactory)),
    __metadata("design:paramtypes", [Object, contracts_1.HiddenHandContractFactory])
], HiddenHandRewardsResolver);
exports.HiddenHandRewardsResolver = HiddenHandRewardsResolver;
//# sourceMappingURL=hidden-hand.rewards-resolver.js.map