"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const crypto_browserify_1 = require("crypto-browserify");
/**
 * Instance with basic information
 */
class Instance {
    constructor(init) {
        this.id = init.id;
        this.contractID = init.contractID;
        this.darcID = init.darcID;
        this.data = init.data;
    }
    /**
     * Create an instance from a proof
     * @param id the instance-id to extract
     * @param p The proof
     * @returns the instance
     */
    static fromProof(id, p) {
        if (!p.exists(id)) {
            throw new Error(`key not in proof: ${id.toString("hex")}`);
        }
        return new Instance({ id, contractID: p.contractID, darcID: p.darcID, data: p.value });
    }
    /**
     * Create an instance after requesting its proof to byzcoin
     * @param rpc   The RPC to use
     * @param iid    The ID of the instance
     * @param waitMatch how many times to wait for a match - useful if its called just after an addTransactionAndWait.
     * @param interval how long to wait between two attempts in waitMatch.
     * @returns the instance if it exists
     */
    static fromByzcoin(rpc, iid, waitMatch = 0, interval = 1000) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const p = yield rpc.getProofFromLatest(iid, waitMatch, interval);
            return Instance.fromProof(iid, p);
        });
    }
    /**
     * Returns an instance from a previously toBytes() call.
     * @param buf
     */
    static fromBytes(buf) {
        const obj = JSON.parse(buf.toString());
        return new Instance({
            contractID: obj.contractID,
            darcID: Buffer.from(obj.darcID),
            data: Buffer.from(obj.data),
            id: Buffer.from(obj.id),
        });
    }
    /**
     * Returns the instanceID given a contract and a preID
     * @param contractID
     * @param preID
     */
    static calcInstID(contractID, preID) {
        const h = crypto_browserify_1.createHash("sha256");
        h.update(contractID);
        h.update(preID);
        return h.digest();
    }
    /**
     * Returns a byte representation of the Instance.
     */
    toBytes() {
        return Buffer.from(JSON.stringify(new Instance(this)));
    }
}
exports.default = Instance;
