libyaci

package module
v1.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 6, 2026 License: MIT Imports: 32 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

libyaci

A dynamic gRPC client for Go that uses server reflection to discover services, build protobuf messages, and invoke methods without generated stubs. Designed for Cosmos SDK blockchains, but usable with any reflection-enabled gRPC server.

Features

  • Capability catalog from advertised gRPC reflection services
  • Descriptor-backed request and response builders without generated stubs
  • Dynamic JSON or raw protobuf invocation
  • SDK-version metadata for diagnostics; reflected capabilities decide availability
  • On-demand type resolution for Any fields with descriptor caching
  • Local proto directory fallback for historical/deprecated types
  • Thread-safe concurrent access
  • Raw protobuf transaction decoding (Cosmos SDK)
  • Transaction signing and broadcasting (signing subpackage): secp256k1/ethsecp256k1, raw key or BIP39 mnemonic, SIGN_MODE_DIRECT
  • Cosmos convenience helpers layered on top of reflected capabilities

Installation

go get github.com/Cordtus/libyaci

Requirements

  • Go 1.24+
  • gRPC server with reflection enabled
    • Supports both grpc.reflection.v1 and grpc.reflection.v1alpha (automatic fallback)

Quick Start

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/Cordtus/libyaci"
)

func main() {
    ctx := context.Background()

    client, err := libyaci.Dial(ctx, "localhost:9090", libyaci.WithInsecure())
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()

    methodName := "cosmos.bank.v1beta1.Query.Balance"
    if !client.SupportsMethod(methodName) {
        log.Fatalf("%s is not advertised by this chain", methodName)
    }

    method, err := client.Method(methodName)
    if err != nil {
        log.Fatal(err)
    }

    req, err := method.RequestFromMap(map[string]any{
        "address": "cosmos1...",
        "denom":   "uatom",
    })
    if err != nil {
        log.Fatal(err)
    }

    resp, err := method.Call(ctx, req)
    if err != nil {
        log.Fatal(err)
    }

    jsonBytes, err := resp.JSON()
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(string(jsonBytes))
}

Configuration Options

client, err := libyaci.Dial(ctx, "grpc.example.com:443",
    libyaci.WithInsecure(),                         // Disable TLS
    libyaci.WithMaxRetries(5),                      // Retry count (default: 3)
    libyaci.WithMaxRecvMsgSize(16 * 1024 * 1024),   // Max message size (default: 16MB)
    libyaci.WithDialTimeout(30 * time.Second),      // Connection timeout (default: no timeout)
    libyaci.WithDefaultTimeout(10 * time.Second),   // Timeout per invocation (includes retries)
    libyaci.WithSDKVersion("0.47.0"),               // Diagnostic metadata only
    libyaci.WithDialOptions(grpc.WithPerRPCCredentials(creds)), // Custom gRPC options
    libyaci.WithTLSConfig(&tls.Config{InsecureSkipVerify: true}), // Custom CA / self-signed certs
    libyaci.WithProtoDir("./protos"),               // Secondary fallback for deprecated types
)

Reflection decides what can be called. SDK version options annotate diagnostics and unsupported-method errors, but a method is supported only when its service is advertised by reflection and the method exists in that reflected service descriptor.

By default the client verifies the server certificate against the system roots. Use WithTLSConfig for a custom CA, client certificate, or self-signed endpoint (for example WithTLSConfig(&tls.Config{InsecureSkipVerify: true})). WithTLSConfig is ignored when WithInsecure is set, and should not be combined with a grpc.WithTransportCredentials passed via WithDialOptions.

ALPN Enforcement (grpc-go v1.67+)

Starting with grpc-go v1.67, ALPN (Application-Layer Protocol Negotiation) is enforced by default. Many Cosmos SDK nodes—especially older or self-hosted ones—don't properly support ALPN, causing connection failures:

transport: authentication handshake failed: credentials: cannot check peer: missing selected ALPN property

Fix: Import the alpnfix package before any gRPC imports:

import (
    _ "github.com/Cordtus/libyaci/alpnfix" // Must be first!
    "github.com/Cordtus/libyaci"
)

Or set the environment variable: GRPC_ENFORCE_ALPN_ENABLED=false ./your-program

Note: This disables ALPN enforcement process-wide. If you need ALPN for some connections, use the environment variable approach selectively.

Local Proto Directory (Deprecated/Unavailable Types)

Some Cosmos SDK modules have been deprecated and removed from chains, but their transaction data still exists in historical blocks. Server reflection cannot provide descriptors for these removed modules, causing decode failures.

The WithProtoDir() option allows you to provide local .proto files that will be used as a per-client fallback when server reflection fails to resolve a historical or deprecated type. Current chain query and message support should come from reflected descriptors first.

Basic Usage
client, err := libyaci.Dial(ctx, endpoint,
    libyaci.WithProtoDir("./protos"),
)

When a type like tendermint.liquidity.v1beta1.MsgSwapWithinBatch cannot be resolved via server reflection, the client will look for it in the local proto files.

Directory Structure

The proto directory should mirror the package path structure:

protos/
  tendermint/liquidity/v1beta1/tx.proto
  cosmos/base/v1beta1/coin.proto
  cosmos/staking/v1beta1/tx.proto

Proto files are loaded lazily on first type resolution failure. Standard protobuf imports (google/protobuf/*) are automatically available. The configured directory is validated when Dial runs, and can be retrieved with client.ProtoDir().

UTF-8 recovery (patching a string field to bytes when it contains binary data) works for both reflected and local-proto types, so historical transactions that decode to deprecated message types are recoverable.

Resolution Order
  1. Primary proto registry (from server reflection)
  2. On-demand reflection for unknown types
  3. Local proto directory (if configured)
  4. Error with hint about missing type
Common Deprecated Modules
Module Package Description
Liquidity (Gravity DEX) tendermint.liquidity.v1beta1 AMM/DEX module removed from Cosmos Hub
LSM Staking Extensions cosmos.staking.v1beta1 MsgTokenizeShares, MsgRedeemTokensForShares
Advanced: Custom Fallback Registry

For programmatic proto registration:

// Create a custom fallback registry
fb := libyaci.NewFallbackRegistry()

// Register your own types programmatically
fb.RegisterFileDescriptor(myProtoDescriptor)

// Use the custom registry
client, err := libyaci.Dial(ctx, endpoint,
    libyaci.WithFallbackRegistry(fb),
)
Fallback Options
Option Description
WithProtoDir(path) Load local .proto files into this client for fallback resolution
WithGlobalFallback() Explicitly use the shared global fallback registry
WithFallbackRegistry(fb) Use a custom fallback registry

Transaction Signing & Broadcasting

The signing subpackage builds, signs (SIGN_MODE_DIRECT), and broadcasts Cosmos transactions. Transaction scaffolding (cosmos.tx.v1beta1.*, cosmos.crypto.secp256k1.PubKey, cosmos.base.v1beta1.Coin) is resolved from server reflection, so no generated Cosmos stubs are needed. It adds cryptographic dependencies (btcec/v2, btcutil/bech32, cosmos/go-bip39, golang.org/x/crypto) that are only compiled when you import the subpackage.

import (
    "context"

    "github.com/Cordtus/libyaci"
    "github.com/Cordtus/libyaci/signing"
)

ctx := context.Background()
client, err := libyaci.Dial(ctx, "grpc.example.com:443", libyaci.WithInsecure())
if err != nil { /* ... */ }
defer client.Close()

// Key source: mnemonic (BIP44) or a raw hex/base64 private key.
signer, err := signing.NewMnemonicSigner(mnemonic, signing.DefaultHDPath, signing.Secp256k1)
if err != nil { /* ... */ }
// or: signing.NewPrivateKeySigner(hexKey, signing.EthSecp256k1)

address, err := signer.Address("cosmos")
if err != nil { /* ... */ }

accountNumber, sequence, err := signing.FetchAccountNumberSequence(ctx, client, address)
if err != nil { /* ... */ }

msgs := []signing.Msg{
    []byte(`{"@type":"/cosmos.bank.v1beta1.MsgSend",
             "fromAddress":"cosmos1...","toAddress":"cosmos1...",
             "amount":[{"denom":"uatom","amount":"1000"}]}`),
}

tx, err := signing.BuildAndSign(client.Resolver(), signer, "cosmoshub-4", msgs, signing.TxOptions{
    Memo:          "",
    Fee:           []signing.Coin{{Denom: "uatom", Amount: "5000"}},
    GasLimit:      200000,
    AccountNumber: accountNumber,
    Sequence:      sequence,
    AddressPrefix: "cosmos",
})
if err != nil { /* ... */ }

// Optional: estimate the gas limit and fee, then rebuild with them.
gasLimit, fee, err := signing.EstimateFee(ctx, client, signer, "cosmoshub-4", msgs, signing.TxOptions{
    AccountNumber: accountNumber,
    Sequence:      sequence,
}, []signing.Coin{{Denom: "uatom", Amount: "0.025"}}, 1.3)
if err != nil { /* ... */ }
tx, err = signing.BuildAndSign(client.Resolver(), signer, "cosmoshub-4", msgs, signing.TxOptions{
    Fee:           fee,
    GasLimit:      gasLimit,
    AccountNumber: accountNumber,
    Sequence:      sequence,
    AddressPrefix: "cosmos",
})
if err != nil { /* ... */ }

