"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.claimClassicTicker = exports.prepareClaimClassicTicker = void 0;
const util_1 = require("@polkadot/util");
const eth_sig_util_1 = require("eth-sig-util");
const internal_1 = require("../../internal");
const types_1 = require("../../types");
const constants_1 = require("../../utils/constants");
const conversion_1 = require("../../utils/conversion");
/**
 * @hidden
 * Generate the message a classic user has to sign to claim their ticker. This is used to validate
 *   if the DID that is claiming the ticker in Polymesh is the actual owner of the ticker in Ethereum. The message format is
 *   `classic_claim` followed by the DID in hex format (stripped of the leading 0x). So, if the DID is
 *   `0x1230000000000000000000000000000000000000000000000000000000000000`, the message will be
 *   `classic_claim1230000000000000000000000000000000000000000000000000000000000000`
 */
function generateClassicSigneableMessage(did) {
    const strippedDid = did.replace('0x', '');
    return util_1.stringToHex(`${constants_1.CLASSIC_CLAIM_SIGNATURE_PREFIX}${strippedDid}`);
}
/**
 * @hidden
 */
function prepareClaimClassicTicker(args) {
    return __awaiter(this, void 0, void 0, function* () {
        const { context: { polymeshApi: { tx, query: { asset }, }, }, context, } = this;
        const { ticker, ethereumSignature } = args;
        const rawTicker = conversion_1.stringToTicker(ticker, context);
        const [classicReservation, { expiry, owner: reservationOwner }, { did }] = yield Promise.all([
            asset.classicTickers(rawTicker),
            asset.tickers(rawTicker),
            context.getCurrentIdentity(),
        ]);
        if (classicReservation.isNone) {
            throw new internal_1.PolymeshError({
                code: types_1.ErrorCode.UnmetPrerequisite,
                message: 'The supplied ticker is not in the reserved classic ticker list',
            });
        }
        const reservationExpired = expiry.isSome && conversion_1.momentToDate(expiry.unwrap()) < new Date();
        if (reservationExpired) {
            throw new internal_1.PolymeshError({
                code: types_1.ErrorCode.UnmetPrerequisite,
                message: "The Ticker's claiming period has already expired",
            });
        }
        const ownerDid = conversion_1.identityIdToString(reservationOwner);
        if (ownerDid !== constants_1.CLASSIC_TICKER_OWNER_DID) {
            throw new internal_1.PolymeshError({
                code: types_1.ErrorCode.UnmetPrerequisite,
                message: 'Ticker already claimed',
                data: {
                    ownerDid,
                },
            });
        }
        const { eth_owner: ethOwner } = classicReservation.unwrap();
        let signerAddress;
        try {
            signerAddress = eth_sig_util_1.recoverPersonalSignature({
                data: generateClassicSigneableMessage(did),
                sig: ethereumSignature,
            }).toLowerCase();
        }
        catch (err) {
            throw new internal_1.PolymeshError({
                code: types_1.ErrorCode.ValidationError,
                message: 'Ethereum signature not valid',
                data: {
                    error: err.message,
                },
            });
        }
        if (signerAddress !== util_1.u8aToString(ethOwner).toLowerCase()) {
            throw new internal_1.PolymeshError({
                code: types_1.ErrorCode.UnmetPrerequisite,
                message: 'The account that signed the message is not the classic Ticker owner',
                data: {
                    signerAddress,
                },
            });
        }
        this.addTransaction(tx.asset.claimClassicTicker, {}, rawTicker, conversion_1.stringToEcdsaSignature(ethereumSignature, context));
        return new internal_1.TickerReservation({ ticker }, context);
    });
}
exports.prepareClaimClassicTicker = prepareClaimClassicTicker;
/**
 * @hidden
 */
const claimClassicTicker = () => new internal_1.Procedure(prepareClaimClassicTicker, {
    permissions: {
        tokens: [],
        transactions: [types_1.TxTags.asset.ClaimClassicTicker],
        portfolios: [],
    },
});
exports.claimClassicTicker = claimClassicTicker;
//# sourceMappingURL=claimClassicTicker.js.map