"use strict";
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 });
const bignumber_1 = require("@ethersproject/bignumber");
const bignumber_js_1 = __importDefault(require("bignumber.js"));
const currency_1 = __importDefault(require("../currency"));
const web_1 = require("arbundles/web");
const ethereumSigner = web_1.InjectedTypedEthereumSigner;
class EthereumConfig extends currency_1.default {
    constructor(config) {
        super(config);
        this.inheritsRPC = true;
        this.base = ["wei", 1e18];
    }
    getTx(txId) {
        return __awaiter(this, void 0, void 0, function* () {
            const provider = this.providerInstance;
            const response = yield provider.getTransaction(txId);
            if (!response)
                throw new Error("Tx doesn't exist");
            if (!response.to)
                throw new Error(`Unable to resolve transactions ${txId} receiver`);
            return {
                from: response.from,
                to: response.to,
                blockHeight: response.blockNumber ? new bignumber_js_1.default(response.blockNumber) : undefined,
                amount: new bignumber_js_1.default(response.value.toHexString(), 16),
                pending: response.blockNumber ? false : true,
                confirmed: response.confirmations >= this.minConfirm,
            };
        });
    }
    ownerToAddress(owner) {
        // return (
        //   "0x" +
        //   keccak256(Buffer.from(owner.slice(1)))
        //     .slice(-20)
        //     .toString("hex")
        // );
        // return owner;
        return owner.toString().toLowerCase();
    }
    sign(data) {
        return __awaiter(this, void 0, void 0, function* () {
            const signer = yield this.getSigner();
            return signer.sign(data);
        });
    }
    getSigner() {
        if (!this.signer) {
            this.signer = new web_1.InjectedTypedEthereumSigner(this.wallet);
        }
        return this.signer;
    }
    verify(pub, data, signature) {
        return __awaiter(this, void 0, void 0, function* () {
            return ethereumSigner.verify(pub, data, signature);
        });
    }
    getCurrentHeight() {
        return __awaiter(this, void 0, void 0, function* () {
            const provider = this.providerInstance;
            const response = yield provider.send("eth_blockNumber", []);
            return new bignumber_js_1.default(response, 16);
        });
    }
    getFee(amount, to) {
        return __awaiter(this, void 0, void 0, function* () {
            const provider = this.providerInstance;
            const tx = {
                to,
                from: this.address,
                value: "0x" + new bignumber_js_1.default(amount).toString(16),
            };
            const estimatedGas = yield provider.estimateGas(tx);
            const gasPrice = yield provider.getGasPrice();
            return new bignumber_js_1.default(estimatedGas.mul(gasPrice).toString());
        });
    }
    sendTx(data) {
        return __awaiter(this, void 0, void 0, function* () {
            const signer = this.w3signer;
            const receipt = yield signer.sendTransaction(data); // .catch((e) => { console.error(`Sending tx: ${e}`) })
            return receipt ? receipt.hash : undefined;
        });
    }
    createTx(amount, to, _fee) {
        return __awaiter(this, void 0, void 0, function* () {
            const amountc = bignumber_1.BigNumber.from(new bignumber_js_1.default(amount).toFixed());
            const signer = this.w3signer;
            const estimatedGas = yield signer.estimateGas({ to, from: this.address, value: amountc.toHexString() });
            let gasPrice = yield signer.getGasPrice();
            if (this.name === "matic") {
                gasPrice = bignumber_1.BigNumber.from(new bignumber_js_1.default(gasPrice.toString()).multipliedBy(10).decimalPlaces(0).toString());
            }
            const txr = yield signer.populateTransaction({ to, from: this.address, value: amountc.toHexString(), gasPrice, gasLimit: estimatedGas });
            return { txId: undefined, tx: txr };
        });
    }
    getPublicKey() {
        return __awaiter(this, void 0, void 0, function* () {
            return this.address;
        });
    }
    ready() {
        var _a, _b;
        return __awaiter(this, void 0, void 0, function* () {
            this.w3signer = yield this.wallet.getSigner();
            this._address = (yield this.w3signer.getAddress()).toLowerCase();
            yield this.getSigner().ready();
            // this.providerInstance = new .JsonRpcProvider(this.providerUrl);
            this.providerInstance = this.wallet;
            yield ((_b = (_a = this.providerInstance) === null || _a === void 0 ? void 0 : _a._ready) === null || _b === void 0 ? void 0 : _b.call(_a));
        });
    }
}
exports.default = EthereumConfig;
//# sourceMappingURL=ethereum.js.map