resp, err := signing.Broadcast(ctx, client, tx.TxBytes, signing.BroadcastModeSync)
if err != nil { /* CheckTx rejected or transport error */ }
_ = resp.TxHash
Signing API
Item Description
Signer Interface: PublicKey, Address(prefix), Sign(signDoc), PubKeyTypeURL, Algorithm
NewPrivateKeySigner(secret, algo, ...) secp256k1 key from 64-char hex or base64
NewMnemonicSigner(mnemonic, hdPath, algo, ...) BIP39/BIP44 derivation (default m/44'/118'/0'/0/0)
GenerateMnemonic(bits) New BIP39 mnemonic (128–256 bits)
PrivateKeySigner.EthereumAddress() Lowercase 0x address for ethsecp256k1 keys
BuildAndSign(resolver, signer, chainID, msgs, opts) Returns body/auth/sign-doc/tx bytes, signature, tx hash
ResolvePubKeyTypeURL(resolver, algo) Picks the reflected public-key type URL for an algorithm
FetchAccountNumberSequence(ctx, client, address) Account number and sequence (AccountInfo, then Account)
EstimateGas(ctx, client, signer, chainID, msgs, opts) Simulates the tx and returns raw gas used
EstimateFee(ctx, client, signer, chainID, msgs, opts, gasPrices, adjustment) Returns the adjusted gas limit and computed fee
FeeFromGasPrices(gasLimit, gasPrices) Exact ceil(gasLimit × price) fee (rational arithmetic)
Broadcast(ctx, client, txBytes, mode) BROADCAST_MODE_SYNC/ASYNC/BLOCK; errors on non-zero CheckTx code
Simulate(ctx, client, txBytes) Returns gasInfo.gasUsed
SignAndBroadcast(ctx, client, signer, chainID, prefix, msgs, opts, mode, retries) Fetch sequence, build/sign, broadcast; retries on sequence mismatch
BroadcastAndConfirm(ctx, client, txBytes, mode, opts) Broadcast, then wait for inclusion
WaitForTx(ctx, client, hash, opts) Poll GetTx until the tx is included or the timeout elapses
EstimateFeeForAccount(ctx, client, pubKey, pubKeyTypeURL, prefix, chainID, ...) Estimate gas/fee from an account's public key, no private key needed
FetchMinGasPrice(ctx, client) Best-effort node minimum gas price (parses a DecCoin list)

Notes:

  • Fee estimation: build the tx once with BuildAndSign, or use EstimateFee to simulate, apply a gas adjustment (default 1.3), and compute the fee from per-gas-unit prices. Gas prices are chain/operator policy and are not reliably exposed over gRPC, so pass them in (for example {Denom:"uluna", Amount:"0.015"}). Simulation accepts any valid signature — it does not need to match the account's key — but the public key in the signer info must derive to an existing account (the fee-payer lookup). A few chains additionally enforce funds during simulation.
  • KeyAlgorithm is signing.Secp256k1 (standard Cosmos) or signing.EthSecp256k1 (Ethermint/Injective/Sei). ethsecp256k1 chains use different public-key type URLs, so call signing.ResolvePubKeyTypeURL(client.Resolver(), algo) and pass the result to signing.WithPubKeyTypeURL.
  • The bech32 prefix must match the chain's configured prefix (cosmos, osmo, testcore, sei, inj, …). client.GetBech32Prefix() discovers it when the chain advertises cosmos.auth.v1beta1.Query.Bech32Prefix; otherwise supply it.
  • Signatures are deterministic (RFC 6979) 64-byte r||s over SHA-256(signDoc), as required by SIGN_MODE_DIRECT.
  • Message payloads are protobuf-JSON objects with an @type; any type reachable by reflection or WithProtoDir can be signed.
  • Security: private keys and mnemonics are handled in-process. Never log secrets; prefer an external signer in production (implement the Signer interface — hardware, KMS, or remote signers plug in without changes).
  • Test identity: signing.TestMnemonic (about ×11 + abuse) and signing.NewTestSigner(algo) provide a canonical, publicly known key for tests, simulation, and fee estimation. It controls no funds and must never hold real assets. At m/44'/118'/0'/0/0 it derives public key 022fb1…aa5b19, Ethereum address 0x497c…79bd, cosmos1wcf9…taz44 (secp256k1), and genesis1f97…wkqm (ethsecp256k1).
  • Not yet implemented: SIGN_MODE_AMINO_JSON, legacy multisig, and automatic gas-price discovery.
Live verification

The signing path is exercised against live testnets by signing/integration_test.go (gated by LIBYACI_SIGNING_ENDPOINTS). It was verified against secp256k1 chains (Cosmos Hub theta, Celestia mocha-5, Akash sandbox-2, Coreum, Axelar, Noble, Seda, Sei atlantic-2, Terra2 phoenix-1), ethsecp256k1 (Injective-888), and GenesisL1 (genesis_29-2, which uses ethsecp256k1 account keys): transactions were built, signed, decoded by the node, and reached the ante handler (rejected only for missing funds/accounts, which is expected for unfunded test keys). EstimateFee was verified live on GenesisL1 and Terra2 using an existing account's public key signed by an unrelated key. FetchMinGasPrice and WaitForTx were verified live on Terra2 (phoenix-1). Streaming is unit-tested against a dynamic gRPC mock. Self-signed TLS endpoints are reachable with libyaci.WithTLSConfig(&tls.Config{InsecureSkipVerify: true}).

Core Methods

Reflection Catalog
Method Description
Catalog() *Catalog Get reflected services, methods, and message types
SupportsService(service string) bool Check whether a service was advertised by reflection
SupportsMethod(method string) bool Check whether a method is callable according to reflection
ChainInfo() ChainInfo Get configured or detected chain metadata
DetectChainInfo(ctx) Query GetNodeInfo when available and record chain metadata
Dynamic Calls
Method Description
Method(name string) (*Method, error) Get a reusable reflected method handle
Method.NewRequest() Create a descriptor-backed request message
Request.Set(field, value) Set a request field by proto or JSON name
Method.Call(ctx, request) Invoke a method with a dynamic request
Method.EachPage(ctx, values, fn) Iterate standard Cosmos SDK paginated query responses
Response.JSON() Marshal a dynamic response to protobuf JSON
NewMessage(fullName string) Create an arbitrary reflected protobuf message

Legacy JSON helpers remain available:

Method Description
Invoke(method string, request []byte) ([]byte, error) Call any method with protobuf JSON bytes
InvokeRaw(method string, request []byte) (*dynamicpb.Message, error) Call method and return a raw dynamic message
InvokeContext(ctx, method, request) Call with a caller-controlled context
InvokeWithTimeout(method, request, timeout) Call with a per-call timeout
InvokeWithRetry(method, request, maxRetries) Call with an explicit retry budget
Utilities
Method Description
ExtractField(method string, request []byte, field string) (any, error) Call method and extract specific field
DecodeTxBytes(txBytes []byte) ([]byte, error) Decode raw protobuf transaction bytes to JSON
Resolver() *Resolver Get underlying type resolver
ProtoDir() *ProtoDir Get the configured local proto directory (nil if none)
SkippedFiles() []string Reflected files skipped during Dial because they could not be registered
Conn() *grpc.ClientConn Get underlying gRPC connection
Close() error Close client connection
Streaming RPCs

Server-, client-, and bidirectional-streaming methods are supported. All return descriptor-backed *dynamicpb.Message values; always Close() a stream when done.

Method Description
ServerStream(ctx, method, request) (*ServerStream, error) Open a server stream; call Recv() until io.EOF
ClientStream(ctx, method) (*ClientStream, error) Open a client stream; Send() then CloseAndRecv()
BidiStream(ctx, method) (*BidiStream, error) Open a bidirectional stream; Send() / Recv()
Method.ServerStream/ClientStream/BidiStream Descriptor-backed variants taking a *Request

Protobuf extensions are resolved from reflected and fallback descriptors via Resolver.FindExtensionByName / FindExtensionByNumber.

raw_log encoding. The descriptor patch for cosmos-sdk#22414 changes cosmos.base.abci.v1beta1.TxResponse.raw_log from string to bytes, so that field appears base64-encoded in JSON output. Other string fields that contain binary data are patched on demand (UTF-8 recovery) for both reflected and local-proto types.

Retries. Only transient gRPC errors are retried (Unavailable, DeadlineExceeded, ResourceExhausted, Aborted); application errors return immediately. WithDefaultTimeout / InvokeWithTimeout bound the whole invocation, including retries.


Cosmos SDK Convenience Helpers

These helpers wrap common Cosmos SDK query methods when they are advertised by reflection. Use Catalog() and SupportsMethod() for the complete chain-specific capability set, including custom modules.

Tendermint/CometBFT Service
Method Description gRPC Method
GetLatestBlock() (*BlockResponse, error) Get latest block cosmos.base.tendermint.v1beta1.Service.GetLatestBlock
GetLatestBlockHeight() (int64, error) Get latest block height -
GetBlockByHeight(height int64) (*BlockResponse, error) Get block at height cosmos.base.tendermint.v1beta1.Service.GetBlockByHeight
GetEarliestBlockHeight() (int64, error) Find earliest available block (handles pruning) -
GetNodeInfo() (*NodeInfoResponse, error) Get node info cosmos.base.tendermint.v1beta1.Service.GetNodeInfo
GetChainID() (string, error) Get chain ID -
GetSyncing() (bool, error) Check if node is syncing cosmos.base.tendermint.v1beta1.Service.GetSyncing
GetLatestValidatorSet() (*ValidatorSetResponse, error) Get latest validator set cosmos.base.tendermint.v1beta1.Service.GetLatestValidatorSet
GetValidatorSetByHeight(height int64) (*ValidatorSetResponse, error) Get validator set at height cosmos.base.tendermint.v1beta1.Service.GetValidatorSetByHeight
SupportsBlockResults() bool Check whether block-results RPCs are advertised -
GetBlockResults(height int64) (*BlockResultsResponse, error) Get block results when advertised cosmos.base.tendermint.v1beta1.Service.GetBlockResults
GetLatestBlockResults() (*BlockResultsResponse, error) Get latest block results when advertised cosmos.base.tendermint.v1beta1.Service.GetLatestBlockResults
Transaction Service
Method Description gRPC Method
GetTx(hash string) (*TxResponse, error) Get transaction by hash cosmos.tx.v1beta1.Service.GetTx
GetTxsByHeight(height int64) ([]byte, error) Get all transactions at height (raw JSON, follows pagination) cosmos.tx.v1beta1.Service.GetTxsEvent
GetTxsByHeightParsed(height int64) (*TxsEventResponse, error) Get all transactions at height (parsed, follows pagination) cosmos.tx.v1beta1.Service.GetTxsEvent
GetBlockWithTxs(height int64) (*BlockWithTxsResponse, error) Get block with full transactions cosmos.tx.v1beta1.Service.GetBlockWithTxs
Auth Module
Method Description gRPC Method
GetAccount(address string) (*AccountResponse, error) Get account by address cosmos.auth.v1beta1.Query.Account
GetAccounts(paginationKey string) (*AccountsResponse, error) List all accounts cosmos.auth.v1beta1.Query.Accounts
GetAccountInfo(address string) (*AccountInfoResponse, error) Get account info cosmos.auth.v1beta1.Query.AccountInfo
GetModuleAccounts() (map[string]string, error) Get all module accounts (address -> name) cosmos.auth.v1beta1.Query.ModuleAccounts
GetModuleAccountByName(name string) (*AccountResponse, error) Get module account by name cosmos.auth.v1beta1.Query.ModuleAccountByName
GetBech32Prefix() (string, error) Get bech32 address prefix cosmos.auth.v1beta1.Query.Bech32Prefix
GetAuthParams() (*AuthParamsResponse, error) Get auth module params cosmos.auth.v1beta1.Query.Params
Authz Module
Method Description gRPC Method
GetGrants(granter, grantee string) (*GrantsResponse, error) Get grants between accounts cosmos.authz.v1beta1.Query.Grants
GetGranterGrants(granter string) (*GrantsResponse, error) Get all grants by granter cosmos.authz.v1beta1.Query.GranterGrants
GetGranteeGrants(grantee string) (*GrantsResponse, error) Get all grants to grantee cosmos.authz.v1beta1.Query.GranteeGrants
Bank Module
Method Description gRPC Method
GetBalance(address, denom string) (*BalanceResponse, error) Get balance of specific denom cosmos.bank.v1beta1.Query.Balance
GetAllBalances(address string) (*AllBalancesResponse, error) Get all balances for address cosmos.bank.v1beta1.Query.AllBalances
GetSpendableBalances(address string) (*SpendableBalancesResponse, error) Get spendable balances cosmos.bank.v1beta1.Query.SpendableBalances
GetTotalSupply() (*TotalSupplyResponse, error) Get total supply of all coins cosmos.bank.v1beta1.Query.TotalSupply
GetSupplyOf(denom string) (*SupplyOfResponse, error) Get supply of specific denom cosmos.bank.v1beta1.Query.SupplyOf
GetDenomMetadata(denom string) (*DenomMetadataResponse, error) Get denom metadata cosmos.bank.v1beta1.Query.DenomMetadata
GetDenomsMetadata() (*DenomsMetadataResponse, error) Get all denom metadata cosmos.bank.v1beta1.Query.DenomsMetadata
GetDenomOwners(denom string) (*DenomOwnersResponse, error) Get all owners of a denom cosmos.bank.v1beta1.Query.DenomOwners
GetBankParams() (*BankParamsResponse, error) Get bank module params cosmos.bank.v1beta1.Query.Params
Staking Module
Method Description gRPC Method
GetValidators(status string) (*ValidatorsResponse, error) Get validators by status cosmos.staking.v1beta1.Query.Validators
GetAllValidators() (map[string]string, error) Get all validators (handles pagination) -
GetValidator(validatorAddr string) (*ValidatorResponse, error) Get single validator cosmos.staking.v1beta1.Query.Validator
GetStakingPool() (*StakingPoolResponse, error) Get staking pool info cosmos.staking.v1beta1.Query.Pool
GetStakingParams() (*StakingParamsResponse, error) Get staking params cosmos.staking.v1beta1.Query.Params
GetBondDenom() (string, error) Get bond denom -
GetDelegation(delegator, validator string) (*DelegationResponse, error) Get specific delegation cosmos.staking.v1beta1.Query.Delegation
GetDelegations(delegatorAddr string) (*DelegationsResponse, error) Get delegator's delegations cosmos.staking.v1beta1.Query.DelegatorDelegations
GetValidatorDelegations(validatorAddr string) (*DelegationsResponse, error) Get validator's delegations cosmos.staking.v1beta1.Query.ValidatorDelegations
GetDelegatorValidators(delegatorAddr string) (*ValidatorsResponse, error) Get delegator's validators cosmos.staking.v1beta1.Query.DelegatorValidators
GetUnbondingDelegation(delegator, validator string) (*UnbondingDelegationResponse, error) Get unbonding delegation cosmos.staking.v1beta1.Query.UnbondingDelegation
GetDelegatorUnbondingDelegations(delegatorAddr string) (*UnbondingDelegationsResponse, error) Get all unbonding delegations cosmos.staking.v1beta1.Query.DelegatorUnbondingDelegations
GetRedelegations(delegatorAddr string) (*RedelegationsResponse, error) Get redelegations cosmos.staking.v1beta1.Query.Redelegations
Distribution Module
Method Description gRPC Method
GetCommunityPool() (*CommunityPoolResponse, error) Get community pool balance cosmos.distribution.v1beta1.Query.CommunityPool
GetDelegationRewards(delegator, validator string) (*DelegationRewardsResponse, error) Get delegation rewards cosmos.distribution.v1beta1.Query.DelegationRewards
GetDelegationTotalRewards(delegatorAddr string) (*DelegationTotalRewardsResponse, error) Get total delegation rewards cosmos.distribution.v1beta1.Query.DelegationTotalRewards
GetDelegatorWithdrawAddress(delegatorAddr string) (string, error) Get withdraw address cosmos.distribution.v1beta1.Query.DelegatorWithdrawAddress
GetValidatorCommission(validatorAddr string) (*ValidatorCommissionResponse, error) Get validator commission cosmos.distribution.v1beta1.Query.ValidatorCommission
GetValidatorOutstandingRewards(validatorAddr string) (*ValidatorOutstandingRewardsResponse, error) Get outstanding rewards cosmos.distribution.v1beta1.Query.ValidatorOutstandingRewards
GetDistributionParams() (*DistributionParamsResponse, error) Get distribution params cosmos.distribution.v1beta1.Query.Params
Governance Module (v1)
Method Description gRPC Method
GetProposals(status string) (*ProposalsResponse, error) Get proposals by status cosmos.gov.v1.Query.Proposals
GetProposal(proposalID uint64) (*ProposalResponse, error) Get single proposal cosmos.gov.v1.Query.Proposal
GetProposalVotes(proposalID uint64) (*VotesResponse, error) Get proposal votes cosmos.gov.v1.Query.Votes
GetProposalDeposits(proposalID uint64) (*DepositsResponse, error) Get proposal deposits cosmos.gov.v1.Query.Deposits
GetTallyResult(proposalID uint64) (*TallyResultResponse, error) Get proposal tally cosmos.gov.v1.Query.TallyResult
GetGovParams() (*GovParamsResponse, error) Get governance params cosmos.gov.v1.Query.Params
Mint Module
Method Description gRPC Method
GetInflation() (string, error) Get current inflation rate cosmos.mint.v1beta1.Query.Inflation
GetAnnualProvisions() (string, error) Get annual provisions cosmos.mint.v1beta1.Query.AnnualProvisions
GetMintParams() (*MintParamsResponse, error) Get mint params cosmos.mint.v1beta1.Query.Params
Slashing Module
Method Description gRPC Method
GetSigningInfo(consAddr string) (*SigningInfoResponse, error) Get validator signing info cosmos.slashing.v1beta1.Query.SigningInfo
GetSigningInfos() (*SigningInfosResponse, error) Get all signing infos cosmos.slashing.v1beta1.Query.SigningInfos
GetSlashingParams() (*SlashingParamsResponse, error) Get slashing params cosmos.slashing.v1beta1.Query.Params
Evidence Module
Method Description gRPC Method
GetEvidence(hash string) (*EvidenceResponse, error) Get evidence by hash cosmos.evidence.v1beta1.Query.Evidence
GetAllEvidence() (*AllEvidenceResponse, error) Get all evidence cosmos.evidence.v1beta1.Query.AllEvidence
Feegrant Module
Method Description gRPC Method
GetAllowance(granter, grantee string) (*AllowanceResponse, error) Get fee allowance cosmos.feegrant.v1beta1.Query.Allowance
GetAllowances(grantee string) (*AllowancesResponse, error) Get all allowances for grantee cosmos.feegrant.v1beta1.Query.Allowances
GetAllowancesByGranter(granter string) (*AllowancesResponse, error) Get all allowances by granter cosmos.feegrant.v1beta1.Query.AllowancesByGranter
Upgrade Module
Method Description gRPC Method
GetCurrentPlan() (*CurrentPlanResponse, error) Get current upgrade plan cosmos.upgrade.v1beta1.Query.CurrentPlan
GetAppliedPlan(name string) (*AppliedPlanResponse, error) Get applied plan height cosmos.upgrade.v1beta1.Query.AppliedPlan
GetModuleVersions() (*ModuleVersionsResponse, error) Get module versions cosmos.upgrade.v1beta1.Query.ModuleVersions
IBC Client Module
Method Description gRPC Method
GetIBCClientStates() (*IBCClientStatesResponse, error) Get all IBC client states ibc.core.client.v1.Query.ClientStates
GetIBCClientState(clientID string) (*IBCClientStateResponse, error) Get IBC client state ibc.core.client.v1.Query.ClientState
IBC Connection Module
Method Description gRPC Method
GetIBCConnections() (*IBCConnectionsResponse, error) Get all IBC connections ibc.core.connection.v1.Query.Connections
GetIBCConnection(connectionID string) (*IBCConnectionResponse, error) Get IBC connection ibc.core.connection.v1.Query.Connection
GetIBCClientConnections(clientID string) ([]string, error) Get connections for client ibc.core.connection.v1.Query.ClientConnections
IBC Channel Module
Method Description gRPC Method
GetIBCChannels() (*IBCChannelsResponse, error) Get all IBC channels ibc.core.channel.v1.Query.Channels
GetIBCChannel(portID, channelID string) (*IBCChannelResponse, error) Get IBC channel ibc.core.channel.v1.Query.Channel
GetIBCConnectionChannels(connectionID string) (*IBCChannelsResponse, error) Get channels for connection ibc.core.channel.v1.Query.ConnectionChannels
IBC Transfer Module
Method Description gRPC Method
GetIBCDenomTrace(hash string) (*IBCDenomTraceResponse, error) Get denom trace by hash ibc.applications.transfer.v1.Query.Denom
GetIBCDenomTraces() (*IBCDenomTracesResponse, error) Get all denom traces ibc.applications.transfer.v1.Query.Denoms
GetIBCDenomHash(trace string) (string, error) Calculate denom hash ibc.applications.transfer.v1.Query.DenomHash
GetIBCEscrowAddress(portID, channelID string) (string, error) Get escrow address ibc.applications.transfer.v1.Query.EscrowAddress
GetIBCTotalEscrowForDenom(denom string) (*IBCTotalEscrowResponse, error) Get total escrowed amount ibc.applications.transfer.v1.Query.TotalEscrowForDenom
GetIBCTransferParams() (*IBCTransferParamsResponse, error) Get IBC transfer params ibc.applications.transfer.v1.Query.Params

gRPC Method Reference

For reference, here are the underlying gRPC method paths used by the convenience methods. These can also be called directly via client.Invoke().

Tendermint/CometBFT Service
cosmos.base.tendermint.v1beta1.Service.GetLatestBlock
cosmos.base.tendermint.v1beta1.Service.GetBlockByHeight
cosmos.base.tendermint.v1beta1.Service.GetNodeInfo
cosmos.base.tendermint.v1beta1.Service.GetSyncing
cosmos.base.tendermint.v1beta1.Service.GetLatestValidatorSet
cosmos.base.tendermint.v1beta1.Service.GetValidatorSetByHeight
cosmos.base.tendermint.v1beta1.Service.GetBlockResults
cosmos.base.tendermint.v1beta1.Service.GetLatestBlockResults
Transaction Service
cosmos.tx.v1beta1.Service.GetTx
cosmos.tx.v1beta1.Service.GetTxsEvent
cosmos.tx.v1beta1.Service.GetBlockWithTxs
cosmos.tx.v1beta1.Service.BroadcastTx
cosmos.tx.v1beta1.Service.Simulate
Auth Module
cosmos.auth.v1beta1.Query.Account
cosmos.auth.v1beta1.Query.Accounts
cosmos.auth.v1beta1.Query.AccountInfo
cosmos.auth.v1beta1.Query.ModuleAccounts
cosmos.auth.v1beta1.Query.ModuleAccountByName
cosmos.auth.v1beta1.Query.Bech32Prefix
cosmos.auth.v1beta1.Query.Params
Authz Module
cosmos.authz.v1beta1.Query.Grants
cosmos.authz.v1beta1.Query.GranterGrants
cosmos.authz.v1beta1.Query.GranteeGrants
Bank Module
cosmos.bank.v1beta1.Query.Balance
cosmos.bank.v1beta1.Query.AllBalances
cosmos.bank.v1beta1.Query.SpendableBalances
cosmos.bank.v1beta1.Query.TotalSupply
cosmos.bank.v1beta1.Query.SupplyOf
cosmos.bank.v1beta1.Query.DenomMetadata
cosmos.bank.v1beta1.Query.DenomsMetadata
cosmos.bank.v1beta1.Query.DenomOwners
cosmos.bank.v1beta1.Query.Params
Staking Module
cosmos.staking.v1beta1.Query.Validators
cosmos.staking.v1beta1.Query.Validator
cosmos.staking.v1beta1.Query.Pool
cosmos.staking.v1beta1.Query.Params
cosmos.staking.v1beta1.Query.Delegation
cosmos.staking.v1beta1.Query.DelegatorDelegations
cosmos.staking.v1beta1.Query.DelegatorUnbondingDelegations
cosmos.staking.v1beta1.Query.DelegatorValidators
cosmos.staking.v1beta1.Query.ValidatorDelegations
cosmos.staking.v1beta1.Query.UnbondingDelegation
cosmos.staking.v1beta1.Query.Redelegations
cosmos.staking.v1beta1.Query.HistoricalInfo
Distribution Module
cosmos.distribution.v1beta1.Query.CommunityPool
cosmos.distribution.v1beta1.Query.DelegationRewards
cosmos.distribution.v1beta1.Query.DelegationTotalRewards
cosmos.distribution.v1beta1.Query.DelegatorWithdrawAddress
cosmos.distribution.v1beta1.Query.ValidatorCommission
cosmos.distribution.v1beta1.Query.ValidatorOutstandingRewards
cosmos.distribution.v1beta1.Query.ValidatorSlashes
cosmos.distribution.v1beta1.Query.Params
Governance Module (v1)
cosmos.gov.v1.Query.Proposals
cosmos.gov.v1.Query.Proposal
cosmos.gov.v1.Query.Votes
cosmos.gov.v1.Query.Deposits
cosmos.gov.v1.Query.TallyResult
cosmos.gov.v1.Query.Params
Mint Module
cosmos.mint.v1beta1.Query.Inflation
cosmos.mint.v1beta1.Query.AnnualProvisions
cosmos.mint.v1beta1.Query.Params
Slashing Module
cosmos.slashing.v1beta1.Query.SigningInfo
cosmos.slashing.v1beta1.Query.SigningInfos
cosmos.slashing.v1beta1.Query.Params
Evidence Module
cosmos.evidence.v1beta1.Query.Evidence
cosmos.evidence.v1beta1.Query.AllEvidence
Feegrant Module
cosmos.feegrant.v1beta1.Query.Allowance
cosmos.feegrant.v1beta1.Query.Allowances
cosmos.feegrant.v1beta1.Query.AllowancesByGranter
Upgrade Module
cosmos.upgrade.v1beta1.Query.CurrentPlan
cosmos.upgrade.v1beta1.Query.AppliedPlan
cosmos.upgrade.v1beta1.Query.ModuleVersions
IBC Core - Client
ibc.core.client.v1.Query.ClientStates
ibc.core.client.v1.Query.ClientState
ibc.core.client.v1.Query.ConsensusStates
ibc.core.client.v1.Query.ClientParams
IBC Core - Connection
ibc.core.connection.v1.Query.Connections
ibc.core.connection.v1.Query.Connection
ibc.core.connection.v1.Query.ClientConnections
ibc.core.connection.v1.Query.ConnectionParams
IBC Core - Channel
ibc.core.channel.v1.Query.Channels
ibc.core.channel.v1.Query.Channel
ibc.core.channel.v1.Query.ConnectionChannels
ibc.core.channel.v1.Query.PacketCommitments
ibc.core.channel.v1.Query.PacketAcknowledgements
ibc.core.channel.v1.Query.UnreceivedPackets
ibc.core.channel.v1.Query.UnreceivedAcks
IBC Applications - Transfer
ibc.applications.transfer.v1.Query.Denom
ibc.applications.transfer.v1.Query.Denoms
ibc.applications.transfer.v1.Query.DenomHash
ibc.applications.transfer.v1.Query.EscrowAddress
ibc.applications.transfer.v1.Query.TotalEscrowForDenom
ibc.applications.transfer.v1.Query.Params

Thread Safety

The client is safe for concurrent use from multiple goroutines. The internal type resolver uses proper synchronization to handle concurrent symbol lookups, ensuring that multiple goroutines fetching the same type will coordinate correctly without race conditions.

How It Works

  1. Connects to the gRPC server
  2. Fetches all service descriptors via the reflection API
    • Tries grpc.reflection.v1 first, falls back to grpc.reflection.v1alpha for older servers
    • Caches the detected version per connection for performance
  3. Builds a local proto registry from the descriptors
  4. Creates dynamic request messages from JSON input
  5. Invokes methods and marshals responses back to JSON
  6. Fetches additional descriptors on-demand for unknown Any types
  7. Falls back to pre-compiled descriptors for deprecated types not in reflection

Example CLI

go build -o grpc-cli ./examples/cli

./grpc-cli -addr localhost:9090 -insecure -list
./grpc-cli -addr localhost:9090 -insecure -list -json
./grpc-cli -addr localhost:9090 -insecure -method "cosmos.bank.v1beta1.Query.TotalSupply" -request "{}"
./grpc-cli -addr localhost:9090 -insecure -protodir ./protos -method "cosmos.tx.v1beta1.Service.GetTx" -request '{"hash":"..."}'

License

MIT License - see LICENSE for details.

Documentation

Overview

Package libyaci provides a dynamic gRPC client that uses server reflection to invoke methods without precompiled protobuf stubs.

Basic Usage

client, err := libyaci.Dial(ctx, "localhost:9090", libyaci.WithInsecure())
if err != nil {
    log.Fatal(err)
}
defer client.Close()

resp, err := client.Invoke(
    "cosmos.bank.v1beta1.Query.Balance",
    []byte(`{"address":"cosmos1...", "denom":"uatom"}`),
)

Invocation Methods

Invoke returns JSON bytes:

resp, err := client.Invoke("package.Service.Method", []byte(`{}`))

InvokeJSON marshals/unmarshals Go types:

var result ResponseType
err := client.InvokeJSON("package.Service.Method", request, &result)

InvokeRaw returns the dynamic protobuf message:

msg, err := client.InvokeRaw("package.Service.Method", nil)
field := msg.ProtoReflect().Get(msg.Descriptor().Fields().ByName("field"))

Service Discovery

services := client.ListServices()
methods, err := client.ListMethods("cosmos.bank.v1beta1.Query")
input, output, err := client.DescribeMethod("cosmos.bank.v1beta1.Query.Balance")

Cosmos SDK Convenience Methods

High-level methods for common Cosmos SDK queries:

// Block queries
block, err := client.GetLatestBlock()
height, err := client.GetLatestBlockHeight()
block, err := client.GetBlockByHeight(12345)
earliest, err := client.GetEarliestBlockHeight()

// Transaction queries
txs, err := client.GetTxsByHeight(12345)
txsParsed, err := client.GetTxsByHeightParsed(12345)

// Chain info
chainID, err := client.GetChainID()
denom, err := client.GetBondDenom()

// Account queries
validators, err := client.GetAllValidators()  // returns map[address]moniker
modules, err := client.GetModuleAccounts()    // returns map[address]name
balance, err := client.GetBalance(address, denom)
balances, err := client.GetAllBalances(address)
delegations, err := client.GetDelegations(delegatorAddr)

Configuration

client, err := libyaci.Dial(ctx, "grpc.example.com:443",
    libyaci.WithInsecure(),
    libyaci.WithMaxRetries(5),
    libyaci.WithMaxRecvMsgSize(16*1024*1024),
    libyaci.WithDialTimeout(30*time.Second),
    libyaci.WithDefaultTimeout(10*time.Second), // per-call timeout
    libyaci.WithProtoDir("./protos"),           // local protos for deprecated types
)

ALPN Connection Issues

If connections fail with "missing selected ALPN property" errors (common with older Cosmos nodes), import the alpnfix subpackage before any gRPC imports:

import _ "github.com/Cordtus/libyaci/alpnfix"

Deprecated Type Resolution

Historical blockchain data may contain message types from deprecated modules that no longer exist on the server. Use WithProtoDir to provide local .proto files for these types:

client, err := libyaci.Dial(ctx, addr,
    libyaci.WithProtoDir("./protos"),  // protos/tendermint/liquidity/v1beta1/*.proto
)

Thread Safety

Client and Resolver are safe for concurrent use. The proto registry uses read-write locks when fetching descriptors on-demand.

Performance

Initial connection fetches all descriptors from the server, which may take several seconds for servers with many services. Subsequent calls use cached descriptors. Reuse the client instance for best performance.

Index

Constants

This section is empty.

Variables

View Source
var ErrUnsupportedMethod = errors.New("unsupported method")

ErrUnsupportedMethod is returned when the connected server does not expose a requested method through reflection.

Functions

func DisableALPNEnforcement added in v0.9.0

func DisableALPNEnforcement()

DisableALPNEnforcement globally disables ALPN enforcement for all gRPC connections in the process. This is useful when you know all your target servers don't support ALPN. Call this before creating any clients.

This function is safe to call multiple times; it only takes effect once.

func IsUnsupportedMethod added in v1.0.0

func IsUnsupportedMethod(err error) bool

IsUnsupportedMethod reports whether err indicates missing reflected method support on the connected server.

Types

type AccountInfoResponse added in v0.3.0

type AccountInfoResponse struct {
	Info struct {
		Address       string `json:"address"`
		PubKey        any    `json:"pubKey"`
		AccountNumber string `json:"accountNumber"`
		Sequence      string `json:"sequence"`
	} `json:"info"`
}

AccountInfoResponse represents account info response.

type AccountResponse added in v0.3.0

type AccountResponse struct {
	Account json.RawMessage `json:"account"`
}

AccountResponse represents an account query response.

type AccountsResponse added in v0.3.0

type AccountsResponse struct {
	Accounts   []json.RawMessage `json:"accounts"`
	Pagination *PaginationResp   `json:"pagination,omitempty"`
}

AccountsResponse represents the accounts query response.

type AllBalancesResponse added in v0.3.0

type AllBalancesResponse struct {
	Balances   []Coin          `json:"balances"`
	Pagination *PaginationResp `json:"pagination,omitempty"`
}

AllBalancesResponse represents multiple coin balances.

type AllEvidenceResponse added in v0.3.0

type AllEvidenceResponse struct {
	Evidence   []json.RawMessage `json:"evidence"`
	Pagination *PaginationResp   `json:"pagination,omitempty"`
}

AllEvidenceResponse represents all evidence response.

type AllowanceResponse added in v0.3.0

type AllowanceResponse struct {
	Allowance json.RawMessage `json:"allowance"`
}

AllowanceResponse represents fee allowance response.

type AllowancesResponse added in v0.3.0

type AllowancesResponse struct {
	Allowances []json.RawMessage `json:"allowances"`
	Pagination *PaginationResp   `json:"pagination,omitempty"`
}

AllowancesResponse represents fee allowances response.

type AnnualProvisionsResponse added in v0.3.0

type AnnualProvisionsResponse struct {
	AnnualProvisions string `json:"annualProvisions"`
}

AnnualProvisionsResponse represents annual provisions response.

type AppliedPlanResponse added in v0.3.0

type AppliedPlanResponse struct {
	Height string `json:"height"`
}

AppliedPlanResponse represents applied plan response.

type AuthParamsResponse added in v0.3.0

type AuthParamsResponse struct {
	Params struct {
		MaxMemoCharacters      string `json:"maxMemoCharacters"`
		TxSigLimit             string `json:"txSigLimit"`
		TxSizeCostPerByte      string `json:"txSizeCostPerByte"`
		SigVerifyCostEd25519   string `json:"sigVerifyCostEd25519"`
		SigVerifyCostSecp256k1 string `json:"sigVerifyCostSecp256k1"`
	} `json:"params"`
}

AuthParamsResponse represents auth params response.

type BalanceResponse added in v0.3.0

type BalanceResponse struct {
	Balance struct {
		Denom  string `json:"denom"`
		Amount string `json:"amount"`
	} `json:"balance"`
}

BalanceResponse represents a single coin balance.

type BankParamsResponse added in v0.3.0

type BankParamsResponse struct {
	Params struct {
		SendEnabled        []any `json:"sendEnabled"`
		DefaultSendEnabled bool  `json:"defaultSendEnabled"`
	} `json:"params"`
}

BankParamsResponse represents bank params response.

type Bech32PrefixResponse added in v0.3.0

type Bech32PrefixResponse struct {
	Bech32Prefix string `json:"bech32Prefix"`
}

Bech32PrefixResponse represents bech32 prefix response.

type BidiStream added in v1.5.0

type BidiStream struct {
	// contains filtered or unexported fields
}

BidiStream is a handle for a bidirectional-streaming RPC.

func (*BidiStream) Close added in v1.5.0

func (s *BidiStream) Close()

Close cancels the stream and releases its resources.

func (*BidiStream) CloseSend added in v1.5.0

func (s *BidiStream) CloseSend() error

CloseSend half-closes the send direction.

func (*BidiStream) Context added in v1.5.0

func (s *BidiStream) Context() context.Context

Context returns the stream context.

func (*BidiStream) Recv added in v1.5.0

func (s *BidiStream) Recv() (*dynamicpb.Message, error)

Recv receives the next response message.

func (*BidiStream) Send added in v1.5.0

func (s *BidiStream) Send(msg *dynamicpb.Message) error

Send sends the next request message.

type BlockResponse added in v0.3.0

type BlockResponse struct {
	Block struct {
		Header struct {
			Height  string `json:"height"`
			Time    string `json:"time"`
			ChainID string `json:"chainId"`
		} `json:"header"`
		Data struct {
			Txs []string `json:"txs"`
		} `json:"data"`
	} `json:"block"`
	BlockID struct {
		Hash string `json:"hash"`
	} `json:"blockId"`
}

BlockResponse represents the structure returned by GetLatestBlock and GetBlockByHeight.

type BlockResultsResponse added in v1.0.0

type BlockResultsResponse struct {
	Height               int64             `json:"height,string"`
	TxsResults           []ExecTxResult    `json:"txsResults,omitempty"`
	FinalizeBlockEvents  []Event           `json:"finalizeBlockEvents,omitempty"`
	ValidatorUpdates     []ValidatorUpdate `json:"validatorUpdates,omitempty"`
	ConsensusParamUpdate json.RawMessage   `json:"consensusParamUpdates,omitempty"`
	AppHash              string            `json:"appHash,omitempty"`
}

BlockResultsResponse represents the response from GetBlockResults and GetLatestBlockResults. Contains finalize_block_events which include consensus-level events like slashing and jailing.

func (*BlockResultsResponse) FindSlashingEvents added in v1.0.0

func (r *BlockResultsResponse) FindSlashingEvents() []Event

FindSlashingEvents searches block results for slashing-related events. Returns events with types: "slash", "liveness", "jail".

type BlockWithTxsResponse added in v0.3.0

type BlockWithTxsResponse struct {
	Txs        []json.RawMessage `json:"txs"`
	BlockID    json.RawMessage   `json:"blockId"`
	Block      json.RawMessage   `json:"block"`
	Pagination *PaginationResp   `json:"pagination,omitempty"`
}

BlockWithTxsResponse represents block with transactions response.

type Catalog added in v1.0.0

type Catalog struct {
	// contains filtered or unexported fields
}

Catalog is an immutable snapshot of services, methods, and message types advertised by server reflection at client initialization time.

func (*Catalog) ChainInfo added in v1.0.0

func (c *Catalog) ChainInfo() ChainInfo

ChainInfo returns configured or detected chain metadata.

func (*Catalog) HasMethod added in v1.0.0

func (c *Catalog) HasMethod(method string) bool

HasMethod reports whether the connected server exposes a method.

func (*Catalog) HasService added in v1.0.0

func (c *Catalog) HasService(service string) bool

HasService reports whether the connected server exposes a service.

func (*Catalog) MessageTypesByPackage added in v1.0.0

func (c *Catalog) MessageTypesByPackage(pkg string) []MessageInfo

MessageTypesByPackage returns reflected messages in the requested proto package sorted by full name.

func (*Catalog) Messages added in v1.0.0

func (c *Catalog) Messages() []MessageInfo

Messages returns all reflected message types sorted by full name.

func (*Catalog) Method added in v1.0.0

func (c *Catalog) Method(method string) (MethodInfo, bool)

Method returns metadata for a reflected method.

func (*Catalog) Methods added in v1.0.0

func (c *Catalog) Methods() []MethodInfo

Methods returns all reflected methods sorted by full name.

func (*Catalog) QueryServices added in v1.0.0

func (c *Catalog) QueryServices() []ServiceInfo

QueryServices returns advertised services named Query, which is the standard Cosmos SDK module query-service convention.

func (*Catalog) Service added in v1.0.0

func (c *Catalog) Service(service string) (ServiceInfo, bool)

Service returns metadata for a reflected service.

func (*Catalog) Services added in v1.0.0

func (c *Catalog) Services() []ServiceInfo

Services returns all reflected services sorted by name.

type ChainInfo added in v1.0.0

type ChainInfo struct {
	ChainID           string
	AppName           string
	AppVersion        string
	SDKVersion        string
	MinSDKVersion     string
	ReflectionVersion string
}

ChainInfo contains configured or detected metadata about the connected chain. Reflected capabilities remain the source of truth for method availability.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a dynamic gRPC client that uses server reflection to invoke methods.

func Dial

func Dial(ctx context.Context, address string, opts ...Option) (*Client, error)

Dial creates a new reflection-based gRPC client connected to the specified address. The client will automatically fetch proto descriptors from the server using reflection.

func (*Client) BidiStream added in v1.5.0

func (c *Client) BidiStream(ctx context.Context, method string) (*BidiStream, error)

BidiStream opens a bidirectional-streaming call.

func (*Client) Catalog added in v1.0.0

func (c *Client) Catalog() *Catalog

Catalog returns the client's reflected capability catalog.

func (*Client) ChainInfo added in v1.0.0

func (c *Client) ChainInfo() ChainInfo

ChainInfo returns configured or detected chain metadata.

func (*Client) ClientStream added in v1.5.0

func (c *Client) ClientStream(ctx context.Context, method string) (*ClientStream, error)

ClientStream opens a client-streaming call.

func (*Client) Close

func (c *Client) Close() error

Close closes the client connection.

func (*Client) Conn

func (c *Client) Conn() *grpc.ClientConn

Conn returns the underlying gRPC connection.

func (*Client) DecodeTxBytes added in v0.2.0

func (c *Client) DecodeTxBytes(rawBytes []byte) ([]byte, error)

DecodeTxBytes decodes raw protobuf transaction bytes to JSON. The raw bytes should be the protobuf-encoded cosmos.tx.v1beta1.Tx message. Handles UTF-8 errors by patching string fields that contain binary data.

func (*Client) DescribeMethod

func (c *Client) DescribeMethod(method string) (input, output string, err error)

DescribeMethod returns a human-readable description of a method's input and output types.

func (*Client) DetectChainInfo added in v1.0.0

func (c *Client) DetectChainInfo(ctx context.Context) (ChainInfo, error)

DetectChainInfo queries GetNodeInfo when available and records chain metadata for diagnostics. Missing GetNodeInfo returns partial configured metadata.

func (*Client) ExtractField

func (c *Client) ExtractField(method string, request []byte, fieldName string) (interface{}, error)

ExtractField invokes a method and extracts a specific field from the response.

func (*Client) GetAccount added in v0.3.0

func (c *Client) GetAccount(address string) (*AccountResponse, error)

GetAccount fetches account information by address.

func (*Client) GetAccountInfo added in v0.3.0

func (c *Client) GetAccountInfo(address string) (*AccountInfoResponse, error)

GetAccountInfo fetches account info (address, pubkey, account number, sequence).

func (*Client) GetAccounts added in v0.3.0

func (c *Client) GetAccounts(paginationKey string) (*AccountsResponse, error)

GetAccounts fetches all accounts with pagination.

func (*Client) GetAllBalances added in v0.3.0

func (c *Client) GetAllBalances(address string) (*AllBalancesResponse, error)

GetAllBalances fetches all balances for an address.

func (*Client) GetAllEvidence added in v0.3.0

func (c *Client) GetAllEvidence() (*AllEvidenceResponse, error)

GetAllEvidence fetches all evidence.

func (*Client) GetAllValidators added in v0.3.0

func (c *Client) GetAllValidators() (map[string]string, error)

GetAllValidators fetches all validators (all statuses) with pagination handling. Returns a map of operator address -> moniker.

func (*Client) GetAllowance added in v0.3.0

func (c *Client) GetAllowance(granter, grantee string) (*AllowanceResponse, error)

GetAllowance fetches the fee allowance of a grantee by granter.

func (*Client) GetAllowances added in v0.3.0

func (c *Client) GetAllowances(grantee string) (*AllowancesResponse, error)

GetAllowances fetches all allowances for a grantee.

func (*Client) GetAllowancesByGranter added in v0.3.0

func (c *Client) GetAllowancesByGranter(granter string) (*AllowancesResponse, error)

GetAllowancesByGranter fetches all allowances given by a granter.

func (*Client) GetAnnualProvisions added in v0.3.0

func (c *Client) GetAnnualProvisions() (string, error)

GetAnnualProvisions fetches the current annual provisions.

func (*Client) GetAppliedPlan added in v0.3.0

func (c *Client) GetAppliedPlan(name string) (*AppliedPlanResponse, error)

GetAppliedPlan fetches the height at which a plan was applied.

func (*Client) GetAuthParams added in v0.3.0

func (c *Client) GetAuthParams() (*AuthParamsResponse, error)

GetAuthParams fetches auth module parameters.

func (*Client) GetBalance added in v0.3.0

func (c *Client) GetBalance(address, denom string) (*BalanceResponse, error)

GetBalance fetches the balance of a specific denom for an address.

func (*Client) GetBankParams added in v0.3.0

func (c *Client) GetBankParams() (*BankParamsResponse, error)

GetBankParams fetches bank module parameters.

func (*Client) GetBech32Prefix added in v0.3.0

func (c *Client) GetBech32Prefix() (string, error)

GetBech32Prefix fetches the bech32 prefix used by the chain.

func (*Client) GetBlockByHeight added in v0.3.0

func (c *Client) GetBlockByHeight(height int64) (*BlockResponse, error)

GetBlockByHeight fetches block information for a given height.

func (*Client) GetBlockResults added in v1.0.0

func (c *Client) GetBlockResults(height int64) (*BlockResultsResponse, error)

GetBlockResults fetches block results for a given height. Block results contain finalize_block_events which include consensus-level events like validator slashing, jailing, and validator set updates. Requires cosmos-sdk v0.53+ with the GetBlockResults RPC enabled.

func (*Client) GetBlockWithTxs added in v0.3.0

func (c *Client) GetBlockWithTxs(height int64) (*BlockWithTxsResponse, error)

GetBlockWithTxs fetches a block with all transactions at a specific height.

func (*Client) GetBondDenom added in v0.3.0

func (c *Client) GetBondDenom() (string, error)

GetBondDenom fetches the bond denom from staking params.

func (*Client) GetChainID added in v0.3.0

func (c *Client) GetChainID() (string, error)

GetChainID extracts the chain ID from node info.

func (*Client) GetCommunityPool added in v0.3.0

func (c *Client) GetCommunityPool() (*CommunityPoolResponse, error)

GetCommunityPool fetches the community pool balance.

func (*Client) GetCurrentPlan added in v0.3.0

func (c *Client) GetCurrentPlan() (*CurrentPlanResponse, error)

GetCurrentPlan fetches the current upgrade plan (if any).

func (*Client) GetDelegation added in v0.3.0

func (c *Client) GetDelegation(delegatorAddr, validatorAddr string) (*DelegationResponse, error)

GetDelegation fetches a specific delegation.

func (*Client) GetDelegationRewards added in v0.3.0

func (c *Client) GetDelegationRewards(delegatorAddr, validatorAddr string) (*DelegationRewardsResponse, error)

GetDelegationRewards fetches rewards for a specific delegation.

func (*Client) GetDelegationTotalRewards added in v0.3.0

func (c *Client) GetDelegationTotalRewards(delegatorAddr string) (*DelegationTotalRewardsResponse, error)

GetDelegationTotalRewards fetches total rewards for all delegations of a delegator.

func (*Client) GetDelegations added in v0.3.0

func (c *Client) GetDelegations(delegatorAddr string) (*DelegationsResponse, error)

GetDelegations fetches delegations for a delegator address.

func (*Client) GetDelegatorUnbondingDelegations added in v0.3.0

func (c *Client) GetDelegatorUnbondingDelegations(delegatorAddr string) (*UnbondingDelegationsResponse, error)

GetDelegatorUnbondingDelegations fetches all unbonding delegations for a delegator.

func (*Client) GetDelegatorValidators added in v0.3.0

func (c *Client) GetDelegatorValidators(delegatorAddr string) (*ValidatorsResponse, error)

GetDelegatorValidators fetches all validators a delegator is delegating to.

func (*Client) GetDelegatorWithdrawAddress added in v0.3.0

func (c *Client) GetDelegatorWithdrawAddress(delegatorAddr string) (string, error)

GetDelegatorWithdrawAddress fetches the withdraw address for a delegator.

func (*Client) GetDenomMetadata added in v0.3.0

func (c *Client) GetDenomMetadata(denom string) (*DenomMetadataResponse, error)

GetDenomMetadata fetches metadata for a specific denomination.

func (*Client) GetDenomOwners added in v0.3.0

func (c *Client) GetDenomOwners(denom string) (*DenomOwnersResponse, error)

GetDenomOwners fetches all owners of a specific denomination.

func (*Client) GetDenomsMetadata added in v0.3.0

func (c *Client) GetDenomsMetadata() (*DenomsMetadataResponse, error)

GetDenomsMetadata fetches metadata for all denominations.

func (*Client) GetDistributionParams added in v0.3.0

func (c *Client) GetDistributionParams() (*DistributionParamsResponse, error)

GetDistributionParams fetches distribution module parameters.

func (*Client) GetEarliestBlockHeight added in v0.3.0

func (c *Client) GetEarliestBlockHeight() (int64, error)

GetEarliestBlockHeight finds the earliest available block height. First tries to fetch block 1; if pruned, parses error or falls back to binary search.

func (*Client) GetEvidence added in v0.3.0

func (c *Client) GetEvidence(hash string) (*EvidenceResponse, error)

GetEvidence fetches a specific evidence by hash.

func (*Client) GetGovParams added in v0.3.0

func (c *Client) GetGovParams() (*GovParamsResponse, error)

GetGovParams fetches governance module parameters.

func (*Client) GetGranteeGrants added in v0.3.0

func (c *Client) GetGranteeGrants(grantee string) (*GrantsResponse, error)

GetGranteeGrants fetches all grants received by a grantee.

func (*Client) GetGranterGrants added in v0.3.0

func (c *Client) GetGranterGrants(granter string) (*GrantsResponse, error)

GetGranterGrants fetches all grants given by a granter.

func (*Client) GetGrants added in v0.3.0

func (c *Client) GetGrants(granter, grantee string) (*GrantsResponse, error)

GetGrants fetches grants for a granter/grantee pair.

func (*Client) GetIBCChannel added in v0.3.0

func (c *Client) GetIBCChannel(portID, channelID string) (*IBCChannelResponse, error)

GetIBCChannel fetches a specific IBC channel.

func (*Client) GetIBCChannels added in v0.3.0

func (c *Client) GetIBCChannels() (*IBCChannelsResponse, error)

GetIBCChannels fetches all IBC channels.

func (*Client) GetIBCClientConnections added in v0.3.0

func (c *Client) GetIBCClientConnections(clientID string) ([]string, error)

GetIBCClientConnections fetches all connections for a client.

func (*Client) GetIBCClientState added in v0.3.0

func (c *Client) GetIBCClientState(clientID string) (*IBCClientStateResponse, error)

GetIBCClientState fetches a specific IBC client state.

func (*Client) GetIBCClientStates added in v0.3.0

func (c *Client) GetIBCClientStates() (*IBCClientStatesResponse, error)

GetIBCClientStates fetches all IBC client states.

func (*Client) GetIBCConnection added in v0.3.0

func (c *Client) GetIBCConnection(connectionID string) (*IBCConnectionResponse, error)

GetIBCConnection fetches a specific IBC connection.

func (*Client) GetIBCConnectionChannels added in v0.3.0

func (c *Client) GetIBCConnectionChannels(connectionID string) (*IBCChannelsResponse, error)

GetIBCConnectionChannels fetches all channels for a connection.

func (*Client) GetIBCConnections added in v0.3.0

func (c *Client) GetIBCConnections() (*IBCConnectionsResponse, error)

GetIBCConnections fetches all IBC connections.

func (*Client) GetIBCDenomHash added in v0.3.0

func (c *Client) GetIBCDenomHash(trace string) (string, error)

GetIBCDenomHash calculates the hash for a denom trace path.

func (*Client) GetIBCDenomTrace added in v0.3.0

func (c *Client) GetIBCDenomTrace(hash string) (*IBCDenomTraceResponse, error)

GetIBCDenomTrace fetches the denom trace for an IBC denom hash.

func (*Client) GetIBCDenomTraces added in v0.3.0

func (c *Client) GetIBCDenomTraces() (*IBCDenomTracesResponse, error)

GetIBCDenomTraces fetches all denom traces.

func (*Client) GetIBCEscrowAddress added in v0.3.0

func (c *Client) GetIBCEscrowAddress(portID, channelID string) (string, error)

GetIBCEscrowAddress fetches the escrow address for a channel.

func (*Client) GetIBCTotalEscrowForDenom added in v0.3.0

func (c *Client) GetIBCTotalEscrowForDenom(denom string) (*IBCTotalEscrowResponse, error)

GetIBCTotalEscrowForDenom fetches total amount escrowed for a denom.

func (*Client) GetIBCTransferParams added in v0.3.0

func (c *Client) GetIBCTransferParams() (*IBCTransferParamsResponse, error)

GetIBCTransferParams fetches IBC transfer module parameters.

func (*Client) GetInflation added in v0.3.0

func (c *Client) GetInflation() (string, error)

GetInflation fetches the current inflation rate.

func (*Client) GetLatestBlock added in v0.3.0

func (c *Client) GetLatestBlock() (*BlockResponse, error)

GetLatestBlock fetches the latest block from the chain.

func (*Client) GetLatestBlockHeight added in v0.3.0

func (c *Client) GetLatestBlockHeight() (int64, error)

GetLatestBlockHeight returns the latest block height as an int64.

func (*Client) GetLatestBlockResults added in v1.0.0

func (c *Client) GetLatestBlockResults() (*BlockResultsResponse, error)

GetLatestBlockResults fetches block results for the latest block. Block results contain finalize_block_events which include consensus-level events like validator slashing, jailing, and validator set updates. Requires cosmos-sdk v0.53+ with the GetBlockResults RPC enabled.

func (*Client) GetLatestValidatorSet added in v0.3.0

func (c *Client) GetLatestValidatorSet() (*ValidatorSetResponse, error)

GetLatestValidatorSet fetches the latest validator set.

func (*Client) GetMethodDescriptor

func (c *Client) GetMethodDescriptor(method string) (protoreflect.MethodDescriptor, error)

GetMethodDescriptor returns the method descriptor for a given method.

func (*Client) GetMintParams added in v0.3.0

func (c *Client) GetMintParams() (*MintParamsResponse, error)

GetMintParams fetches mint module parameters.

func (*Client) GetModuleAccountByName added in v0.3.0

func (c *Client) GetModuleAccountByName(name string) (*AccountResponse, error)

GetModuleAccountByName fetches a module account by name.

func (*Client) GetModuleAccounts added in v0.3.0

func (c *Client) GetModuleAccounts() (map[string]string, error)

GetModuleAccounts fetches all module accounts. Returns a map of address -> module name.

func (*Client) GetModuleVersions added in v0.3.0

func (c *Client) GetModuleVersions() (*ModuleVersionsResponse, error)

GetModuleVersions fetches module versions.

func (*Client) GetNodeInfo added in v0.3.0

func (c *Client) GetNodeInfo() (*NodeInfoResponse, error)

GetNodeInfo fetches node information including chain ID.

func (*Client) GetProposal added in v0.3.0

func (c *Client) GetProposal(proposalID uint64) (*ProposalResponse, error)

GetProposal fetches a single governance proposal by ID.

func (*Client) GetProposalDeposits added in v0.3.0

func (c *Client) GetProposalDeposits(proposalID uint64) (*DepositsResponse, error)

GetProposalDeposits fetches deposits for a proposal.

func (*Client) GetProposalVotes added in v0.3.0

func (c *Client) GetProposalVotes(proposalID uint64) (*VotesResponse, error)

GetProposalVotes fetches votes for a proposal.

func (*Client) GetProposals added in v0.3.0

func (c *Client) GetProposals(status string) (*ProposalsResponse, error)

GetProposals fetches all governance proposals. Status can be: PROPOSAL_STATUS_UNSPECIFIED, PROPOSAL_STATUS_DEPOSIT_PERIOD, PROPOSAL_STATUS_VOTING_PERIOD, PROPOSAL_STATUS_PASSED, PROPOSAL_STATUS_REJECTED, PROPOSAL_STATUS_FAILED, or empty for all.

func (*Client) GetRedelegations added in v0.3.0

func (c *Client) GetRedelegations(delegatorAddr string) (*RedelegationsResponse, error)

GetRedelegations fetches redelegations for a delegator.

func (*Client) GetSigningInfo added in v0.3.0

func (c *Client) GetSigningInfo(consAddr string) (*SigningInfoResponse, error)

GetSigningInfo fetches signing info for a validator consensus address.

func (*Client) GetSigningInfos added in v0.3.0

func (c *Client) GetSigningInfos() (*SigningInfosResponse, error)

GetSigningInfos fetches signing info for all validators.

func (*Client) GetSlashingParams added in v0.3.0

func (c *Client) GetSlashingParams() (*SlashingParamsResponse, error)

GetSlashingParams fetches slashing module parameters.

func (*Client) GetSpendableBalances added in v0.3.0

func (c *Client) GetSpendableBalances(address string) (*SpendableBalancesResponse, error)

GetSpendableBalances fetches spendable balances for an address.

func (*Client) GetStakingParams added in v0.3.0

func (c *Client) GetStakingParams() (*StakingParamsResponse, error)

GetStakingParams fetches staking parameters.

func (*Client) GetStakingPool added in v0.3.0

func (c *Client) GetStakingPool() (*StakingPoolResponse, error)

GetStakingPool fetches the current staking pool info (bonded/not bonded tokens).

func (*Client) GetSupplyOf added in v0.3.0

func (c *Client) GetSupplyOf(denom string) (*SupplyOfResponse, error)

GetSupplyOf fetches the supply of a specific denomination.

func (*Client) GetSyncing added in v0.3.0

func (c *Client) GetSyncing() (bool, error)

GetSyncing returns whether the node is currently syncing.

func (*Client) GetTallyResult added in v0.3.0

func (c *Client) GetTallyResult(proposalID uint64) (*TallyResultResponse, error)

GetTallyResult fetches the tally result for a proposal.

func (*Client) GetTotalSupply added in v0.3.0

func (c *Client) GetTotalSupply() (*TotalSupplyResponse, error)

GetTotalSupply fetches the total supply of all coins.

func (*Client) GetTx added in v0.3.0

func (c *Client) GetTx(hash string) (*TxResponse, error)

GetTx fetches a transaction by hash.

func (*Client) GetTxsByHeight added in v0.3.0

func (c *Client) GetTxsByHeight(height int64) ([]byte, error)

GetTxsByHeight fetches all transactions for a given block height, following pagination until the node reports no further pages. Returns raw JSON response for flexibility in parsing.

func (*Client) GetTxsByHeightParsed added in v0.3.0

func (c *Client) GetTxsByHeightParsed(height int64) (*TxsEventResponse, error)

GetTxsByHeightParsed fetches transactions and returns them in a structured format.

func (*Client) GetUnbondingDelegation added in v0.3.0

func (c *Client) GetUnbondingDelegation(delegatorAddr, validatorAddr string) (*UnbondingDelegationResponse, error)

GetUnbondingDelegation fetches a specific unbonding delegation.

func (*Client) GetValidator added in v0.3.0

func (c *Client) GetValidator(validatorAddr string) (*ValidatorResponse, error)

GetValidator fetches a single validator by operator address.

func (*Client) GetValidatorCommission added in v0.3.0

func (c *Client) GetValidatorCommission(validatorAddr string) (*ValidatorCommissionResponse, error)

GetValidatorCommission fetches accumulated commission for a validator.

func (*Client) GetValidatorDelegations added in v0.3.0

func (c *Client) GetValidatorDelegations(validatorAddr string) (*DelegationsResponse, error)

GetValidatorDelegations fetches all delegations to a validator.

func (*Client) GetValidatorOutstandingRewards added in v0.3.0

func (c *Client) GetValidatorOutstandingRewards(validatorAddr string) (*ValidatorOutstandingRewardsResponse, error)

GetValidatorOutstandingRewards fetches outstanding rewards for a validator.

func (*Client) GetValidatorSetByHeight added in v0.3.0

func (c *Client) GetValidatorSetByHeight(height int64) (*ValidatorSetResponse, error)

GetValidatorSetByHeight fetches the validator set at a specific height.

func (*Client) GetValidators added in v0.3.0

func (c *Client) GetValidators(status string) (*ValidatorsResponse, error)

GetValidators fetches validators with optional status filter. Status can be: BOND_STATUS_BONDED, BOND_STATUS_UNBONDED, BOND_STATUS_UNBONDING, or empty for all.

func (*Client) Invoke

func (c *Client) Invoke(method string, request []byte) ([]byte, error)

Invoke calls the specified gRPC method with the given JSON request payload. The method should be specified as "package.Service.Method" (e.g., "cosmos.bank.v1beta1.Query.Balance"). Returns the response as JSON bytes.

func (*Client) InvokeContext added in v1.0.0

func (c *Client) InvokeContext(ctx context.Context, method string, request []byte) ([]byte, error)

InvokeContext calls the specified gRPC method with a caller-controlled context.

func (*Client) InvokeJSON

func (c *Client) InvokeJSON(method string, request interface{}, result interface{}) error

InvokeJSON is a convenience method that accepts and returns Go values instead of JSON bytes. The request will be marshaled to JSON and the response will be unmarshaled into the result.

func (*Client) InvokeRaw

func (c *Client) InvokeRaw(method string, request []byte) (*dynamicpb.Message, error)

InvokeRaw calls the method and returns the dynamic protobuf message directly. This is useful when you need to access specific fields without JSON marshaling.

func (*Client) InvokeRawContext added in v1.0.0

func (c *Client) InvokeRawContext(ctx context.Context, method string, request []byte) (*dynamicpb.Message, error)

InvokeRawContext calls the method and returns the dynamic protobuf message directly using a caller-controlled context.

func (*Client) InvokeWithRetry

func (c *Client) InvokeWithRetry(method string, request []byte, maxRetries uint) ([]byte, error)

InvokeWithRetry calls the specified gRPC method with custom retry count.

func (*Client) InvokeWithRetryContext added in v1.0.0

func (c *Client) InvokeWithRetryContext(ctx context.Context, method string, request []byte, maxRetries uint) ([]byte, error)

InvokeWithRetryContext calls the specified gRPC method with custom retry count and a caller-controlled context.

func (*Client) InvokeWithTimeout added in v1.1.0

func (c *Client) InvokeWithTimeout(method string, request []byte, timeout time.Duration) ([]byte, error)

InvokeWithTimeout calls the method with a per-invocation timeout that also bounds retries and backoff. A timeout <= 0 falls back to the default.

func (*Client) ListMethods

func (c *Client) ListMethods(serviceName string) ([]string, error)

ListMethods returns all methods for a given service.

func (*Client) ListServices

func (c *Client) ListServices() []string

ListServices returns all services available on the connected server.

func (*Client) Method added in v1.0.0

func (c *Client) Method(name string) (*Method, error)

Method returns a reflected method handle.

func (*Client) NewMessage added in v1.0.0

func (c *Client) NewMessage(fullName string) (*Request, error)

NewMessage creates an empty reflected message by full type name.

func (*Client) ProtoDir added in v1.1.0

func (c *Client) ProtoDir() *ProtoDir

ProtoDir returns the configured local proto directory, or nil if none.

func (*Client) Resolver

func (c *Client) Resolver() *Resolver

Resolver returns the underlying type resolver, useful for custom protojson operations.

func (*Client) ServerStream added in v1.5.0

func (c *Client) ServerStream(ctx context.Context, method string, request []byte) (*ServerStream, error)

ServerStream opens a server-streaming call with a protobuf-JSON request.

func (*Client) SkippedFiles added in v1.1.0

func (c *Client) SkippedFiles() []string

SkippedFiles returns reflected proto files that could not be registered during Dial. These are typically files with unresolvable dependencies or custom options; methods that depend on them will not be callable.

func (*Client) SupportsBlockResults added in v1.0.0

func (c *Client) SupportsBlockResults() bool

SupportsBlockResults reports whether the connected server advertises the block-results RPCs through reflection.

func (*Client) SupportsMethod added in v1.0.0

func (c *Client) SupportsMethod(method string) bool

SupportsMethod reports whether the connected server exposes a method.

func (*Client) SupportsService added in v1.0.0

func (c *Client) SupportsService(service string) bool

SupportsService reports whether the connected server exposes a service.

type ClientStream added in v1.5.0

type ClientStream struct {
	// contains filtered or unexported fields
}

ClientStream is a handle for a client-streaming RPC. Send messages, then call CloseAndRecv for the single response.

func (*ClientStream) Close added in v1.5.0

func (s *ClientStream) Close()

Close cancels the stream and releases its resources.

func (*ClientStream) CloseAndRecv added in v1.5.0

func (s *ClientStream) CloseAndRecv() (*dynamicpb.Message, error)

CloseAndRecv half-closes the send direction and receives the response.

func (*ClientStream) Context added in v1.5.0

func (s *ClientStream) Context() context.Context

Context returns the stream context.

func (*ClientStream) Send added in v1.5.0

func (s *ClientStream) Send(msg *dynamicpb.Message) error

Send sends the next request message.

type Coin added in v0.3.0

type Coin struct {
	Denom  string `json:"denom"`
	Amount string `json:"amount"`
}

Coin represents a Cosmos SDK coin.

type CommunityPoolResponse added in v0.3.0

type CommunityPoolResponse struct {
	Pool []struct {
		Denom  string `json:"denom"`
		Amount string `json:"amount"`
	} `json:"pool"`
}

CommunityPoolResponse represents community pool response.

type CurrentPlanResponse added in v0.3.0

type CurrentPlanResponse struct {
	Plan *struct {
		Name   string `json:"name"`
		Height string `json:"height"`
		Info   string `json:"info"`
	} `json:"plan"`
}

CurrentPlanResponse represents current upgrade plan response.

type DelegationResponse added in v0.3.0

type DelegationResponse struct {
	DelegationResponse struct {
		Delegation struct {
			DelegatorAddress string `json:"delegatorAddress"`
			ValidatorAddress string `json:"validatorAddress"`
			Shares           string `json:"shares"`
		} `json:"delegation"`
		Balance Coin `json:"balance"`
	} `json:"delegationResponse"`
}

DelegationResponse represents a single delegation response.

type DelegationRewardsResponse added in v0.3.0

type DelegationRewardsResponse struct {
	Rewards []struct {
		Denom  string `json:"denom"`
		Amount string `json:"amount"`
	} `json:"rewards"`
}

DelegationRewardsResponse represents delegation rewards response.

type DelegationTotalRewardsResponse added in v0.3.0

type DelegationTotalRewardsResponse struct {
	Rewards []struct {
		ValidatorAddress string `json:"validatorAddress"`
		Reward           []struct {
			Denom  string `json:"denom"`
			Amount string `json:"amount"`
		} `json:"reward"`
	} `json:"rewards"`
	Total []struct {
		Denom  string `json:"denom"`
		Amount string `json:"amount"`
	} `json:"total"`
}

DelegationTotalRewardsResponse represents total rewards response.

type DelegationsResponse added in v0.3.0

type DelegationsResponse struct {
	DelegationResponses []struct {
		Delegation struct {
			DelegatorAddress string `json:"delegatorAddress"`
			ValidatorAddress string `json:"validatorAddress"`
			Shares           string `json:"shares"`
		} `json:"delegation"`
		Balance Coin `json:"balance"`
	} `json:"delegationResponses"`
	Pagination *PaginationResp `json:"pagination,omitempty"`
}

DelegationsResponse represents delegator delegations response.

type DenomMetadataResponse added in v0.3.0

type DenomMetadataResponse struct {
	Metadata struct {
		Description string `json:"description"`
		Base        string `json:"base"`
		Display     string `json:"display"`
		Name        string `json:"name"`
		Symbol      string `json:"symbol"`
		DenomUnits  []struct {
			Denom    string   `json:"denom"`
			Exponent uint32   `json:"exponent"`
			Aliases  []string `json:"aliases"`
		} `json:"denomUnits"`
	} `json:"metadata"`
}

DenomMetadataResponse represents denom metadata response.

type DenomOwnersResponse added in v0.3.0

type DenomOwnersResponse struct {
	DenomOwners []struct {
		Address string `json:"address"`
		Balance Coin   `json:"balance"`
	} `json:"denomOwners"`
	Pagination *PaginationResp `json:"pagination,omitempty"`
}

DenomOwnersResponse represents denom owners response.

type DenomsMetadataResponse added in v0.3.0

type DenomsMetadataResponse struct {
	Metadatas  []json.RawMessage `json:"metadatas"`
	Pagination *PaginationResp   `json:"pagination,omitempty"`
}

DenomsMetadataResponse represents all denoms metadata response.

type DepositsResponse added in v0.3.0

type DepositsResponse struct {
	Deposits   []json.RawMessage `json:"deposits"`
	Pagination *PaginationResp   `json:"pagination,omitempty"`
}

DepositsResponse represents proposal deposits response.

type DistributionParamsResponse added in v0.3.0

type DistributionParamsResponse struct {
	Params struct {
		CommunityTax        string `json:"communityTax"`
		BaseProposerReward  string `json:"baseProposerReward"`
		BonusProposerReward string `json:"bonusProposerReward"`
		WithdrawAddrEnabled bool   `json:"withdrawAddrEnabled"`
	} `json:"params"`
}

DistributionParamsResponse represents distribution params response.

type Event added in v1.0.0

type Event struct {
	Type       string           `json:"type"`
	Attributes []EventAttribute `json:"attributes,omitempty"`
}

Event represents an ABCI event from block results.

func (*Event) GetEventAttribute added in v1.0.0

func (e *Event) GetEventAttribute(key string) string

GetEventAttribute returns the value of an attribute by key, or empty string if not found.

type EventAttribute added in v1.0.0

type EventAttribute struct {
	Key   string `json:"key"`
	Value string `json:"value"`
	Index bool   `json:"index,omitempty"`
}

EventAttribute represents a key-value attribute in an ABCI event.

type EvidenceResponse added in v0.3.0

type EvidenceResponse struct {
	Evidence json.RawMessage `json:"evidence"`
}

EvidenceResponse represents evidence response.

type ExecTxResult added in v1.0.0

type ExecTxResult struct {
	Code      uint32  `json:"code"`
	Data      string  `json:"data,omitempty"`
	Log       string  `json:"log,omitempty"`
	Info      string  `json:"info,omitempty"`
	GasWanted int64   `json:"gasWanted,string,omitempty"`
	GasUsed   int64   `json:"gasUsed,string,omitempty"`
	Events    []Event `json:"events,omitempty"`
	Codespace string  `json:"codespace,omitempty"`
}

ExecTxResult represents a transaction execution result.

type FallbackRegistry added in v0.4.0

type FallbackRegistry struct {
	// contains filtered or unexported fields
}

FallbackRegistry holds pre-compiled proto descriptors for types that may not be available via server reflection (e.g., deprecated modules).

func GlobalFallback added in v0.4.0

func GlobalFallback() *FallbackRegistry

GlobalFallback returns the global fallback registry. Use this to register fallback descriptors that should be available to all clients.

func NewFallbackRegistry added in v0.4.0

func NewFallbackRegistry() *FallbackRegistry

NewFallbackRegistry creates a new empty fallback registry.

func (*FallbackRegistry) Files added in v0.4.0

func (r *FallbackRegistry) Files() *protoregistry.Files

Files returns the underlying file registry.

func (*FallbackRegistry) FindDescriptorByName added in v0.4.0

func (r *FallbackRegistry) FindDescriptorByName(name protoreflect.FullName) (protoreflect.Descriptor, error)

FindDescriptorByName looks up a descriptor by its full name. First checks the in-memory registry, then the local proto directory if configured.

func (*FallbackRegistry) FindDescriptorByNameContext added in v1.0.0

func (r *FallbackRegistry) FindDescriptorByNameContext(ctx context.Context, name protoreflect.FullName) (protoreflect.Descriptor, error)

FindDescriptorByNameContext looks up a descriptor by full name using the supplied context for lazy proto directory loading.

func (*FallbackRegistry) MergeInto added in v0.4.0

func (r *FallbackRegistry) MergeInto(target *protoregistry.Files) error

MergeInto merges this fallback registry into a target protoregistry.Files. This is used during resolver initialization.

func (*FallbackRegistry) ProtoDir added in v0.7.0

func (r *FallbackRegistry) ProtoDir() *ProtoDir

ProtoDir returns the configured proto directory, or nil if none.

func (*FallbackRegistry) RegisterFileDescriptor added in v0.4.0

func (r *FallbackRegistry) RegisterFileDescriptor(fdProto *descriptorpb.FileDescriptorProto) error

RegisterFileDescriptor registers a single file descriptor proto. Dependencies must be registered first.

func (*FallbackRegistry) RegisterFileDescriptorSet added in v0.4.0

func (r *FallbackRegistry) RegisterFileDescriptorSet(fds *descriptorpb.FileDescriptorSet) error

RegisterFileDescriptorSet registers multiple file descriptor protos. Files are registered in order, so dependencies should come first.

func (*FallbackRegistry) SetProtoDir added in v0.7.0

func (r *FallbackRegistry) SetProtoDir(dir *ProtoDir)

SetProtoDir configures a local proto directory for fallback resolution. The directory will be loaded lazily when first needed.

type GovParamsResponse added in v0.3.0

type GovParamsResponse struct {
	VotingParams  json.RawMessage `json:"votingParams,omitempty"`
	DepositParams json.RawMessage `json:"depositParams,omitempty"`
	TallyParams   json.RawMessage `json:"tallyParams,omitempty"`
	Params        json.RawMessage `json:"params,omitempty"`
}

GovParamsResponse represents gov params response.

type GrantsResponse added in v0.3.0

type GrantsResponse struct {
	Grants []struct {
		Authorization json.RawMessage `json:"authorization"`
		Expiration    string          `json:"expiration,omitempty"`
	} `json:"grants"`
	Pagination *PaginationResp `json:"pagination,omitempty"`
}

GrantsResponse represents authz grants response.

type IBCChannelResponse added in v0.3.0

type IBCChannelResponse struct {
	Channel struct {
		State        string `json:"state"`
		Ordering     string `json:"ordering"`
		Counterparty struct {
			PortID    string `json:"portId"`
			ChannelID string `json:"channelId"`
		} `json:"counterparty"`
		ConnectionHops []string `json:"connectionHops"`
		Version        string   `json:"version"`
	} `json:"channel"`
	ProofHeight struct {
		RevisionNumber string `json:"revisionNumber"`
		RevisionHeight string `json:"revisionHeight"`
	} `json:"proofHeight"`
}

IBCChannelResponse represents a single IBC channel response.

type IBCChannelsResponse added in v0.3.0

type IBCChannelsResponse struct {
	Channels []struct {
		State        string `json:"state"`
		Ordering     string `json:"ordering"`
		Counterparty struct {
			PortID    string `json:"portId"`
			ChannelID string `json:"channelId"`
		} `json:"counterparty"`
		ConnectionHops []string `json:"connectionHops"`
		Version        string   `json:"version"`
		PortID         string   `json:"portId"`
		ChannelID      string   `json:"channelId"`
	} `json:"channels"`
	Pagination *PaginationResp `json:"pagination,omitempty"`
	Height     struct {
		RevisionNumber string `json:"revisionNumber"`
		RevisionHeight string `json:"revisionHeight"`
	} `json:"height"`
}

IBCChannelsResponse represents IBC channels response.

type IBCClientStateResponse added in v0.3.0

type IBCClientStateResponse struct {
	ClientState json.RawMessage `json:"clientState"`
	ProofHeight struct {
		RevisionNumber string `json:"revisionNumber"`
		RevisionHeight string `json:"revisionHeight"`
	} `json:"proofHeight"`
}

IBCClientStateResponse represents a single IBC client state response.

type IBCClientStatesResponse added in v0.3.0

type IBCClientStatesResponse struct {
	ClientStates []struct {
		ClientID    string          `json:"clientId"`
		ClientState json.RawMessage `json:"clientState"`
	} `json:"clientStates"`
	Pagination *PaginationResp `json:"pagination,omitempty"`
}

IBCClientStatesResponse represents IBC client states response.

type IBCConnectionResponse added in v0.3.0

type IBCConnectionResponse struct {
	Connection struct {
		ClientID     string          `json:"clientId"`
		Versions     json.RawMessage `json:"versions"`
		State        string          `json:"state"`
		Counterparty struct {
			ClientID     string `json:"clientId"`
			ConnectionID string `json:"connectionId"`
			Prefix       struct {
				KeyPrefix string `json:"keyPrefix"`
			} `json:"prefix"`
		} `json:"counterparty"`
		DelayPeriod string `json:"delayPeriod"`
	} `json:"connection"`
	ProofHeight struct {
		RevisionNumber string `json:"revisionNumber"`
		RevisionHeight string `json:"revisionHeight"`
	} `json:"proofHeight"`
}

IBCConnectionResponse represents a single IBC connection response.

type IBCConnectionsResponse added in v0.3.0

type IBCConnectionsResponse struct {
	Connections []struct {
		ID           string          `json:"id"`
		ClientID     string          `json:"clientId"`
		Versions     json.RawMessage `json:"versions"`
		State        string          `json:"state"`
		Counterparty struct {
			ClientID     string `json:"clientId"`
			ConnectionID string `json:"connectionId"`
			Prefix       struct {
				KeyPrefix string `json:"keyPrefix"`
			} `json:"prefix"`
		} `json:"counterparty"`
		DelayPeriod string `json:"delayPeriod"`
	} `json:"connections"`
	Pagination *PaginationResp `json:"pagination,omitempty"`
	Height     struct {
		RevisionNumber string `json:"revisionNumber"`
		RevisionHeight string `json:"revisionHeight"`
	} `json:"height"`
}

IBCConnectionsResponse represents IBC connections response.

type IBCDenomHashResponse added in v0.3.0

type IBCDenomHashResponse struct {
	Hash string `json:"hash"`
}

IBCDenomHashResponse represents IBC denom hash response.

type IBCDenomTraceResponse added in v0.3.0

type IBCDenomTraceResponse struct {
	DenomTrace struct {
		Path      string `json:"path"`
		BaseDenom string `json:"baseDenom"`
	} `json:"denomTrace"`
}

IBCDenomTraceResponse represents IBC denom trace response.

type IBCDenomTracesResponse added in v0.3.0

type IBCDenomTracesResponse struct {
	DenomTraces []struct {
		Path      string `json:"path"`
		BaseDenom string `json:"baseDenom"`
	} `json:"denomTraces"`
	Pagination *PaginationResp `json:"pagination,omitempty"`
}

IBCDenomTracesResponse represents IBC denom traces response.

type IBCEscrowAddressResponse added in v0.3.0

type IBCEscrowAddressResponse struct {
	EscrowAddress string `json:"escrowAddress"`
}

IBCEscrowAddressResponse represents IBC escrow address response.

type IBCTotalEscrowResponse added in v0.3.0

type IBCTotalEscrowResponse struct {
	Amount Coin `json:"amount"`
}

IBCTotalEscrowResponse represents total escrow for denom response.

type IBCTransferParamsResponse added in v0.3.0

type IBCTransferParamsResponse struct {
	Params struct {
		SendEnabled    bool `json:"sendEnabled"`
		ReceiveEnabled bool `json:"receiveEnabled"`
	} `json:"params"`
}

IBCTransferParamsResponse represents IBC transfer params response.

type InflationResponse added in v0.3.0

type InflationResponse struct {
	Inflation string `json:"inflation"`
}

InflationResponse represents inflation response.

type MessageInfo added in v1.0.0

type MessageInfo struct {
	FullName string
	File     string
}

MessageInfo describes a reflected protobuf message.

type Method added in v1.0.0

type Method struct {
	// contains filtered or unexported fields
}

Method is a reusable reflected gRPC method handle.

func (*Method) BidiStream added in v1.5.0

func (m *Method) BidiStream(ctx context.Context) (*BidiStream, error)

BidiStream opens a bidirectional-streaming call.

func (*Method) Call added in v1.0.0

func (m *Method) Call(ctx context.Context, req *Request) (*Response, error)

Call invokes this reflected method with a descriptor-backed request.

func (*Method) CallMap added in v1.0.0

func (m *Method) CallMap(ctx context.Context, values map[string]any) (*Response, error)

CallMap creates a request from a map and invokes this method.

func (*Method) ClientStream added in v1.5.0

func (m *Method) ClientStream(ctx context.Context) (*ClientStream, error)

ClientStream opens a client-streaming call.

func (*Method) EachPage added in v1.0.0

func (m *Method) EachPage(ctx context.Context, values map[string]any, fn func(*Response) error) error

EachPage invokes a reflected method once per page for standard Cosmos SDK request/response messages that use pagination.key and pagination.next_key. If the method has no pagination fields, it invokes the method once.

func (*Method) Info added in v1.0.0

func (m *Method) Info() MethodInfo

Info returns reflected method metadata.

func (*Method) NewRequest added in v1.0.0

func (m *Method) NewRequest() *Request

NewRequest creates an empty descriptor-backed request for this method.

func (*Method) RequestFromMap added in v1.0.0

func (m *Method) RequestFromMap(values map[string]any) (*Request, error)

RequestFromMap creates a request and populates it from field names or JSON names.

func (*Method) ServerStream added in v1.5.0

func (m *Method) ServerStream(ctx context.Context, req *Request) (*ServerStream, error)

ServerStream opens a server-streaming call and sends the single request.

type MethodInfo added in v1.0.0

type MethodInfo struct {
	FullName        string
	Service         string
	Name            string
	Input           string
	Output          string
	ClientStreaming bool
	ServerStreaming bool
}

MethodInfo describes a reflected gRPC method.

type MintParamsResponse added in v0.3.0

type MintParamsResponse struct {
	Params struct {
		MintDenom           string `json:"mintDenom"`
		InflationRateChange string `json:"inflationRateChange"`
		InflationMax        string `json:"inflationMax"`
		InflationMin        string `json:"inflationMin"`
		GoalBonded          string `json:"goalBonded"`
		BlocksPerYear       string `json:"blocksPerYear"`
	} `json:"params"`
}

MintParamsResponse represents mint params response.

type ModuleAccountsResponse added in v0.3.0

type ModuleAccountsResponse struct {
	Accounts []struct {
		Type        string `json:"@type"`
		BaseAccount struct {
			Address string `json:"address"`
		} `json:"baseAccount"`
		Name        string   `json:"name"`
		Permissions []string `json:"permissions"`
	} `json:"accounts"`
}

ModuleAccountsResponse represents the module accounts query response.

type ModuleVersionsResponse added in v0.3.0

type ModuleVersionsResponse struct {
	ModuleVersions []struct {
		Name    string `json:"name"`
		Version string `json:"version"`
	} `json:"moduleVersions"`
}

ModuleVersionsResponse represents module versions response.

type NodeInfoResponse added in v0.3.0

type NodeInfoResponse struct {
	DefaultNodeInfo struct {
		Network string `json:"network"`
		Moniker string `json:"moniker"`
	} `json:"defaultNodeInfo"`
	ApplicationVersion struct {
		Name             string `json:"name"`
		AppName          string `json:"appName"`
		Version          string `json:"version"`
		GitCommit        string `json:"gitCommit"`
		BuildTags        string `json:"buildTags"`
		GoVersion        string `json:"goVersion"`
		CosmosSDKVersion string `json:"cosmosSdkVersion"`
		BuildDeps        []struct {
			Path    string `json:"path"`
			Version string `json:"version"`
			Sum     string `json:"sum"`
		} `json:"buildDeps"`
	} `json:"applicationVersion"`
}

NodeInfoResponse represents the response from GetNodeInfo.

type Option

type Option func(*options)

Option configures the Client.

func WithDefaultTimeout added in v1.1.0

func WithDefaultTimeout(timeout time.Duration) Option

WithDefaultTimeout sets a timeout applied to every invocation, covering the call and any retries/backoff. A zero value disables it.

func WithDialOptions

func WithDialOptions(opts ...grpc.DialOption) Option

WithDialOptions appends additional gRPC dial options.

func WithDialTimeout added in v0.2.0

func WithDialTimeout(timeout time.Duration) Option

WithDialTimeout sets a timeout for the initial connection and descriptor fetching. If not set, the timeout is controlled by the context passed to Dial().

func WithDisableALPNEnforcement added in v0.9.0

func WithDisableALPNEnforcement() Option

WithDisableALPNEnforcement disables ALPN (Application-Layer Protocol Negotiation) enforcement for TLS connections. This is needed for some gRPC servers that don't properly support ALPN negotiation.

Starting with grpc-go v1.67, ALPN is enforced by default. Some servers, particularly older or misconfigured ones, fail the TLS handshake because they don't include the required ALPN property in their response.

Use this option if you encounter errors like:

"transport: authentication handshake failed: credentials: cannot check peer:
missing selected ALPN property"

IMPORTANT: Due to grpc-go's initialization order, this option may not work if grpc-go has already cached the environment variable. For reliable ALPN bypass, use one of these approaches instead:

1. Import the alpnfix package before any grpc imports:

import (
    _ "github.com/Cordtus/libyaci/alpnfix" // Must be first!
    "github.com/Cordtus/libyaci"
)

2. Set the environment variable before running:

GRPC_ENFORCE_ALPN_ENABLED=false ./your-program

This option is kept for cases where the above approaches are impractical.

func WithFallbackRegistry added in v0.4.0

func WithFallbackRegistry(fb *FallbackRegistry) Option

WithFallbackRegistry sets a custom fallback registry for resolving types that are not available via server reflection (e.g., deprecated modules).

func WithGlobalFallback added in v0.4.0

func WithGlobalFallback() Option

WithGlobalFallback uses the global fallback registry (shared across clients). This is useful when multiple clients need to share the same fallback descriptors.

func WithInsecure

func WithInsecure() Option

WithInsecure disables TLS for the connection.

func WithMaxRecvMsgSize

func WithMaxRecvMsgSize(size int) Option

WithMaxRecvMsgSize sets the maximum message size the client can receive.

func WithMaxRetries

func WithMaxRetries(n uint) Option

WithMaxRetries sets the maximum number of retries for failed calls.

func WithMinSDKVersion added in v1.0.0

func WithMinSDKVersion(version string) Option

WithMinSDKVersion records the minimum Cosmos SDK version expected by the caller. This is diagnostic metadata; reflection still decides what methods can be called.

func WithProtoDir added in v0.7.0

func WithProtoDir(path string) Option

WithProtoDir configures a directory containing .proto files to use as fallback when server reflection fails to resolve a type. Proto files are compiled and registered, providing definitions for deprecated types.

The directory should contain .proto files with proper package declarations. Imports are resolved relative to the directory root, and standard protobuf imports (google/protobuf/*) are automatically available.

Proto files are loaded lazily on first type resolution failure.

Example:

client, err := libyaci.Dial(ctx, addr,
    libyaci.WithProtoDir("/path/to/protos"),
)

When a type like "tendermint.liquidity.v1beta1.MsgSwapWithinBatch" cannot be resolved via server reflection, the client will look for it in the local proto files.

Directory structure should mirror the proto package path:

protos/
  tendermint/liquidity/v1beta1/tx.proto
  cosmos/base/v1beta1/coin.proto

func WithSDKVersion added in v1.0.0

func WithSDKVersion(version string) Option

WithSDKVersion records the target chain's Cosmos SDK version for diagnostics. Reflected service and method descriptors remain the source of truth for method availability.

func WithTLSConfig added in v1.2.0

func WithTLSConfig(cfg *tls.Config) Option

WithTLSConfig supplies a custom TLS configuration for the connection. Use it for custom CA roots, client certificates, or to skip verification for self-signed endpoints:

libyaci.WithTLSConfig(&tls.Config{InsecureSkipVerify: true})

It is ignored when WithInsecure is set. Do not also pass grpc.WithTransportCredentials via WithDialOptions.

type PaginationResp added in v0.3.0

type PaginationResp struct {
	NextKey string `json:"nextKey,omitempty"`
	Total   string `json:"total,omitempty"`
}

PaginationResp represents pagination info in responses.

type ProposalResponse added in v0.3.0

type ProposalResponse struct {
	Proposal json.RawMessage `json:"proposal"`
}

ProposalResponse represents a single proposal response.

type ProposalsResponse added in v0.3.0

type ProposalsResponse struct {
	Proposals  []json.RawMessage `json:"proposals"`
	Pagination *PaginationResp   `json:"pagination,omitempty"`
}

ProposalsResponse represents gov proposals response.

type ProtoDir added in v0.7.0

type ProtoDir struct {
	// contains filtered or unexported fields
}

ProtoDir represents a directory containing .proto files that can be loaded as fallback types when server reflection fails to resolve deprecated types.

func NewProtoDir added in v0.7.0

func NewProtoDir(path string) *ProtoDir

NewProtoDir creates a ProtoDir for the given directory path. The directory is not loaded until Load() is called or a lookup triggers lazy loading.

func (*ProtoDir) FindDescriptorByName added in v0.7.0

func (p *ProtoDir) FindDescriptorByName(ctx context.Context, name protoreflect.FullName) (protoreflect.Descriptor, error)

FindDescriptorByName looks up a descriptor by full name. Triggers lazy loading if not already loaded.

func (*ProtoDir) IsLoaded added in v0.7.0

func (p *ProtoDir) IsLoaded() bool

IsLoaded returns whether the proto directory has been loaded.

func (*ProtoDir) Load added in v0.7.0

func (p *ProtoDir) Load(ctx context.Context) error

Load compiles all .proto files in the directory and registers them. This method is safe to call multiple times (subsequent calls are no-ops). Uses protocompile to parse proto files with automatic import resolution.

func (*ProtoDir) Path added in v0.7.0

func (p *ProtoDir) Path() string

Path returns the directory path.

func (*ProtoDir) Registry added in v0.7.0

func (p *ProtoDir) Registry() *protoregistry.Files

Registry returns the underlying file registry. Returns nil if not yet loaded.

type RedelegationsResponse added in v0.3.0

type RedelegationsResponse struct {
	RedelegationResponses []struct {
		Redelegation struct {
			DelegatorAddress    string `json:"delegatorAddress"`
			ValidatorSrcAddress string `json:"validatorSrcAddress"`
			ValidatorDstAddress string `json:"validatorDstAddress"`
			Entries             []struct {
				CreationHeight string `json:"creationHeight"`
				CompletionTime string `json:"completionTime"`
				InitialBalance string `json:"initialBalance"`
				SharesDst      string `json:"sharesDst"`
			} `json:"entries"`
		} `json:"redelegation"`
		Entries []struct {
			RedelegationEntry struct {
				CreationHeight string `json:"creationHeight"`
				CompletionTime string `json:"completionTime"`
				InitialBalance string `json:"initialBalance"`
				SharesDst      string `json:"sharesDst"`
			} `json:"redelegationEntry"`
			Balance string `json:"balance"`
		} `json:"entries"`
	} `json:"redelegationResponses"`
	Pagination *PaginationResp `json:"pagination,omitempty"`
}

RedelegationsResponse represents redelegations response.

type Request added in v1.0.0

type Request struct {
	// contains filtered or unexported fields
}

Request is a descriptor-backed dynamic protobuf request.

func (*Request) JSON added in v1.0.0

func (r *Request) JSON() ([]byte, error)

JSON marshals the request to protobuf JSON.

func (*Request) LoadJSON added in v1.0.0

func (r *Request) LoadJSON(data []byte) error

LoadJSON unmarshals protobuf JSON into the request.

func (*Request) Message added in v1.0.0

func (r *Request) Message() *dynamicpb.Message

Message returns the underlying dynamic protobuf message.

func (*Request) Set added in v1.0.0

func (r *Request) Set(field string, value any) error

Set assigns a top-level field by proto name or JSON name.

func (*Request) SetMap added in v1.0.0

func (r *Request) SetMap(values map[string]any) error

SetMap assigns multiple fields by proto name or JSON name.

func (*Request) SetPath added in v1.0.0

func (r *Request) SetPath(path string, value any) error

SetPath assigns a nested field by dot-separated proto or JSON names.

type Resolver

type Resolver struct {
	// contains filtered or unexported fields
}

Resolver provides thread-safe resolution of protobuf types using server reflection. It implements protoregistry.MessageTypeResolver and protoregistry.ExtensionTypeResolver.

func (*Resolver) CreatePatchedResolver added in v0.6.1

func (r *Resolver) CreatePatchedResolver(messageType, fieldName string) (*Resolver, error)

CreatePatchedResolver creates a new temporary Resolver with a specific field patched from TYPE_STRING to TYPE_BYTES. This is used to recover from UTF-8 validation errors when string fields contain binary data. The original resolver is NOT modified - the returned resolver is for one-time use.

func (*Resolver) Files

func (r *Resolver) Files() *protoregistry.Files

Files returns the underlying file registry.

func (*Resolver) FindExtensionByName

func (r *Resolver) FindExtensionByName(name protoreflect.FullName) (protoreflect.ExtensionType, error)

FindExtensionByName resolves a protobuf extension field by its full name. It searches the reflected registry first, then the fallback registry.

func (*Resolver) FindExtensionByNumber

func (r *Resolver) FindExtensionByNumber(containingType protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error)

FindExtensionByNumber resolves an extension field by its containing message and field number. It searches the reflected registry first, then the fallback registry.

func (*Resolver) FindMessageByName

func (r *Resolver) FindMessageByName(name protoreflect.FullName) (protoreflect.MessageType, error)

FindMessageByName finds a message type by its full name. This method is called automatically when unmarshaling protobuf Any types. It first checks the primary registry, then attempts server reflection, and finally falls back to the fallback registry for deprecated types.

func (*Resolver) FindMessageByURL

func (r *Resolver) FindMessageByURL(url string) (protoreflect.MessageType, error)

FindMessageByURL finds a message type by its type URL (used in protobuf Any types).

func (*Resolver) FindMethodDescriptor

func (r *Resolver) FindMethodDescriptor(serviceName, methodName string) (protoreflect.MethodDescriptor, error)

FindMethodDescriptor finds a method descriptor by service and method name.

func (*Resolver) ProtoDir added in v1.1.0

func (r *Resolver) ProtoDir() *ProtoDir

ProtoDir returns the configured local proto directory, or nil if none.

func (*Resolver) ResetStats added in v0.5.0

func (r *Resolver) ResetStats()

ResetStats resets all cache statistics to zero.

func (*Resolver) Stats added in v0.5.0

func (r *Resolver) Stats() ResolverStats

Stats returns cache hit/miss statistics for the resolver. This is useful for diagnosing performance issues with type resolution.

type ResolverStats added in v0.5.0

type ResolverStats struct {
	CacheHits      uint64 // Types found in cache (no gRPC call)
	CacheMisses    uint64 // Types that required gRPC fetch
	FallbackHits   uint64 // Types found in fallback registry
	FallbackMisses uint64 // Types not found anywhere
}

ResolverStats contains cache hit/miss statistics for the resolver.

type Response added in v1.0.0

type Response struct {
	// contains filtered or unexported fields
}

Response is a descriptor-backed dynamic protobuf response.

func (*Response) Field added in v1.0.0

func (r *Response) Field(path string) (protoreflect.Value, error)

Field returns a top-level or dot-separated nested field value.

func (*Response) JSON added in v1.0.0

func (r *Response) JSON() ([]byte, error)

JSON marshals the response to protobuf JSON.

func (*Response) Map added in v1.0.0

func (r *Response) Map() (map[string]any, error)

Map marshals the response to protobuf JSON and decodes it into a map.

func (*Response) Message added in v1.0.0

func (r *Response) Message() *dynamicpb.Message

Message returns the underlying dynamic protobuf message.

type ServerStream added in v1.5.0

type ServerStream struct {
	// contains filtered or unexported fields
}

ServerStream is a handle for a server-streaming RPC. Call Recv until it returns io.EOF, then Close.

func (*ServerStream) Close added in v1.5.0

func (s *ServerStream) Close()

Close cancels the stream and releases its resources.

func (*ServerStream) CloseSend added in v1.5.0

func (s *ServerStream) CloseSend() error

CloseSend half-closes the send direction.

func (*ServerStream) Context added in v1.5.0

func (s *ServerStream) Context() context.Context

Context returns the stream context.

func (*ServerStream) Recv added in v1.5.0

func (s *ServerStream) Recv() (*dynamicpb.Message, error)

Recv receives the next response message.

type ServiceInfo added in v1.0.0

type ServiceInfo struct {
	Name    string
	Methods []MethodInfo
}

ServiceInfo describes a reflected gRPC service.

type SigningInfoResponse added in v0.3.0

type SigningInfoResponse struct {
	ValSigningInfo struct {
		Address             string `json:"address"`
		StartHeight         string `json:"startHeight"`
		IndexOffset         string `json:"indexOffset"`
		JailedUntil         string `json:"jailedUntil"`
		Tombstoned          bool   `json:"tombstoned"`
		MissedBlocksCounter string `json:"missedBlocksCounter"`
	} `json:"valSigningInfo"`
}

SigningInfoResponse represents signing info response.

type SigningInfosResponse added in v0.3.0

type SigningInfosResponse struct {
	Info       []json.RawMessage `json:"info"`
	Pagination *PaginationResp   `json:"pagination,omitempty"`
}

SigningInfosResponse represents all signing infos response.

type SlashingParamsResponse added in v0.3.0

type SlashingParamsResponse struct {
	Params struct {
		SignedBlocksWindow      string `json:"signedBlocksWindow"`
		MinSignedPerWindow      string `json:"minSignedPerWindow"`
		DowntimeJailDuration    string `json:"downtimeJailDuration"`
		SlashFractionDoubleSign string `json:"slashFractionDoubleSign"`
		SlashFractionDowntime   string `json:"slashFractionDowntime"`
	} `json:"params"`
}

SlashingParamsResponse represents slashing params response.

type SpendableBalancesResponse added in v0.3.0

type SpendableBalancesResponse struct {
	Balances   []Coin          `json:"balances"`
	Pagination *PaginationResp `json:"pagination,omitempty"`
}

SpendableBalancesResponse represents spendable balances response.

type StakingParamsResponse added in v0.3.0

type StakingParamsResponse struct {
	Params struct {
		BondDenom         string `json:"bondDenom"`
		UnbondingTime     string `json:"unbondingTime"`
		MaxValidators     uint32 `json:"maxValidators"`
		MaxEntries        uint32 `json:"maxEntries"`
		HistoricalEntries uint32 `json:"historicalEntries"`
		MinCommissionRate string `json:"minCommissionRate"`
	} `json:"params"`
}

StakingParamsResponse represents the staking params query response.

type StakingPoolResponse added in v0.3.0

type StakingPoolResponse struct {
	Pool struct {
		NotBondedTokens string `json:"notBondedTokens"`
		BondedTokens    string `json:"bondedTokens"`
	} `json:"pool"`
}

StakingPoolResponse represents staking pool response.

type SupplyOfResponse added in v0.3.0

type SupplyOfResponse struct {
	Amount Coin `json:"amount"`
}

SupplyOfResponse represents supply of a single denom response.

type SyncingResponse added in v0.3.0

type SyncingResponse struct {
	Syncing bool `json:"syncing"`
}

SyncingResponse represents the syncing status response.

type TallyResultResponse added in v0.3.0

type TallyResultResponse struct {
	Tally struct {
		YesCount        string `json:"yesCount"`
		AbstainCount    string `json:"abstainCount"`
		NoCount         string `json:"noCount"`
		NoWithVetoCount string `json:"noWithVetoCount"`
	} `json:"tally"`
}

TallyResultResponse represents tally result response.

type TotalSupplyResponse added in v0.3.0

type TotalSupplyResponse struct {
	Supply     []Coin          `json:"supply"`
	Pagination *PaginationResp `json:"pagination,omitempty"`
}

TotalSupplyResponse represents total supply response.

type TxResponse added in v0.3.0

type TxResponse struct {
	Tx         json.RawMessage `json:"tx"`
	TxResponse json.RawMessage `json:"txResponse"`
}

TxResponse represents a single transaction response.

type TxsEventResponse added in v0.3.0

type TxsEventResponse struct {
	Txs         []json.RawMessage `json:"txs"`
	TxResponses []json.RawMessage `json:"txResponses"`
	Pagination  *PaginationResp   `json:"pagination,omitempty"`
	Total       string            `json:"total,omitempty"`
}

TxsEventResponse represents the response from GetTxsEvent.

type TypeNotFoundError added in v0.7.0

type TypeNotFoundError struct {
	TypeName    string // full proto type name that was not found
	OriginalErr error  // underlying error from the resolution attempt
	Hint        string // suggestion for how to fix the issue
}

TypeNotFoundError provides detailed information when a type cannot be resolved via server reflection or fallback registries.

func (*TypeNotFoundError) Error added in v0.7.0

func (e *TypeNotFoundError) Error() string

Error implements the error interface with a helpful message.

func (*TypeNotFoundError) Unwrap added in v0.7.0

func (e *TypeNotFoundError) Unwrap() error

Unwrap returns the underlying error for use with errors.Is/errors.As.

type UnbondingDelegationResponse added in v0.3.0

type UnbondingDelegationResponse struct {
	Unbond struct {
		DelegatorAddress string `json:"delegatorAddress"`
		ValidatorAddress string `json:"validatorAddress"`
		Entries          []struct {
			CreationHeight string `json:"creationHeight"`
			CompletionTime string `json:"completionTime"`
			InitialBalance string `json:"initialBalance"`
			Balance        string `json:"balance"`
		} `json:"entries"`
	} `json:"unbond"`
}

UnbondingDelegationResponse represents unbonding delegation response.

type UnbondingDelegationsResponse added in v0.3.0

type UnbondingDelegationsResponse struct {
	UnbondingResponses []struct {
		DelegatorAddress string `json:"delegatorAddress"`
		ValidatorAddress string `json:"validatorAddress"`
		Entries          []struct {
			CreationHeight string `json:"creationHeight"`
			CompletionTime string `json:"completionTime"`
			InitialBalance string `json:"initialBalance"`
			Balance        string `json:"balance"`
		} `json:"entries"`
	} `json:"unbondingResponses"`
	Pagination *PaginationResp `json:"pagination,omitempty"`
}

UnbondingDelegationsResponse represents multiple unbonding delegations.

type UnsupportedMethodError added in v1.0.0

type UnsupportedMethodError struct {
	Method            string
	Service           string
	SDKVersion        string
	Reason            string
	Available         []string
	AvailableServices []string
}

UnsupportedMethodError describes a method that is not available on the connected server according to reflected descriptors.

func (*UnsupportedMethodError) Error added in v1.0.0

func (e *UnsupportedMethodError) Error() string

func (*UnsupportedMethodError) Unwrap added in v1.0.0

func (e *UnsupportedMethodError) Unwrap() error

type ValidatorCommissionResponse added in v0.3.0

type ValidatorCommissionResponse struct {
	Commission struct {
		Commission []struct {
			Denom  string `json:"denom"`
			Amount string `json:"amount"`
		} `json:"commission"`
	} `json:"commission"`
}

ValidatorCommissionResponse represents validator commission response.

type ValidatorOutstandingRewardsResponse added in v0.3.0

type ValidatorOutstandingRewardsResponse struct {
	Rewards struct {
		Rewards []struct {
			Denom  string `json:"denom"`
			Amount string `json:"amount"`
		} `json:"rewards"`
	} `json:"rewards"`
}

ValidatorOutstandingRewardsResponse represents outstanding rewards response.

type ValidatorResponse added in v0.3.0

type ValidatorResponse struct {
	Validator struct {
		OperatorAddress string `json:"operatorAddress"`
		ConsensusPubkey any    `json:"consensusPubkey"`
		Jailed          bool   `json:"jailed"`
		Status          string `json:"status"`
		Tokens          string `json:"tokens"`
		DelegatorShares string `json:"delegatorShares"`
		Description     struct {
			Moniker         string `json:"moniker"`
			Identity        string `json:"identity"`
			Website         string `json:"website"`
			SecurityContact string `json:"securityContact"`
			Details         string `json:"details"`
		} `json:"description"`
		UnbondingHeight string `json:"unbondingHeight"`
		UnbondingTime   string `json:"unbondingTime"`
		Commission      struct {
			CommissionRates struct {
				Rate          string `json:"rate"`
				MaxRate       string `json:"maxRate"`
				MaxChangeRate string `json:"maxChangeRate"`
			} `json:"commissionRates"`
			UpdateTime string `json:"updateTime"`
		} `json:"commission"`
		MinSelfDelegation string `json:"minSelfDelegation"`
	} `json:"validator"`
}

ValidatorResponse represents a single validator response.

type ValidatorSetResponse added in v0.3.0

type ValidatorSetResponse struct {
	BlockHeight string `json:"blockHeight"`
	Validators  []struct {
		Address          string `json:"address"`
		PubKey           any    `json:"pubKey"`
		VotingPower      string `json:"votingPower"`
		ProposerPriority string `json:"proposerPriority"`
	} `json:"validators"`
	Pagination *PaginationResp `json:"pagination,omitempty"`
}

ValidatorSetResponse represents the validator set response.

type ValidatorUpdate added in v1.0.0

type ValidatorUpdate struct {
	PubKey json.RawMessage `json:"pubKey,omitempty"`
	Power  int64           `json:"power,string"`
}

ValidatorUpdate represents a validator update from block results.

type ValidatorsResponse added in v0.3.0

type ValidatorsResponse struct {
	Validators []struct {
		OperatorAddress string `json:"operatorAddress"`
		Description     struct {
			Moniker string `json:"moniker"`
		} `json:"description"`
		Status string `json:"status"`
		Tokens string `json:"tokens"`
	} `json:"validators"`
	Pagination *PaginationResp `json:"pagination,omitempty"`
}

ValidatorsResponse represents the validators query response.

type VotesResponse added in v0.3.0

type VotesResponse struct {
	Votes      []json.RawMessage `json:"votes"`
	Pagination *PaginationResp   `json:"pagination,omitempty"`
}

VotesResponse represents proposal votes response.

type WithdrawAddressResponse added in v0.3.0

type WithdrawAddressResponse struct {
	WithdrawAddress string `json:"withdrawAddress"`
}

WithdrawAddressResponse represents withdraw address response.

Directories

Path Synopsis
Package alpnfix provides a workaround for grpc-go's ALPN enforcement.
Package alpnfix provides a workaround for grpc-go's ALPN enforcement.
examples
cli command
Example demonstrates how to use libyaci to call Cosmos SDK gRPC methods without any precompiled protobuf stubs.
Example demonstrates how to use libyaci to call Cosmos SDK gRPC methods without any precompiled protobuf stubs.
Package signing adds Cosmos transaction signing and broadcasting on top of the reflection-first libyaci client.
Package signing adds Cosmos transaction signing and broadcasting on top of the reflection-first libyaci client.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址