import { PlatformNativeSigner, chainToPlatform, isNativeSigner, } from '@wormhole-foundation/connect-sdk';
import { ethers } from 'ethers';
import { EvmPlatform } from './platform';
import { _platform } from './types';
// Get a SignOnlySigner for the EVM platform
export async function getEvmSignerForKey(rpc, privateKey) {
    const [_, chain] = await EvmPlatform.chainFromRpc(rpc);
    const _signer = new ethers.Wallet(privateKey, rpc);
    return getEvmSignerForSigner(chain, _signer);
}
// Get a SignOnlySigner for the EVM platform
export async function getEvmSignerForSigner(chain, signer) {
    const address = await signer.getAddress();
    return new EvmNativeSigner(chain, address, signer);
}
export class EvmNativeSigner extends 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;
    }
}
export function isEvmNativeSigner(signer) {
    return (isNativeSigner(signer) &&
        chainToPlatform(signer.chain()) === _platform &&
        isEthersSigner(signer.unwrap()));
}
function isEthersSigner(thing) {
    return thing instanceof ethers.AbstractSigner;
}
//# sourceMappingURL=signer.js.map