"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.effectiveValue = effectiveValue;
exports.leafHashes = leafHashes;
exports.paymentsRoot = paymentsRoot;
exports.leavesToTuples = leavesToTuples;
exports.encodeExtensionLeavesV1 = encodeExtensionLeavesV1;
exports.encodeExtensionLeavesV2 = encodeExtensionLeavesV2;
const ethers_1 = require("ethers");
const checkpoint_core_1 = require("@dbis/checkpoint-core");
function effectiveValue(leaf) {
    return (0, checkpoint_core_1.effectiveTokenOrNativeWei)(leaf);
}
function leafHashes(chainId, leaves) {
    return leaves.map((l) => (0, checkpoint_core_1.paymentLeafV1Hash)(chainId, {
        txHash: l.txHash,
        from: l.from,
        to: l.to,
        value: effectiveValue(l),
        blockNumber: l.blockNumber,
        blockTimestamp: l.blockTimestamp,
        gasUsed: l.gasUsed,
        success: l.success,
    }));
}
function paymentsRoot(chainId, leaves) {
    return (0, checkpoint_core_1.buildMerkleRoot)(leafHashes(chainId, leaves));
}
const PAYMENT_LEAF_TUPLE = 'tuple(bytes32,address,address,uint256,uint256,uint64,uint256,bool)';
function leavesToTuples(leaves) {
    return leaves.map((l) => [
        l.txHash,
        l.from,
        l.to,
        effectiveValue(l),
        BigInt(l.blockNumber),
        BigInt(l.blockTimestamp),
        l.gasUsed,
        l.success,
    ]);
}
function encodeExtensionLeavesV1(leaves) {
    return ethers_1.ethers.AbiCoder.defaultAbiCoder().encode([PAYMENT_LEAF_TUPLE + '[]'], [leavesToTuples(leaves)]);
}
function encodeExtensionLeavesV2(leaves) {
    const PAYMENT_LEAF_V2_TUPLE = 'tuple(bytes32,address,address,address,uint256,uint256,uint64,uint256,bool,uint32)';
    const tuples = leaves.map((l) => [
        l.txHash,
        l.from,
        l.to,
        l.token ?? ethers_1.ethers.ZeroAddress,
        effectiveValue(l),
        BigInt(l.blockNumber),
        BigInt(l.blockTimestamp),
        l.gasUsed,
        l.success,
        l.tokenLogIndex ?? 0,
    ]);
    return ethers_1.ethers.AbiCoder.defaultAbiCoder().encode(['bytes1', PAYMENT_LEAF_V2_TUPLE + '[]'], [ethers_1.ethers.toBeHex(0x02, 1), tuples]);
}
