"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TransactionSigner = void 0;
const encoding_1 = require("@cosmjs/encoding");
const math_1 = require("@cosmjs/math");
const proto_signing_1 = require("@cosmjs/proto-signing");
const tx_1 = require("@ritbit/v4-proto/src/codegen/ritbit/accountplus/tx");
const tx_2 = require("cosmjs-types/cosmos/tx/v1beta1/tx");
const any_1 = require("cosmjs-types/google/protobuf/any");
const long_1 = __importDefault(require("long"));
const protobufjs_1 = __importDefault(require("protobufjs"));
const registry_1 = require("../lib/registry");
// Required for encoding and decoding queries that are of type Long.
// Must be done once but since the individal modules should be usable
// - must be set in each module that encounters encoding/decoding Longs.
// Reference: https://github.com/protobufjs/protobuf.js/issues/921
protobufjs_1.default.util.Long = long_1.default;
protobufjs_1.default.configure();
class TransactionSigner {
    constructor(address, stargateSigningClient, offlineSigner) {
        this.address = address;
        this.stargateSigningClient = stargateSigningClient;
        this.offlineSigner = offlineSigner;
    }
    /**
     * @description Get the encoded signed transaction or the promise is rejected if
     * no fee can be set for the transaction.
     *
     * @throws UserError if the fee is undefined.
     * @returns The signed and encoded transaction.
     */
    async signTransaction(messages, transactionOptions, fee, memo = '', publicKey) {
        var _a;
        if (!fee) {
            throw new Error('Fee cannot be undefined');
        }
        const registry = (0, registry_1.generateRegistry)();
        // Encode the messages
        const encodedMessages = messages.map((msg) => registry.encodeAsAny(msg));
        // Encode the TxExtension message
        const txExtension = tx_1.TxExtension.encode({
            selectedAuthenticators: (_a = transactionOptions.authenticators) !== null && _a !== void 0 ? _a : [],
        }).finish();
        // Create the non-critical extension message
        const nonCriticalExtensionOptions = [
            any_1.Any.fromPartial({
                typeUrl: '/ritbit.accountplus.TxExtension',
                value: txExtension,
            }),
        ];
        // Construct the TxBody
        const txBody = tx_2.TxBody.fromPartial({
            messages: encodedMessages,
            memo,
            extensionOptions: [],
            nonCriticalExtensionOptions,
        });
        // Encode the TxBody
        const txBodyBytes = tx_2.TxBody.encode(txBody).finish();
        if (!publicKey) {
            throw new Error('Public key cannot be undefined');
        }
        const pubkey = (0, proto_signing_1.encodePubkey)(publicKey); // Use the public key of the signer
        const gasLimit = math_1.Int53.fromString(String(fee.gas)).toNumber();
        const authInfoBytes = (0, proto_signing_1.makeAuthInfoBytes)([{ pubkey, sequence: transactionOptions.sequence }], fee.amount, gasLimit, undefined, undefined);
        // Create the SignDoc
        const signDoc = (0, proto_signing_1.makeSignDoc)(txBodyBytes, authInfoBytes, transactionOptions.chainId, transactionOptions.accountNumber);
        // Use OfflineSigner to sign the transaction
        const signerAddress = this.address;
        if ((0, proto_signing_1.isOfflineDirectSigner)(this.offlineSigner)) {
            const { signed, signature } = await this.offlineSigner.signDirect(signerAddress, signDoc);
            const txRaw = tx_2.TxRaw.fromPartial({
                bodyBytes: signed.bodyBytes,
                authInfoBytes: signed.authInfoBytes,
                signatures: [(0, encoding_1.fromBase64)(signature.signature)],
            });
            return Uint8Array.from(tx_2.TxRaw.encode(txRaw).finish());
        }
        else {
            const rawTx = await this.stargateSigningClient.sign(this.address, messages, fee, memo, {
                accountNumber: transactionOptions.accountNumber,
                sequence: transactionOptions.sequence,
                chainId: transactionOptions.chainId,
            });
            return Uint8Array.from(tx_2.TxRaw.encode(rawTx).finish());
        }
    }
}
exports.TransactionSigner = TransactionSigner;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2lnbmVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vLi4vc3JjL2NsaWVudHMvbW9kdWxlcy9zaWduZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7O0FBQ0EsK0NBQThDO0FBQzlDLHVDQUFxQztBQUNyQyx5REFPK0I7QUFFL0IsMkVBQWlGO0FBQ2pGLDBEQUFrRTtBQUNsRSwwREFBdUQ7QUFDdkQsZ0RBQXdC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