"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.recordIsoAttestationBatch = recordIsoAttestationBatch;
const ethers_1 = require("ethers");
const checkpoint_core_1 = require("@dbis/checkpoint-core");
const leafCodec_1 = require("./leafCodec");
const REGISTRY_V2_ABI = [
    'function recordBatch(uint64 batchId, tuple(bytes32 txHash,address from,address to,uint256 valueWei,uint256 blockNumber138,uint64 blockTimestamp138,uint64 valueUsdE8,uint32 logCount,bytes32 receiptHash,bytes32 instructionId,bytes32 endToEndIdHash,bytes32 uetr,bytes32 payloadHash,uint8 msgTypeCode,bytes32 debtorRefHash,bytes32 creditorRefHash,bytes32 purposeHash)[] records) external',
    'function recorded(bytes32) view returns (bool)',
];
function isoRecord(leaf, iso) {
    const usd = leaf.totalTransfersUsd ?? leaf.valueUsd ?? leaf.nativeValueUsd ?? '0';
    return {
        txHash: leaf.txHash,
        from: leaf.from,
        to: leaf.to,
        valueWei: (0, leafCodec_1.effectiveValue)(leaf),
        blockNumber138: BigInt(leaf.blockNumber),
        blockTimestamp138: BigInt(leaf.blockTimestamp),
        valueUsdE8: (0, checkpoint_core_1.usdStringToE8)(usd),
        logCount: leaf.logCount ?? 0,
        receiptHash: leaf.receiptHash ?? ethers_1.ethers.ZeroHash,
        instructionId: iso.instructionIdBytes32,
        endToEndIdHash: iso.endToEndIdHash,
        uetr: iso.uetrBytes32,
        payloadHash: iso.payloadHash,
        msgTypeCode: iso.msgTypeCode,
        debtorRefHash: iso.debtorRefHash,
        creditorRefHash: iso.creditorRefHash,
        purposeHash: iso.purposeHash,
    };
}
async function recordIsoAttestationBatch(wallet, registryV2Address, batchId, leaves) {
    if (!registryV2Address || leaves.length === 0)
        return null;
    const registry = new ethers_1.ethers.Contract(registryV2Address, REGISTRY_V2_ABI, wallet);
    const pending = [];
    for (const leaf of leaves) {
        if (!leaf.txHash)
            continue;
        try {
            if (await registry.recorded(leaf.txHash))
                continue;
        }
        catch {
            /* continue */
        }
        const iso = leaf.iso20022 ?? (0, checkpoint_core_1.mapPaymentLeafToCanonical)(leaf);
        pending.push({ leaf, iso });
    }
    if (pending.length === 0)
        return null;
    const records = pending.map(({ leaf, iso }) => isoRecord(leaf, iso));
    const tx = await registry.recordBatch(batchId, records, { gasLimit: 3500000n });
    await tx.wait();
    return tx.hash;
}
