import { AsyncQueue } from './AsyncQueue.js';
import { chainById } from './chains/chains.js';
import { sendTransaction, waitForTransactionReceipt } from '@wagmi/core';
import { createWalletClient, http, zeroAddress, } from 'viem';
export const createTxSenderFromPrivateKeyAccount = (config, account) => {
    const queueByChainId = {};
    config.chains.forEach(chain => {
        queueByChainId[chain.id] = new AsyncQueue(async (tx) => {
            const hash = await sendTransaction(config, {
                chainId: tx.chainId,
                to: tx.to,
                data: tx.data,
                account,
            });
            // Prevent replacement tx.
            await waitForTransactionReceipt(config, {
                hash,
                chainId: tx.chainId,
                pollingInterval: 1000,
            });
            return hash;
        });
    });
    return {
        sendTx: async (tx) => {
            if (!queueByChainId[tx.chainId]) {
                throw new Error(`Chain tx queue for ${tx.chainId} not found`);
            }
            return await queueByChainId[tx.chainId].enqueue(tx);
        },
    };
};
export const createTxSenderFromCustomWalletRpc = (getRpcUrl) => {
    return {
        sendTx: async (tx) => {
            const chain = chainById[tx.chainId];
            if (!chain) {
                throw new Error(`Chain not found for ${tx.chainId}`);
            }
            const walletClient = createWalletClient({
                transport: http(getRpcUrl(tx.chainId)),
            });
            return await walletClient.sendTransaction({
                to: tx.to,
                data: tx.data,
                account: zeroAddress, // will be ignored
                chain: chain,
            });
        },
    };
};
