import { filter, firstValueFrom } from "rxjs";
import { executeWithSigner } from "../../setup";
import { DmkSignerEth, LegacySignerEth } from "@ledgerhq/live-signer-evm";
import { getEnv } from "@ledgerhq/live-env";
import { Signature } from "ethers";
import resolver from "@ledgerhq/coin-evm/hw-getAddress";
const isDmkTransport = (transport) => {
    return ("dmk" in transport &&
        transport.dmk !== undefined &&
        "sessionId" in transport &&
        transport.sessionId !== undefined);
};
const createLiveSigner = (transport) => {
    if (isDmkTransport(transport)) {
        return new DmkSignerEth(transport.dmk, transport.sessionId);
    }
    return new LegacySignerEth(transport);
};
export const createSigner = (transport) => {
    const signer = createLiveSigner(transport);
    return {
        getAddress: signer.getAddress.bind(signer),
        signTransaction: async (path, tx, domain) => {
            // Configure type of resolutions necessary for the clear signing
            const resolutionConfig = {
                externalPlugins: true,
                erc20: true,
                nft: false,
                uniswapV3: true,
                domains: domain && [domain],
            };
            const loadConfig = {
                cryptoassetsBaseURL: getEnv("DYNAMIC_CAL_BASE_URL"),
                nftExplorerBaseURL: getEnv("NFT_METADATA_SERVICE") + "/v1/ethereum",
            };
            signer.setLoadConfig(loadConfig);
            const observable = signer.clearSignTransaction(path, tx.substring(2), resolutionConfig, true);
            const event = observable.pipe(filter((event) => {
                return event.type === "signer.evm.signed";
            }));
            const { value } = await firstValueFrom(event);
            return Signature.from({
                r: "0x" + value.r,
                s: "0x" + value.s,
                v: typeof value.v === "number" ? value.v : parseInt(value.v, 16),
            }).serialized;
        },
    };
};
export const context = executeWithSigner(createSigner);
export const getAddress = resolver(context);
//# sourceMappingURL=Eth.js.map