"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getAuthorizedTradingKeysMetadata = exports.getAuthorizeNewTradingKeyArguments = exports.createNewRandomChainWallet = void 0;
const encoding_1 = require("@cosmjs/encoding");
const tendermint_rpc_1 = require("@cosmjs/tendermint-rpc");
const bip39_1 = require("@scure/bip39");
const english_1 = require("@scure/bip39/wordlists/english");
const constants_1 = require("../clients/constants");
const local_wallet_1 = __importDefault(require("../clients/modules/local-wallet"));
const constants_2 = require("./constants");
const onboarding_1 = require("./onboarding");
const createNewRandomChainWallet = async () => {
    const mnemonic = (0, bip39_1.generateMnemonic)(english_1.wordlist, 128);
    const { privateKey: privateKeyRaw } = (0, onboarding_1.deriveHDKeyFromMnemonic)(mnemonic);
    const wallet = await local_wallet_1.default.fromMnemonic(mnemonic, constants_2.BECH32_PREFIX);
    const privateKeyHex = privateKeyRaw != null ? `0x${(0, encoding_1.toHex)(privateKeyRaw)}` : undefined;
    const publicKey = wallet.pubKey;
    const address = wallet.address;
    if (privateKeyHex == null || publicKey == null || address == null) {
        return undefined;
    }
    return {
        // 12 english words
        mnemonic,
        // toHex of the raw private key bits
        privateKeyHex,
        // base64, not hex
        publicKey: publicKey.value,
        // valid chain address corresponding to the key pair
        address,
    };
};
exports.createNewRandomChainWallet = createNewRandomChainWallet;
// arguments to authorize a given wallet public key to trade on behalf of the user.
// allows place order, cancel order, batch cancel on subaccount 0 only.
const getAuthorizeNewTradingKeyArguments = ({ generatedWalletPubKey, }) => {
    const wrapAndEncode64 = (s) => (0, encoding_1.toBase64)(new TextEncoder().encode(s));
    const messageFilterSubAuth = [
        {
            type: constants_1.AuthenticatorType.MESSAGE_FILTER,
            config: wrapAndEncode64(constants_1.TYPE_URL_MSG_PLACE_ORDER),
        },
        {
            type: constants_1.AuthenticatorType.MESSAGE_FILTER,
            config: wrapAndEncode64(constants_1.TYPE_URL_MSG_CANCEL_ORDER),
        },
        {
            type: constants_1.AuthenticatorType.MESSAGE_FILTER,
            config: wrapAndEncode64(constants_1.TYPE_URL_BATCH_CANCEL),
        },
    ];
    const anyOfMessageFilterConfigB64 = wrapAndEncode64(JSON.stringify(messageFilterSubAuth));
    const subAuth = [
        {
            type: constants_1.AuthenticatorType.SIGNATURE_VERIFICATION,
            config: generatedWalletPubKey,
        },
        {
            type: constants_1.AuthenticatorType.ANY_OF,
            config: anyOfMessageFilterConfigB64,
        },
        // we limit to cross markets to make it slightly harder to drain user funds on low liquidity markets with trading keys
        // could undo this in the future if people are angry about it
        {
            type: constants_1.AuthenticatorType.SUBACCOUNT_FILTER,
            config: wrapAndEncode64('0'),
        },
    ];
    const jsonString = JSON.stringify(subAuth);
    const encodedData = new TextEncoder().encode(jsonString);
    const topLevelType = constants_1.AuthenticatorType.ALL_OF;
    return {
        type: topLevelType,
        data: encodedData,
    };
};
exports.getAuthorizeNewTradingKeyArguments = getAuthorizeNewTradingKeyArguments;
const isTruthy = (n) => Boolean(n);
// just parses out keys that match the format created in getAuthorizeNewTradingKeyArguments
const getAuthorizedTradingKeysMetadata = (authorizedKeys) => {
    return authorizedKeys
        .map(({ config, id, type }) => {
        var _a;
        if (type !== constants_1.AuthenticatorType.ALL_OF) {
            return null;
        }
        const parsedConfig = JSON.parse(new TextDecoder().decode(config));
        if (parsedConfig == null) {
            return null;
        }
        const publicKey = (_a = parsedConfig.find((t) => t.type === constants_1.AuthenticatorType.SIGNATURE_VERIFICATION)) === null || _a === void 0 ? void 0 : _a.config;
        if (publicKey == null || typeof publicKey !== 'string') {
            return null;
        }
        const address = (0, encoding_1.toBech32)(constants_2.BECH32_PREFIX, (0, tendermint_rpc_1.rawSecp256k1PubkeyToRawAddress)((0, encoding_1.fromBase64)(publicKey)));
        return {
            id: id.toString(),
            publicKey,
            address,
        };
    })
        .filter(isTruthy);
};
exports.getAuthorizedTradingKeysMetadata = getAuthorizedTradingKeysMetadata;
//# sourceMappingURL=data:application/json;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