"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.encodeFingerprintPreimage = exports.parseStatus = exports.channelDataToStatus = void 0;
var ethers_1 = require("ethers");
var outcome_1 = require("./outcome");
var state_1 = require("./state");
var FINGERPRINT_PREIMAGE_TYPE = "tuple(\n  bytes32 stateHash,\n  address challengerAddress,\n  bytes32 outcomeHash\n)";
function channelDataToStatus(channelData) {
    var turnNumRecord = channelData.turnNumRecord, finalizesAt = channelData.finalizesAt;
    var hash = ethers_1.utils.keccak256(encodeFingerprintPreimage(channelData));
    var fingerprint = ethers_1.utils.hexDataSlice(hash, 12);
    var status = '0x' +
        ethers_1.utils.hexZeroPad(ethers_1.utils.hexlify(turnNumRecord), 6).slice(2) +
        ethers_1.utils.hexZeroPad(ethers_1.utils.hexlify(finalizesAt), 6).slice(2) +
        fingerprint.slice(2);
    return status;
}
exports.channelDataToStatus = channelDataToStatus;
function parseStatus(status) {
    validateHexString(status);
    var cursor = 2;
    var turnNumRecord = '0x' + status.slice(cursor, (cursor += 12));
    var finalizesAt = '0x' + status.slice(cursor, (cursor += 12));
    var fingerprint = '0x' + status.slice(cursor);
    return {
        turnNumRecord: asNumber(turnNumRecord),
        finalizesAt: asNumber(finalizesAt),
        fingerprint: fingerprint,
    };
}
exports.parseStatus = parseStatus;
var asNumber = function (s) { return ethers_1.BigNumber.from(s).toNumber(); };
function getFingerprintPreimage(_a) {
    var finalizesAt = _a.finalizesAt, state = _a.state, challengerAddress = _a.challengerAddress, outcome = _a.outcome;
    var isOpen = finalizesAt === 0;
    if (isOpen && (outcome || state || challengerAddress)) {
        console.warn("Invalid open channel storage: " + JSON.stringify(outcome || state || challengerAddress));
    }
    var stateHash = isOpen || !state ? ethers_1.constants.HashZero : state_1.hashState(state);
    var outcomeHash = isOpen || !outcome ? ethers_1.constants.HashZero : outcome_1.hashOutcome(outcome);
    challengerAddress = challengerAddress || ethers_1.constants.AddressZero;
    return { stateHash: stateHash, challengerAddress: challengerAddress, outcomeHash: outcomeHash };
}
function encodeFingerprintPreimage(data) {
    return ethers_1.utils.defaultAbiCoder.encode([FINGERPRINT_PREIMAGE_TYPE], [getFingerprintPreimage(data)]);
}
exports.encodeFingerprintPreimage = encodeFingerprintPreimage;
function validateHexString(hexString) {
    if (!ethers_1.utils.isHexString(hexString)) {
        throw new Error("Not a hex string: " + hexString);
    }
    if (hexString.length !== 66) {
        throw new Error("Incorrect length: " + hexString.length);
    }
}
//# sourceMappingURL=channel-storage.js.map