"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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TokenManager = void 0;
const LSAN_json_1 = require("@logsn/contracts/artifacts/src/alpha/Token.sol/LSAN.json");
const shared_1 = require("@logsn/shared");
const utils_1 = require("@streamr/utils");
const decimal_js_1 = __importDefault(require("decimal.js"));
const tsyringe_1 = require("tsyringe");
const Config_1 = require("../Config");
const Ethereum_1 = require("../Ethereum");
const Authentication_1 = require("../streamr/Authentication");
const Config_2 = require("../streamr/Config");
const ContractFactory_1 = require("../streamr/ContractFactory");
const LoggerFactory_1 = require("../streamr/LoggerFactory");
const contract_1 = require("../streamr/utils/contract");
let TokenManager = class TokenManager {
    constructor(contractFactory, loggerFactory, authentication, logStoreClientConfig, streamrClientConfig) {
        this.contractFactory = contractFactory;
        this.logStoreClientConfig = logStoreClientConfig;
        this.streamrClientConfig = streamrClientConfig;
        this.logger = loggerFactory.createLogger(module);
        this.authentication = authentication;
        this.logstoreTokenManagerContractsReadonly =
            (0, Ethereum_1.getStreamRegistryChainProviders)(this.streamrClientConfig).map((provider) => {
                this.logger.debug('provider: ' + provider);
                const tokenManagerAddress = (0, utils_1.toEthereumAddress)(this.logStoreClientConfig.contracts.logStoreTokenManagerChainAddress);
                this.logger.debug('tokenManagerAddress: ' + tokenManagerAddress);
                return this.contractFactory.createReadContract(tokenManagerAddress, LSAN_json_1.abi, provider, 'logStoreTokenManager');
            });
    }
    async connectToContract() {
        if (!this.logStoreTokenManagerContract) {
            const chainSigner = await this.authentication.getStreamRegistryChainSigner();
            this.logStoreTokenManagerContract =
                this.contractFactory.createWriteContract((0, utils_1.toEthereumAddress)(this.logStoreClientConfig.contracts.logStoreTokenManagerChainAddress), LSAN_json_1.abi, chainSigner, 'LSAN');
        }
    }
    async getBalance() {
        return (0, contract_1.queryAllReadonlyContracts)(async (contract) => {
            const accountAddress = await this.authentication.getAddress();
            this.logger.debug(`getBalance of current account: ${accountAddress}`);
            const balance = await contract
                .balanceOf(accountAddress)
                .then((b) => b.toBigInt());
            this.logger.debug(`got balance of ${accountAddress}: ${balance}`);
            return balance;
        }, this.logstoreTokenManagerContractsReadonly);
    }
    async getPrice() {
        return (0, contract_1.queryAllReadonlyContracts)(async (contract) => {
            this.logger.debug('getPrice');
            const priceBN = await contract.price();
            return priceBN.toBigInt();
        }, this.logstoreTokenManagerContractsReadonly);
    }
    async mint(amount, overrides) {
        this.logger.debug('mint amount: ' + amount);
        await this.connectToContract();
        const mergedOverrides = {
            ...(0, Ethereum_1.getStreamRegistryOverrides)(this.streamrClientConfig),
            ...overrides,
        };
        return this.logStoreTokenManagerContract.mint({
            value: amount,
            ...mergedOverrides,
        });
    }
    /**
     * Helper to get correct amount of tokens in desired currency
     */
    async convert({ to, amount, from, }) {
        this.logger.debug(`convert amount ${amount} from ${from} to ${to}`);
        const getWeiPerUsd = async () => {
            const usdPerMatic = await (0, shared_1.getMaticPrice)(new Date().getTime());
            const usdPerWei = new decimal_js_1.default(usdPerMatic).mul('1e-18');
            return usdPerWei.pow(-1);
        };
        const getWeiPerByte = async () => {
            const weiPerByte = await (0, contract_1.queryAllReadonlyContracts)((contract) => {
                return contract.price();
            }, this.logstoreTokenManagerContractsReadonly);
            return new decimal_js_1.default(weiPerByte.toString());
        };
        const getRatesToWei = {
            wei: () => new decimal_js_1.default(1),
            usd: getWeiPerUsd,
            bytes: getWeiPerByte,
        };
        const outputDecimals = {
            wei: 0,
            usd: 18,
            bytes: 0,
        };
        const result = new decimal_js_1.default(amount.toString())
            .mul(await getRatesToWei[from]())
            .div(await getRatesToWei[to]())
            .toDP(outputDecimals[to], decimal_js_1.default.ROUND_DOWN);
        return result.toString();
    }
};
exports.TokenManager = TokenManager;
exports.TokenManager = TokenManager = __decorate([
    (0, tsyringe_1.scoped)(tsyringe_1.Lifecycle.ContainerScoped),
    __param(0, (0, tsyringe_1.inject)(ContractFactory_1.ContractFactoryInjectionToken)),
    __param(1, (0, tsyringe_1.inject)(LoggerFactory_1.LoggerFactoryInjectionToken)),
    __param(2, (0, tsyringe_1.inject)(Authentication_1.AuthenticationInjectionToken)),
    __param(3, (0, tsyringe_1.inject)(Config_1.LogStoreClientConfigInjectionToken)),
    __param(4, (0, tsyringe_1.inject)(Config_2.StreamrClientConfigInjectionToken)),
    __metadata("design:paramtypes", [Object, Object, Object, Object, Object])
], TokenManager);
//# sourceMappingURL=TokenManager.js.map