"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Get = void 0;
const stargate_1 = require("@cosmjs/stargate");
const query_1 = require("@ritbit/v4-proto/src/codegen/ritbit/accountplus/query");
const AuthModule = __importStar(require("cosmjs-types/cosmos/auth/v1beta1/query"));
const BankModule = __importStar(require("cosmjs-types/cosmos/bank/v1beta1/query"));
const long_1 = __importDefault(require("long"));
const protobufjs_1 = __importDefault(require("protobufjs"));
const helpers_1 = require("../../lib/helpers");
const constants_1 = require("../constants");
const errors_1 = require("../lib/errors");
const proto_includes_1 = require("./proto-includes");
// Required for encoding and decoding queries that are of type Long.
// Must be done once but since the individal modules should be usable without
// dYdXClient - 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 Get {
    constructor(tendermintClient, stargateQueryClient) {
        this.tendermintClient = tendermintClient;
        this.stargateQueryClient = stargateQueryClient;
    }
    /**
     * @description Get latest block
     *
     * @returns last block structure
     */
    async latestBlock() {
        return this.tendermintClient.getBlock();
    }
    /**
     * @description Get latest block height
     *
     * @returns last height
     */
    async latestBlockHeight() {
        const block = await this.latestBlock();
        return block.header.height;
    }
    /**
     * @description Get all fee tier params.
     *
     * @returns All fee tier params.
     */
    async getFeeTiers() {
        const requestData = Uint8Array.from(proto_includes_1.FeeTierModule.QueryPerpetualFeeParamsRequest.encode({}).finish());
        const data = await this.sendQuery('/ritbit.feetiers.Query/PerpetualFeeParams', requestData);
        return proto_includes_1.FeeTierModule.QueryPerpetualFeeParamsResponse.decode(data);
    }
    /**
     * @description Get fee tier the user belongs to
     *
     * @returns the fee tier user belongs to.
     */
    async getUserFeeTier(address) {
        const requestData = Uint8Array.from(proto_includes_1.FeeTierModule.QueryUserFeeTierRequest.encode({ user: address }).finish());
        const data = await this.sendQuery('/ritbit.feetiers.Query/UserFeeTier', requestData);
        return proto_includes_1.FeeTierModule.QueryUserFeeTierResponse.decode(data);
    }
    /**
     * @description Get get trading stats
     *
     * @returns return the user's taker and maker volume
     */
    async getUserStats(address) {
        const requestData = Uint8Array.from(proto_includes_1.StatsModule.QueryUserStatsRequest.encode({ user: address }).finish());
        const data = await this.sendQuery('/ritbit.stats.Query/UserStats', requestData);
        return proto_includes_1.StatsModule.QueryUserStatsResponse.decode(data).stats;
    }
    /**
     * @description Get all balances for an account.
     *
     * @returns Array of Coin balances for all tokens held by an account.
     */
    async getAccountBalances(address) {
        const requestData = Uint8Array.from(BankModule.QueryAllBalancesRequest.encode({ address }).finish());
        const data = await this.sendQuery('/cosmos.bank.v1beta1.Query/AllBalances', requestData);
        return BankModule.QueryAllBalancesResponse.decode(data).balances;
    }
    /**
     * @description Get balances of one denom for an account.
     *
     * @returns Coin balance for denom tokens held by an account.
     */
    async getAccountBalance(address, denom) {
        const requestData = Uint8Array.from(BankModule.QueryBalanceRequest.encode({
            address,
            denom,
        }).finish());
        const data = await this.sendQuery('/cosmos.bank.v1beta1.Query/Balance', requestData);
        const coin = BankModule.QueryBalanceResponse.decode(data).balance;
        return coin;
    }
    /**
     * @description Get spendable (unlocked) balance of one denom for an account.
     * For vesting accounts returns only the unlocked portion; for regular accounts equals full balance.
     *
     * @returns Coin spendable balance for denom.
     */
    async getSpendableBalance(address, denom) {
        const requestData = Uint8Array.from(BankModule.QuerySpendableBalanceByDenomRequest.encode({
            address,
            denom,
        }).finish());
        const data = await this.sendQuery('/cosmos.bank.v1beta1.Query/SpendableBalanceByDenom', requestData);
        const coin = BankModule.QuerySpendableBalanceByDenomResponse.decode(data).balance;
        return coin;
    }
    /**
     * @description Get all spendable (unlocked) balances for an account.
     * For vesting accounts returns only unlocked portions; for regular accounts equals full balances.
     *
     * @returns Array of Coin spendable balances.
     */
    async getSpendableBalances(address) {
        const requestData = Uint8Array.from(BankModule.QuerySpendableBalancesRequest.encode({ address }).finish());
        const data = await this.sendQuery('/cosmos.bank.v1beta1.Query/SpendableBalances', requestData);
        return BankModule.QuerySpendableBalancesResponse.decode(data).balances;
    }
    /**
     * @description Get all subaccounts
     *
     * @returns All subaccounts
     */
    async getSubaccounts() {
        const requestData = Uint8Array.from(proto_includes_1.SubaccountsModule.QueryAllSubaccountRequest.encode({}).finish());
        const data = await this.sendQuery('/ritbit.subaccounts.Query/SubaccountAll', requestData);
        return proto_includes_1.SubaccountsModule.QuerySubaccountAllResponse.decode(data);
    }
    /**
     * @description Get a specific subaccount for an account.
     *
     * @returns Subaccount for account with given accountNumber or default subaccount if none exists.
     */
    async getSubaccount(address, accountNumber) {
        const requestData = Uint8Array.from(proto_includes_1.SubaccountsModule.QueryGetSubaccountRequest.encode({
            owner: address,
            number: accountNumber,
        }).finish());
        const data = await this.sendQuery('/ritbit.subaccounts.Query/Subaccount', requestData);
        return proto_includes_1.SubaccountsModule.QuerySubaccountResponse.decode(data);
    }
    /**
     * @description Get the params for the rewards module.
     *
     * @returns Params for the rewards module.
     */
    async getRewardsParams() {
        const requestData = Uint8Array.from(proto_includes_1.RewardsModule.QueryParamsRequest.encode({}).finish());
        const data = await this.sendQuery('/ritbit.rewards.Query/Params', requestData);
        return proto_includes_1.RewardsModule.QueryParamsResponse.decode(data);
    }
    /**
     * @description Get all Clob Pairs.
     *
     * @returns Information on all Clob Pairs.
     */
    async getAllClobPairs() {
        const requestData = Uint8Array.from(proto_includes_1.ClobModule.QueryAllClobPairRequest.encode({ pagination: constants_1.PAGE_REQUEST }).finish());
        const data = await this.sendQuery('/ritbit.clob.Query/ClobPairAll', requestData);
        return proto_includes_1.ClobModule.QueryClobPairAllResponse.decode(data);
    }
    /**
     * @description Get Clob Pair for an Id or the promise is rejected if no pair exists.
     *
     * @returns Clob Pair for a given Clob Pair Id.
     */
    async getClobPair(pairId) {
        const requestData = Uint8Array.from(proto_includes_1.ClobModule.QueryGetClobPairRequest.encode({ id: pairId }).finish());
        const data = await this.sendQuery('/ritbit.clob.Query/ClobPair', requestData);
        return proto_includes_1.ClobModule.QueryClobPairResponse.decode(data);
    }
    /**
     * @description Get all Prices across markets.
     *
     * @returns Prices across all markets.
     */
    async getAllPrices() {
        const requestData = Uint8Array.from(proto_includes_1.PricesModule.QueryAllMarketPricesRequest.encode({ pagination: constants_1.PAGE_REQUEST }).finish());
        const data = await this.sendQuery('/ritbit.prices.Query/AllMarketPrices', requestData);
        return proto_includes_1.PricesModule.QueryAllMarketPricesResponse.decode(data);
    }
    /**
     * @description Get Price for a clob Id or the promise is rejected if none exists.
     *
     * @returns Price for a given Market Id.
     */
    async getPrice(marketId) {
        const requestData = Uint8Array.from(proto_includes_1.PricesModule.QueryMarketPriceRequest.encode({ id: marketId }).finish());
        const data = await this.sendQuery('/ritbit.prices.Query/MarketPrice', requestData);
        return proto_includes_1.PricesModule.QueryMarketPriceResponse.decode(data);
    }
    /**
     * @description Get all Perpetuals.
     *
     * @returns Information on all Perpetual pairs.
     */
    async getAllPerpetuals() {
        const requestData = Uint8Array.from(proto_includes_1.PerpetualsModule.QueryAllPerpetualsRequest.encode({ pagination: constants_1.PAGE_REQUEST }).finish());
        const data = await this.sendQuery('/ritbit.perpetuals.Query/AllPerpetuals', requestData);
        return proto_includes_1.PerpetualsModule.QueryAllPerpetualsResponse.decode(data);
    }
    /**
     * @description Get Perpetual for an Id or the promise is rejected if none exists.
     *
     * @returns The Perpetual for a given Perpetual Id.
     */
    async getPerpetual(perpetualId) {
        const requestData = Uint8Array.from(proto_includes_1.PerpetualsModule.QueryPerpetualRequest.encode({ id: perpetualId }).finish());
        const data = await this.sendQuery('/ritbit.perpetuals.Query/Perpetual', requestData);
        return proto_includes_1.PerpetualsModule.QueryPerpetualResponse.decode(data);
    }
    /**
     * @description Get Account for an address or the promise is rejected if the account
     * does not exist on-chain.
     *
     * @throws UnexpectedClientError if a malformed response is returned with no GRPC error.
     * @returns An account with typeUrl for a given address.
     */
    async getAccount(address) {
        const requestData = Uint8Array.from(AuthModule.QueryAccountRequest.encode({ address }).finish());
        const data = await this.sendQuery('/cosmos.auth.v1beta1.Query/Account', requestData);
        const rawAccount = AuthModule.QueryAccountResponse.decode(data).account;
        if (rawAccount === undefined) {
            throw new errors_1.UnexpectedClientError();
        }
        return {
            ...(0, stargate_1.accountFromAny)(rawAccount),
            typeUrl: rawAccount.typeUrl,
        };
    }
    /**
     * @description Get equity tier limit configuration.
     *
     * @returns Information on all equity tiers that are configured.
     */
    async getEquityTierLimitConfiguration() {
        const requestData = Uint8Array.from(proto_includes_1.ClobModule.QueryEquityTierLimitConfigurationRequest.encode({}).finish());
        const data = await this.sendQuery('/ritbit.clob.Query/EquityTierLimitConfiguration', requestData);
        return proto_includes_1.ClobModule.QueryEquityTierLimitConfigurationResponse.decode(data);
    }
    /**
     *
     * @description Get all delegations from a delegator.
     *
     * @returns All delegations from a delegator.
     */
    async getDelegatorDelegations(delegatorAddr) {
        const requestData = Uint8Array.from(proto_includes_1.StakingModule.QueryDelegatorDelegationsRequest.encode({
            delegatorAddr,
            pagination: constants_1.PAGE_REQUEST,
        }).finish());
        const data = await this.sendQuery('/cosmos.staking.v1beta1.Query/DelegatorDelegations', requestData);
        return proto_includes_1.StakingModule.QueryDelegatorDelegationsResponse.decode(data);
    }
    /**
     *
     * @description Get all unbonding delegations from a delegator.
     *
     * @returns All unbonding delegations from a delegator.
     */
    async getDelegatorUnbondingDelegations(delegatorAddr) {
        const requestData = Uint8Array.from(proto_includes_1.StakingModule.QueryDelegatorUnbondingDelegationsRequest.encode({
            delegatorAddr,
            pagination: constants_1.PAGE_REQUEST,
        }).finish());
        const data = await this.sendQuery('/cosmos.staking.v1beta1.Query/DelegatorUnbondingDelegations', requestData);
        return proto_includes_1.StakingModule.QueryDelegatorUnbondingDelegationsResponse.decode(data);
    }
    /**
     *
     * @description Get all unbonding delegations from a delegator.
     *
     * @returns All unbonding delegations from a delegator.
     */
    async getDelegationTotalRewards(delegatorAddress) {
        const requestData = Uint8Array.from(proto_includes_1.DistributionModule.QueryDelegationTotalRewardsRequest.encode({
            delegatorAddress,
        }).finish());
        const data = await this.sendQuery('/cosmos.distribution.v1beta1.Query/DelegationTotalRewards', requestData);
        return proto_includes_1.DistributionModule.QueryDelegationTotalRewardsResponse.decode(data);
    }
    /**
     * @description Get bridge EventParams (chains, token mappings, withdrawal fees).
     *
     * @returns EventParams with bridge config including withdrawal_fee per TokenMapping
     */
    async getBridgeEventParams() {
        const requestData = Uint8Array.from(proto_includes_1.BridgeModule.QueryEventParamsRequest.encode({}).finish());
        const data = await this.sendQuery('/ritbit.bridge.Query/EventParams', requestData);
        return proto_includes_1.BridgeModule.QueryEventParamsResponse.decode(data);
    }
    /**
     * @description Get all delayed complete bridge messages, optionally filtered by address.
     *
     * @returns Information on all delayed complete bridge messages.
     */
    async getDelayedCompleteBridgeMessages(address = '') {
        const requestData = Uint8Array.from(proto_includes_1.BridgeModule.QueryDelayedCompleteBridgeMessagesRequest.encode({ address }).finish());
        const data = await this.sendQuery('/ritbit.bridge.Query/DelayedCompleteBridgeMessages', requestData);
        return proto_includes_1.BridgeModule.QueryDelayedCompleteBridgeMessagesResponse.decode(data);
    }
    /**
     * @description Get all validators of a status.
     *
     * @returns all validators of a status.
     */
    async getAllValidators(status = '') {
        const requestData = Uint8Array.from(proto_includes_1.StakingModule.QueryValidatorsRequest.encode({
            status,
            pagination: constants_1.PAGE_REQUEST,
        }).finish());
        const data = await this.sendQuery('/cosmos.staking.v1beta1.Query/Validators', requestData);
        return proto_includes_1.StakingModule.QueryValidatorsResponse.decode(data);
    }
    /**
     * @description Get all gov proposals.
     *
     * @param proposalStatus Status of the proposal to filter by.
     * @param voter Voter to filter by.
     * @param depositor Depositor to filter by.
     *
     * @returns All gov proposals that match the filters above.
     */
    async getAllGovProposals(proposalStatus = proto_includes_1.ProposalStatus.PROPOSAL_STATUS_VOTING_PERIOD, voter = '', depositor = '') {
        const requestData = Uint8Array.from(proto_includes_1.GovV1Module.QueryProposalsRequest.encode({
            proposalStatus,
            voter,
            depositor,
            pagination: constants_1.PAGE_REQUEST,
        }).finish());
        const data = await this.sendQuery('/cosmos.gov.v1.Query/Proposals', requestData);
        return proto_includes_1.GovV1Module.QueryProposalsResponse.decode(data);
    }
    async getWithdrawalAndTransferGatingStatus(perpetualId) {
        const requestData = Uint8Array.from(proto_includes_1.SubaccountsModule.QueryGetWithdrawalAndTransfersBlockedInfoRequest.encode({
            perpetualId,
        }).finish());
        const data = await this.sendQuery('/ritbit.subaccounts.Query/GetWithdrawalAndTransfersBlockedInfo', requestData);
        return proto_includes_1.SubaccountsModule.QueryGetWithdrawalAndTransfersBlockedInfoResponse.decode(data);
    }
    async getWithdrawalCapacityByDenom(denom) {
        const requestData = Uint8Array.from(proto_includes_1.RateLimitModule.QueryCapacityByDenomRequest.encode({
            denom,
        }).finish());
        const data = await this.sendQuery('/ritbit.ratelimit.Query/CapacityByDenom', requestData);
        return proto_includes_1.RateLimitModule.QueryCapacityByDenomResponse.decode(data);
    }
    async getMegavaultOwnerShares(address) {
        const requestData = Uint8Array.from(proto_includes_1.VaultModule.QueryMegavaultOwnerSharesRequest.encode({
            address,
        }).finish());
        const data = await this.sendQuery('/ritbit.vault.Query/MegavaultOwnerShares', requestData);
        return proto_includes_1.VaultModule.QueryMegavaultOwnerSharesResponse.decode(data);
    }
    async getMegavaultWithdrawalInfo(sharesToWithdraw) {
        const requestData = Uint8Array.from(proto_includes_1.VaultModule.QueryMegavaultWithdrawalInfoRequest.encode({
            sharesToWithdraw: {
                numShares: (0, helpers_1.bigIntToBytes)(sharesToWithdraw),
            },
        }).finish());
        const data = await this.sendQuery('/ritbit.vault.Query/MegavaultWithdrawalInfo', requestData);
        return proto_includes_1.VaultModule.QueryMegavaultWithdrawalInfoResponse.decode(data);
    }
    async getMegavaultAllOwnerShares() {
        const requestData = Uint8Array.from(proto_includes_1.VaultModule.QueryMegavaultAllOwnerSharesRequest.encode({
            pagination: constants_1.PAGE_REQUEST,
        }).finish());
        const data = await this.sendQuery('/ritbit.vault.Query/MegavaultAllOwnerShares', requestData);
        return proto_includes_1.VaultModule.QueryMegavaultAllOwnerSharesResponse.decode(data);
    }
    async getMegavaultTotalShares() {
        const requestData = Uint8Array.from(proto_includes_1.VaultModule.QueryMegavaultTotalSharesRequest.encode({}).finish());
        const data = await this.sendQuery('/ritbit.vault.Query/MegavaultTotalShares', requestData);
        return proto_includes_1.VaultModule.QueryMegavaultTotalSharesResponse.decode(data);
    }
    async getAffiliateInfo(address) {
        const requestData = Uint8Array.from(proto_includes_1.AffiliateModule.AffiliateInfoRequest.encode({
            address,
        }).finish());
        const data = await this.sendQuery('/ritbit.affiliates.Query/AffiliateInfo', requestData);
        return proto_includes_1.AffiliateModule.AffiliateInfoResponse.decode(data);
    }
    async getReferredBy(address) {
        const requestData = Uint8Array.from(proto_includes_1.AffiliateModule.ReferredByRequest.encode({
            address,
        }).finish());
        const data = await this.sendQuery('/ritbit.affiliates.Query/ReferredBy', requestData);
        return proto_includes_1.AffiliateModule.ReferredByResponse.decode(data);
    }
    async getAllAffiliateTiers() {
        const requestData = Uint8Array.from(proto_includes_1.AffiliateModule.AllAffiliateTiersRequest.encode({}).finish());
        const data = await this.sendQuery('/ritbit.affiliates.Query/AllAffiliateTiers', requestData);
        return proto_includes_1.AffiliateModule.AllAffiliateTiersResponse.decode(data);
    }
    async getAffiliateWhitelist() {
        const requestData = Uint8Array.from(proto_includes_1.AffiliateModule.AffiliateWhitelistRequest.encode({}).finish());
        const data = await this.sendQuery('/ritbit.affiliates.Query/AffiliateWhitelist', requestData);
        return proto_includes_1.AffiliateModule.AffiliateWhitelistResponse.decode(data);
    }
    async getAuthenticators(address) {
        const requestData = Uint8Array.from(query_1.GetAuthenticatorsRequest.encode({
            account: address,
        }).finish());
        const data = await this.sendQuery('/ritbit.accountplus.Query/GetAuthenticators', requestData);
        return query_1.GetAuthenticatorsResponse.decode(data);
    }
    /**
     * @description Get fee discounts for all perp markets.
     * @returns All markets' fee discounts.
     */
    async getAllPerpMarketFeeDiscounts() {
        const requestData = Uint8Array.from(proto_includes_1.FeeTierModule.QueryAllMarketFeeDiscountParamsRequest.encode({}).finish());
        const data = await this.sendQuery('/ritbit.feetiers.Query/AllMarketFeeDiscountParams', requestData);
        return proto_includes_1.FeeTierModule.QueryAllMarketFeeDiscountParamsResponse.decode(data);
    }
    /**
     *
     * @param address The address of the user to get the staking tier for.
     * @returns The staking tier for the user.
     */
    async getUserStakingTier(address) {
        const requestData = Uint8Array.from(proto_includes_1.FeeTierModule.QueryUserStakingTierRequest.encode({
            address,
        }).finish());
        const data = await this.sendQuery('/ritbit.feetiers.Query/UserStakingTier', requestData);
        return proto_includes_1.FeeTierModule.QueryUserStakingTierResponse.decode(data);
    }
    /**
     * @description Get all staking tiers.
     * @returns All staking tiers.
     */
    async getAllStakingTiers() {
        const requestData = Uint8Array.from(proto_includes_1.FeeTierModule.QueryStakingTiersRequest.encode({}).finish());
        const data = await this.sendQuery('/ritbit.feetiers.Query/StakingTiers', requestData);
        return proto_includes_1.FeeTierModule.QueryStakingTiersResponse.decode(data);
    }
    async sendQuery(requestUrl, requestData) {
        // eslint-disable-next-line max-len
        const resp = await this.stargateQueryClient.queryAbci(requestUrl, requestData);
        return resp.value;
    }
}
exports.Get = Get;
//# sourceMappingURL=data:application/json;base64, 