import { readFile } from 'node:fs/promises';
import { concat, getContractAddress, sliceHex, } from 'viem';
import { getTransactionCount, waitForTransactionReceipt } from 'viem/actions';
export async function deployArtifact(walletClient, options) {
    const artifact = JSON.parse(await readFile(options.file, 'utf8'));
    let bytecode;
    let linkReferences;
    if ('linkReferences' in artifact) {
        bytecode = artifact.bytecode;
        linkReferences = artifact.linkReferences;
    }
    else {
        bytecode = artifact.bytecode.object;
        linkReferences = artifact.bytecode.linkReferences;
    }
    for (const ref of Object.values(linkReferences)) {
        for (const [name, places] of Object.entries(ref)) {
            const address = options.libs?.[name];
            if (!address)
                throw new Error(`expected library: ${name}`);
            for (const { start, length } of places) {
                bytecode = concat([
                    sliceHex(bytecode, 0, start),
                    address,
                    sliceHex(bytecode, start + length),
                ]);
            }
        }
    }
    const nonce = BigInt(await getTransactionCount(walletClient, walletClient.account));
    const hash = await walletClient.deployContract({
        abi: artifact.abi,
        bytecode,
        args: options.args,
    });
    await waitForTransactionReceipt(walletClient, { hash });
    return getContractAddress({
        from: walletClient.account.address,
        nonce,
    });
}
