"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.prepareDataSignatureParameters = prepareDataSignatureParameters;
exports.getSignatureParameters = getSignatureParameters;
exports.rebuildSignature = rebuildSignature;
const bytes_1 = require("@ethersproject/bytes");
const bignumber_1 = require("@ethersproject/bignumber");
function prepareDataSignatureParameters(args) {
    return __awaiter(this, void 0, void 0, function* () {
        const domainType = [
            { name: "name", type: "string" },
            { name: "version", type: "string" },
            { name: "verifyingContract", type: "address" },
            { name: "salt", type: "bytes32" }
        ];
        const domainData = Object.assign({ name: "Boson Protocol", version: "V2", verifyingContract: args.verifyingContractAddress, salt: (0, bytes_1.hexZeroPad)(bignumber_1.BigNumber.from(args.chainId).toHexString(), 32) }, args.customDomainData);
        Object.keys(domainData).forEach((key) => {
            if (domainData[key] === undefined) {
                delete domainData[key];
            }
        });
        const signatureTypes = Object.assign({ EIP712Domain: domainType }, args.customSignatureType);
        const structuredDataToSign = {
            types: signatureTypes,
            domain: domainData,
            primaryType: args.primaryType,
            message: args.message
        };
        if (args.returnTypedDataToSign) {
            return structuredDataToSign; // Return the raw EIP-712 data
        }
        const dataToSign = JSON.stringify(structuredDataToSign);
        const signerAddress = yield args.web3Lib.getSignerAddress();
        const signature = yield args.web3Lib.send("eth_signTypedData_v4", [
            signerAddress,
            dataToSign
        ]);
        return getSignatureParameters(signature);
    });
}
function getSignatureParameters(signature) {
    if (!(0, bytes_1.isHexString)(signature)) {
        throw new Error(`Value "${signature}" is not a valid hex string`);
    }
    const _signature = signature.substring(2);
    const r = "0x" + _signature.substring(0, 64);
    const s = "0x" + _signature.substring(64, 128);
    let v = parseInt(_signature.substring(128, 130), 16);
    if (!isNaN(v) && v < 2) {
        // support Ledger signature
        v = v + 27;
    }
    return {
        r,
        s,
        v,
        signature
    };
}
function rebuildSignature({ r, s, v }) {
    if (!(0, bytes_1.isHexString)(r) || !(0, bytes_1.isHexString)(s)) {
        throw new Error("r and s must be valid hex strings");
    }
    // Remove '0x' prefix if present
    const rValue = r.startsWith("0x") ? r.substring(2) : r;
    const sValue = s.startsWith("0x") ? s.substring(2) : s;
    // Convert v to two digit hex, handle Ledger signature conversion
    const vValue = v.toString(16).padStart(2, "0");
    // Concatenate the signature parts
    return "0x" + rValue + sValue + vValue;
}
//# sourceMappingURL=signature.js.map