"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isEvmNativeSigner = exports.EvmNativeSigner = exports.getEvmSignerForSigner = exports.getEvmSignerForKey = void 0;
const connect_sdk_1 = require("@wormhole-foundation/connect-sdk");
const ethers_1 = require("ethers");
const platform_1 = require("./platform");
const types_1 = require("./types");
// Get a SignOnlySigner for the EVM platform
async function getEvmSignerForKey(rpc, privateKey) {
    const [_, chain] = await platform_1.EvmPlatform.chainFromRpc(rpc);
    const _signer = new ethers_1.ethers.Wallet(privateKey, rpc);
    return getEvmSignerForSigner(chain, _signer);
}
exports.getEvmSignerForKey = getEvmSignerForKey;
// Get a SignOnlySigner for the EVM platform
async function getEvmSignerForSigner(chain, signer) {
    const address = await signer.getAddress();
    return new EvmNativeSigner(chain, address, signer);
}
exports.getEvmSignerForSigner = getEvmSignerForSigner;
class EvmNativeSigner extends connect_sdk_1.PlatformNativeSigner {
    chain() {
        return this._chain;
    }
    address() {
        return this._address;
    }
    async sign(tx) {
        const signed = [];
        let nonce = await this._signer.getNonce();
        // TODO: Better gas estimation/limits
        let gasLimit = 500000n;
        let maxFeePerGas = 1500000000n; // 1.5gwei
        let maxPriorityFeePerGas = 100000000n; // 0.1gwei
        // Celo does not support this call
        if (this.chain() !== 'Celo') {
            const feeData = await this._signer.provider.getFeeData();
            maxFeePerGas = feeData.maxFeePerGas ?? maxFeePerGas;
            maxPriorityFeePerGas =
                feeData.maxPriorityFeePerGas ?? maxPriorityFeePerGas;
        }
        for (const txn of tx) {
            const { transaction, description } = txn;
            console.log(`Signing: ${description} for ${this.address()}`);
            const t = {
                ...transaction,
                ...{
                    gasLimit,
                    maxFeePerGas,
                    maxPriorityFeePerGas,
                    nonce,
                },
            };
            // TODO
            // const estimate = await this.provider.estimateGas(t)
            // t.gasLimit = estimate
            signed.push(await this._signer.signTransaction(t));
            nonce += 1;
        }
        return signed;
    }
}
exports.EvmNativeSigner = EvmNativeSigner;
function isEvmNativeSigner(signer) {
    return ((0, connect_sdk_1.isNativeSigner)(signer) &&
        (0, connect_sdk_1.chainToPlatform)(signer.chain()) === types_1._platform &&
        isEthersSigner(signer.unwrap()));
}
exports.isEvmNativeSigner = isEvmNativeSigner;
function isEthersSigner(thing) {
    return thing instanceof ethers_1.ethers.AbstractSigner;
}
//# sourceMappingURL=signer.js.map