import { BinaryRepository } from "@lodestar/db";
import { bytesToInt, toHex } from "@lodestar/utils";
import { Bucket, getBucketNameByValue } from "../buckets.js";
import { getRootIndex, getRootIndexKey, storeRootIndex } from "./stateArchiveIndex.js";
export class StateArchiveRepository extends BinaryRepository {
    constructor(config, db) {
        const bucket = Bucket.allForks_stateArchive;
        super(config, db, bucket, getBucketNameByValue(bucket));
    }
    // Handle key as slot
    async put(key, value) {
        await Promise.all([super.putBinary(key, value.serialize()), storeRootIndex(this.db, key, value.hashTreeRoot())]);
    }
    decodeKey(data) {
        return bytesToInt(super.decodeKey(data), "be");
    }
    // Index Root -> Slot
    async getBinaryByRoot(stateRoot) {
        const slot = await this.getSlotByRoot(stateRoot);
        if (slot !== null && Number.isInteger(slot)) {
            return this.getBinary(slot);
        }
        return null;
    }
    async dumpRootIndexEntries() {
        const entries = await this.db.entries({
            lte: getRootIndexKey(Buffer.alloc(32, 0xff)),
            gte: getRootIndexKey(Buffer.alloc(32, 0x00)),
            bucketId: this.bucketId,
        });
        return entries.map((entry) => ({
            root: toHex(entry.key),
            slot: bytesToInt(entry.value, "be"),
        }));
    }
    async getSlotByRoot(root) {
        const value = await getRootIndex(this.db, root);
        return value && bytesToInt(value, "be");
    }
}
//# sourceMappingURL=stateArchive.js.map