github.com/InjectiveLabs/sdk-go@v1.53.0/client/chain/chain.go (about) 1 package chain 2 3 import ( 4 "context" 5 "encoding/base64" 6 "encoding/hex" 7 "encoding/json" 8 "fmt" 9 "math" 10 "strconv" 11 "strings" 12 "sync" 13 "sync/atomic" 14 "time" 15 16 permissionstypes "github.com/InjectiveLabs/sdk-go/chain/permissions/types" 17 18 sdkmath "cosmossdk.io/math" 19 20 "github.com/cosmos/cosmos-sdk/client/grpc/cmtservice" 21 22 distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" 23 24 "github.com/cosmos/cosmos-sdk/types/query" 25 26 "google.golang.org/grpc/credentials/insecure" 27 28 wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" 29 exchangetypes "github.com/InjectiveLabs/sdk-go/chain/exchange/types" 30 chainstreamtypes "github.com/InjectiveLabs/sdk-go/chain/stream/types" 31 tokenfactorytypes "github.com/InjectiveLabs/sdk-go/chain/tokenfactory/types" 32 "github.com/InjectiveLabs/sdk-go/client/common" 33 log "github.com/InjectiveLabs/suplog" 34 rpchttp "github.com/cometbft/cometbft/rpc/client/http" 35 "github.com/cosmos/cosmos-sdk/client" 36 "github.com/cosmos/cosmos-sdk/client/tx" 37 codectypes "github.com/cosmos/cosmos-sdk/codec/types" 38 sdk "github.com/cosmos/cosmos-sdk/types" 39 txtypes "github.com/cosmos/cosmos-sdk/types/tx" 40 authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" 41 authztypes "github.com/cosmos/cosmos-sdk/x/authz" 42 banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" 43 "github.com/cosmos/gogoproto/proto" 44 ibctransfertypes "github.com/cosmos/ibc-go/v8/modules/apps/transfer/types" 45 ibcclienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" 46 ibcconnectiontypes "github.com/cosmos/ibc-go/v8/modules/core/03-connection/types" 47 ibcchanneltypes "github.com/cosmos/ibc-go/v8/modules/core/04-channel/types" 48 "github.com/pkg/errors" 49 "github.com/shopspring/decimal" 50 "google.golang.org/grpc" 51 52 ethcommon "github.com/ethereum/go-ethereum/common" 53 ) 54 55 type OrderbookType string 56 57 const ( 58 msgCommitBatchSizeLimit = 1024 59 msgCommitBatchTimeLimit = 500 * time.Millisecond 60 defaultBroadcastStatusPoll = 100 * time.Millisecond 61 defaultBroadcastTimeout = 40 * time.Second 62 defaultTimeoutHeight = 20 63 defaultTimeoutHeightSyncInterval = 10 * time.Second 64 SpotOrderbook = "injective.exchange.v1beta1.EventOrderbookUpdate.spot_orderbooks" 65 DerivativeOrderbook = "injective.exchange.v1beta1.EventOrderbookUpdate.derivative_orderbooks" 66 ) 67 68 var ( 69 ErrTimedOut = errors.New("tx timed out") 70 ErrQueueClosed = errors.New("queue is closed") 71 ErrEnqueueTimeout = errors.New("enqueue timeout") 72 ErrReadOnly = errors.New("client is in read-only mode") 73 ) 74 75 type ChainClient interface { 76 CanSignTransactions() bool 77 FromAddress() sdk.AccAddress 78 QueryClient() *grpc.ClientConn 79 ClientContext() client.Context 80 // return account number and sequence without increasing sequence 81 GetAccNonce() (accNum uint64, accSeq uint64) 82 83 SimulateMsg(clientCtx client.Context, msgs ...sdk.Msg) (*txtypes.SimulateResponse, error) 84 AsyncBroadcastMsg(msgs ...sdk.Msg) (*txtypes.BroadcastTxResponse, error) 85 SyncBroadcastMsg(msgs ...sdk.Msg) (*txtypes.BroadcastTxResponse, error) 86 87 // Build signed tx with given accNum and accSeq, useful for offline siging 88 // If simulate is set to false, initialGas will be used 89 BuildSignedTx(clientCtx client.Context, accNum, accSeq, initialGas uint64, msg ...sdk.Msg) ([]byte, error) 90 SyncBroadcastSignedTx(tyBytes []byte) (*txtypes.BroadcastTxResponse, error) 91 AsyncBroadcastSignedTx(txBytes []byte) (*txtypes.BroadcastTxResponse, error) 92 QueueBroadcastMsg(msgs ...sdk.Msg) error 93 94 // Bank Module 95 GetBankBalances(ctx context.Context, address string) (*banktypes.QueryAllBalancesResponse, error) 96 GetBankBalance(ctx context.Context, address string, denom string) (*banktypes.QueryBalanceResponse, error) 97 GetBankSpendableBalances(ctx context.Context, address string, pagination *query.PageRequest) (*banktypes.QuerySpendableBalancesResponse, error) 98 GetBankSpendableBalancesByDenom(ctx context.Context, address string, denom string) (*banktypes.QuerySpendableBalanceByDenomResponse, error) 99 GetBankTotalSupply(ctx context.Context, pagination *query.PageRequest) (*banktypes.QueryTotalSupplyResponse, error) 100 GetBankSupplyOf(ctx context.Context, denom string) (*banktypes.QuerySupplyOfResponse, error) 101 GetDenomMetadata(ctx context.Context, denom string) (*banktypes.QueryDenomMetadataResponse, error) 102 GetDenomsMetadata(ctx context.Context, pagination *query.PageRequest) (*banktypes.QueryDenomsMetadataResponse, error) 103 GetDenomOwners(ctx context.Context, denom string, pagination *query.PageRequest) (*banktypes.QueryDenomOwnersResponse, error) 104 GetBankSendEnabled(ctx context.Context, denoms []string, pagination *query.PageRequest) (*banktypes.QuerySendEnabledResponse, error) 105 106 GetAuthzGrants(ctx context.Context, req authztypes.QueryGrantsRequest) (*authztypes.QueryGrantsResponse, error) 107 GetAccount(ctx context.Context, address string) (*authtypes.QueryAccountResponse, error) 108 109 BuildGenericAuthz(granter string, grantee string, msgtype string, expireIn time.Time) *authztypes.MsgGrant 110 BuildExchangeAuthz(granter string, grantee string, authzType ExchangeAuthz, subaccountId string, markets []string, expireIn time.Time) *authztypes.MsgGrant 111 BuildExchangeBatchUpdateOrdersAuthz( 112 granter string, 113 grantee string, 114 subaccountId string, 115 spotMarkets []string, 116 derivativeMarkets []string, 117 expireIn time.Time, 118 ) *authztypes.MsgGrant 119 120 DefaultSubaccount(acc sdk.AccAddress) ethcommon.Hash 121 Subaccount(account sdk.AccAddress, index int) ethcommon.Hash 122 123 GetSubAccountNonce(ctx context.Context, subaccountId ethcommon.Hash) (*exchangetypes.QuerySubaccountTradeNonceResponse, error) 124 GetFeeDiscountInfo(ctx context.Context, account string) (*exchangetypes.QueryFeeDiscountAccountInfoResponse, error) 125 126 UpdateSubaccountNonceFromChain() error 127 SynchronizeSubaccountNonce(subaccountId ethcommon.Hash) error 128 ComputeOrderHashes(spotOrders []exchangetypes.SpotOrder, derivativeOrders []exchangetypes.DerivativeOrder, subaccountId ethcommon.Hash) (OrderHashes, error) 129 130 SpotOrder(defaultSubaccountID ethcommon.Hash, network common.Network, d *SpotOrderData) *exchangetypes.SpotOrder 131 CreateSpotOrder(defaultSubaccountID ethcommon.Hash, d *SpotOrderData, marketsAssistant MarketsAssistant) *exchangetypes.SpotOrder 132 DerivativeOrder(defaultSubaccountID ethcommon.Hash, network common.Network, d *DerivativeOrderData) *exchangetypes.DerivativeOrder 133 CreateDerivativeOrder(defaultSubaccountID ethcommon.Hash, d *DerivativeOrderData, marketAssistant MarketsAssistant) *exchangetypes.DerivativeOrder 134 OrderCancel(defaultSubaccountID ethcommon.Hash, d *OrderCancelData) *exchangetypes.OrderData 135 136 GetGasFee() (string, error) 137 138 StreamEventOrderFail(sender string, failEventCh chan map[string]uint) 139 StreamEventOrderFailWithWebsocket(sender string, websocket *rpchttp.HTTP, failEventCh chan map[string]uint) 140 StreamOrderbookUpdateEvents(orderbookType OrderbookType, marketIDs []string, orderbookCh chan exchangetypes.Orderbook) 141 StreamOrderbookUpdateEventsWithWebsocket(orderbookType OrderbookType, marketIDs []string, websocket *rpchttp.HTTP, orderbookCh chan exchangetypes.Orderbook) 142 143 ChainStream(ctx context.Context, req chainstreamtypes.StreamRequest) (chainstreamtypes.Stream_StreamClient, error) 144 145 // get tx from chain node 146 GetTx(ctx context.Context, txHash string) (*txtypes.GetTxResponse, error) 147 148 // wasm module 149 FetchContractInfo(ctx context.Context, address string) (*wasmtypes.QueryContractInfoResponse, error) 150 FetchContractHistory(ctx context.Context, address string, pagination *query.PageRequest) (*wasmtypes.QueryContractHistoryResponse, error) 151 FetchContractsByCode(ctx context.Context, codeId uint64, pagination *query.PageRequest) (*wasmtypes.QueryContractsByCodeResponse, error) 152 FetchAllContractsState(ctx context.Context, address string, pagination *query.PageRequest) (*wasmtypes.QueryAllContractStateResponse, error) 153 RawContractState( 154 ctx context.Context, 155 contractAddress string, 156 queryData []byte, 157 ) (*wasmtypes.QueryRawContractStateResponse, error) 158 SmartContractState( 159 ctx context.Context, 160 contractAddress string, 161 queryData []byte, 162 ) (*wasmtypes.QuerySmartContractStateResponse, error) 163 FetchCode(ctx context.Context, codeId uint64) (*wasmtypes.QueryCodeResponse, error) 164 FetchCodes(ctx context.Context, pagination *query.PageRequest) (*wasmtypes.QueryCodesResponse, error) 165 FetchPinnedCodes(ctx context.Context, pagination *query.PageRequest) (*wasmtypes.QueryPinnedCodesResponse, error) 166 FetchContractsByCreator(ctx context.Context, creator string, pagination *query.PageRequest) (*wasmtypes.QueryContractsByCreatorResponse, error) 167 168 // tokenfactory module 169 FetchDenomAuthorityMetadata(ctx context.Context, creator string, subDenom string) (*tokenfactorytypes.QueryDenomAuthorityMetadataResponse, error) 170 FetchDenomsFromCreator(ctx context.Context, creator string) (*tokenfactorytypes.QueryDenomsFromCreatorResponse, error) 171 FetchTokenfactoryModuleState(ctx context.Context) (*tokenfactorytypes.QueryModuleStateResponse, error) 172 173 // distribution module 174 FetchValidatorDistributionInfo(ctx context.Context, validatorAddress string) (*distributiontypes.QueryValidatorDistributionInfoResponse, error) 175 FetchValidatorOutstandingRewards(ctx context.Context, validatorAddress string) (*distributiontypes.QueryValidatorOutstandingRewardsResponse, error) 176 FetchValidatorCommission(ctx context.Context, validatorAddress string) (*distributiontypes.QueryValidatorCommissionResponse, error) 177 FetchValidatorSlashes(ctx context.Context, validatorAddress string, startingHeight uint64, endingHeight uint64, pagination *query.PageRequest) (*distributiontypes.QueryValidatorSlashesResponse, error) 178 FetchDelegationRewards(ctx context.Context, delegatorAddress string, validatorAddress string) (*distributiontypes.QueryDelegationRewardsResponse, error) 179 FetchDelegationTotalRewards(ctx context.Context, delegatorAddress string) (*distributiontypes.QueryDelegationTotalRewardsResponse, error) 180 FetchDelegatorValidators(ctx context.Context, delegatorAddress string) (*distributiontypes.QueryDelegatorValidatorsResponse, error) 181 FetchDelegatorWithdrawAddress(ctx context.Context, delegatorAddress string) (*distributiontypes.QueryDelegatorWithdrawAddressResponse, error) 182 FetchCommunityPool(ctx context.Context) (*distributiontypes.QueryCommunityPoolResponse, error) 183 184 // chain exchange module 185 FetchSubaccountDeposits(ctx context.Context, subaccountID string) (*exchangetypes.QuerySubaccountDepositsResponse, error) 186 FetchSubaccountDeposit(ctx context.Context, subaccountId string, denom string) (*exchangetypes.QuerySubaccountDepositResponse, error) 187 FetchExchangeBalances(ctx context.Context) (*exchangetypes.QueryExchangeBalancesResponse, error) 188 FetchAggregateVolume(ctx context.Context, account string) (*exchangetypes.QueryAggregateVolumeResponse, error) 189 FetchAggregateVolumes(ctx context.Context, accounts []string, marketIDs []string) (*exchangetypes.QueryAggregateVolumesResponse, error) 190 FetchAggregateMarketVolume(ctx context.Context, marketId string) (*exchangetypes.QueryAggregateMarketVolumeResponse, error) 191 FetchAggregateMarketVolumes(ctx context.Context, marketIDs []string) (*exchangetypes.QueryAggregateMarketVolumesResponse, error) 192 FetchDenomDecimal(ctx context.Context, denom string) (*exchangetypes.QueryDenomDecimalResponse, error) 193 FetchDenomDecimals(ctx context.Context, denoms []string) (*exchangetypes.QueryDenomDecimalsResponse, error) 194 FetchChainSpotMarkets(ctx context.Context, status string, marketIDs []string) (*exchangetypes.QuerySpotMarketsResponse, error) 195 FetchChainSpotMarket(ctx context.Context, marketId string) (*exchangetypes.QuerySpotMarketResponse, error) 196 FetchChainFullSpotMarkets(ctx context.Context, status string, marketIDs []string, withMidPriceAndTob bool) (*exchangetypes.QueryFullSpotMarketsResponse, error) 197 FetchChainFullSpotMarket(ctx context.Context, marketId string, withMidPriceAndTob bool) (*exchangetypes.QueryFullSpotMarketResponse, error) 198 FetchChainSpotOrderbook(ctx context.Context, marketId string, limit uint64, orderSide exchangetypes.OrderSide, limitCumulativeNotional sdkmath.LegacyDec, limitCumulativeQuantity sdkmath.LegacyDec) (*exchangetypes.QuerySpotOrderbookResponse, error) 199 FetchChainTraderSpotOrders(ctx context.Context, marketId string, subaccountId string) (*exchangetypes.QueryTraderSpotOrdersResponse, error) 200 FetchChainAccountAddressSpotOrders(ctx context.Context, marketId string, address string) (*exchangetypes.QueryAccountAddressSpotOrdersResponse, error) 201 FetchChainSpotOrdersByHashes(ctx context.Context, marketId string, subaccountId string, orderHashes []string) (*exchangetypes.QuerySpotOrdersByHashesResponse, error) 202 FetchChainSubaccountOrders(ctx context.Context, subaccountId string, marketId string) (*exchangetypes.QuerySubaccountOrdersResponse, error) 203 FetchChainTraderSpotTransientOrders(ctx context.Context, marketId string, subaccountId string) (*exchangetypes.QueryTraderSpotOrdersResponse, error) 204 FetchSpotMidPriceAndTOB(ctx context.Context, marketId string) (*exchangetypes.QuerySpotMidPriceAndTOBResponse, error) 205 FetchDerivativeMidPriceAndTOB(ctx context.Context, marketId string) (*exchangetypes.QueryDerivativeMidPriceAndTOBResponse, error) 206 FetchChainDerivativeOrderbook(ctx context.Context, marketId string, limit uint64, limitCumulativeNotional sdkmath.LegacyDec) (*exchangetypes.QueryDerivativeOrderbookResponse, error) 207 FetchChainTraderDerivativeOrders(ctx context.Context, marketId string, subaccountId string) (*exchangetypes.QueryTraderDerivativeOrdersResponse, error) 208 FetchChainAccountAddressDerivativeOrders(ctx context.Context, marketId string, address string) (*exchangetypes.QueryAccountAddressDerivativeOrdersResponse, error) 209 FetchChainDerivativeOrdersByHashes(ctx context.Context, marketId string, subaccountId string, orderHashes []string) (*exchangetypes.QueryDerivativeOrdersByHashesResponse, error) 210 FetchChainTraderDerivativeTransientOrders(ctx context.Context, marketId string, subaccountId string) (*exchangetypes.QueryTraderDerivativeOrdersResponse, error) 211 FetchChainDerivativeMarkets(ctx context.Context, status string, marketIDs []string, withMidPriceAndTob bool) (*exchangetypes.QueryDerivativeMarketsResponse, error) 212 FetchChainDerivativeMarket(ctx context.Context, marketId string) (*exchangetypes.QueryDerivativeMarketResponse, error) 213 FetchDerivativeMarketAddress(ctx context.Context, marketId string) (*exchangetypes.QueryDerivativeMarketAddressResponse, error) 214 FetchSubaccountTradeNonce(ctx context.Context, subaccountId string) (*exchangetypes.QuerySubaccountTradeNonceResponse, error) 215 FetchChainPositions(ctx context.Context) (*exchangetypes.QueryPositionsResponse, error) 216 FetchChainSubaccountPositions(ctx context.Context, subaccountId string) (*exchangetypes.QuerySubaccountPositionsResponse, error) 217 FetchChainSubaccountPositionInMarket(ctx context.Context, subaccountId string, marketId string) (*exchangetypes.QuerySubaccountPositionInMarketResponse, error) 218 FetchChainSubaccountEffectivePositionInMarket(ctx context.Context, subaccountId string, marketId string) (*exchangetypes.QuerySubaccountEffectivePositionInMarketResponse, error) 219 FetchChainPerpetualMarketInfo(ctx context.Context, marketId string) (*exchangetypes.QueryPerpetualMarketInfoResponse, error) 220 FetchChainExpiryFuturesMarketInfo(ctx context.Context, marketId string) (*exchangetypes.QueryExpiryFuturesMarketInfoResponse, error) 221 FetchChainPerpetualMarketFunding(ctx context.Context, marketId string) (*exchangetypes.QueryPerpetualMarketFundingResponse, error) 222 FetchSubaccountOrderMetadata(ctx context.Context, subaccountId string) (*exchangetypes.QuerySubaccountOrderMetadataResponse, error) 223 FetchTradeRewardPoints(ctx context.Context, accounts []string) (*exchangetypes.QueryTradeRewardPointsResponse, error) 224 FetchPendingTradeRewardPoints(ctx context.Context, accounts []string) (*exchangetypes.QueryTradeRewardPointsResponse, error) 225 FetchFeeDiscountAccountInfo(ctx context.Context, account string) (*exchangetypes.QueryFeeDiscountAccountInfoResponse, error) 226 FetchTradeRewardCampaign(ctx context.Context) (*exchangetypes.QueryTradeRewardCampaignResponse, error) 227 FetchFeeDiscountSchedule(ctx context.Context) (*exchangetypes.QueryFeeDiscountScheduleResponse, error) 228 FetchBalanceMismatches(ctx context.Context, dustFactor int64) (*exchangetypes.QueryBalanceMismatchesResponse, error) 229 FetchBalanceWithBalanceHolds(ctx context.Context) (*exchangetypes.QueryBalanceWithBalanceHoldsResponse, error) 230 FetchFeeDiscountTierStatistics(ctx context.Context) (*exchangetypes.QueryFeeDiscountTierStatisticsResponse, error) 231 FetchMitoVaultInfos(ctx context.Context) (*exchangetypes.MitoVaultInfosResponse, error) 232 FetchMarketIDFromVault(ctx context.Context, vaultAddress string) (*exchangetypes.QueryMarketIDFromVaultResponse, error) 233 FetchHistoricalTradeRecords(ctx context.Context, marketId string) (*exchangetypes.QueryHistoricalTradeRecordsResponse, error) 234 FetchIsOptedOutOfRewards(ctx context.Context, account string) (*exchangetypes.QueryIsOptedOutOfRewardsResponse, error) 235 FetchOptedOutOfRewardsAccounts(ctx context.Context) (*exchangetypes.QueryOptedOutOfRewardsAccountsResponse, error) 236 FetchMarketVolatility(ctx context.Context, marketId string, tradeHistoryOptions *exchangetypes.TradeHistoryOptions) (*exchangetypes.QueryMarketVolatilityResponse, error) 237 FetchChainBinaryOptionsMarkets(ctx context.Context, status string) (*exchangetypes.QueryBinaryMarketsResponse, error) 238 FetchTraderDerivativeConditionalOrders(ctx context.Context, subaccountId string, marketId string) (*exchangetypes.QueryTraderDerivativeConditionalOrdersResponse, error) 239 FetchMarketAtomicExecutionFeeMultiplier(ctx context.Context, marketId string) (*exchangetypes.QueryMarketAtomicExecutionFeeMultiplierResponse, error) 240 241 // Tendermint module 242 FetchNodeInfo(ctx context.Context) (*cmtservice.GetNodeInfoResponse, error) 243 FetchSyncing(ctx context.Context) (*cmtservice.GetSyncingResponse, error) 244 FetchLatestBlock(ctx context.Context) (*cmtservice.GetLatestBlockResponse, error) 245 FetchBlockByHeight(ctx context.Context, height int64) (*cmtservice.GetBlockByHeightResponse, error) 246 FetchLatestValidatorSet(ctx context.Context) (*cmtservice.GetLatestValidatorSetResponse, error) 247 FetchValidatorSetByHeight(ctx context.Context, height int64, pagination *query.PageRequest) (*cmtservice.GetValidatorSetByHeightResponse, error) 248 ABCIQuery(ctx context.Context, path string, data []byte, height int64, prove bool) (*cmtservice.ABCIQueryResponse, error) 249 250 // IBC Transfer module 251 FetchDenomTrace(ctx context.Context, hash string) (*ibctransfertypes.QueryDenomTraceResponse, error) 252 FetchDenomTraces(ctx context.Context, pagination *query.PageRequest) (*ibctransfertypes.QueryDenomTracesResponse, error) 253 FetchDenomHash(ctx context.Context, trace string) (*ibctransfertypes.QueryDenomHashResponse, error) 254 FetchEscrowAddress(ctx context.Context, portId string, channelId string) (*ibctransfertypes.QueryEscrowAddressResponse, error) 255 FetchTotalEscrowForDenom(ctx context.Context, denom string) (*ibctransfertypes.QueryTotalEscrowForDenomResponse, error) 256 257 // IBC Core Channel module 258 FetchIBCChannel(ctx context.Context, portId string, channelId string) (*ibcchanneltypes.QueryChannelResponse, error) 259 FetchIBCChannels(ctx context.Context, pagination *query.PageRequest) (*ibcchanneltypes.QueryChannelsResponse, error) 260 FetchIBCConnectionChannels(ctx context.Context, connection string, pagination *query.PageRequest) (*ibcchanneltypes.QueryConnectionChannelsResponse, error) 261 FetchIBCChannelClientState(ctx context.Context, portId string, channelId string) (*ibcchanneltypes.QueryChannelClientStateResponse, error) 262 FetchIBCChannelConsensusState(ctx context.Context, portId string, channelId string, revisionNumber uint64, revisionHeight uint64) (*ibcchanneltypes.QueryChannelConsensusStateResponse, error) 263 FetchIBCPacketCommitment(ctx context.Context, portId string, channelId string, sequence uint64) (*ibcchanneltypes.QueryPacketCommitmentResponse, error) 264 FetchIBCPacketCommitments(ctx context.Context, portId string, channelId string, pagination *query.PageRequest) (*ibcchanneltypes.QueryPacketCommitmentsResponse, error) 265 FetchIBCPacketReceipt(ctx context.Context, portId string, channelId string, sequence uint64) (*ibcchanneltypes.QueryPacketReceiptResponse, error) 266 FetchIBCPacketAcknowledgement(ctx context.Context, portId string, channelId string, sequence uint64) (*ibcchanneltypes.QueryPacketAcknowledgementResponse, error) 267 FetchIBCPacketAcknowledgements(ctx context.Context, portId string, channelId string, packetCommitmentSequences []uint64, pagination *query.PageRequest) (*ibcchanneltypes.QueryPacketAcknowledgementsResponse, error) 268 FetchIBCUnreceivedPackets(ctx context.Context, portId string, channelId string, packetCommitmentSequences []uint64) (*ibcchanneltypes.QueryUnreceivedPacketsResponse, error) 269 FetchIBCUnreceivedAcks(ctx context.Context, portId string, channelId string, packetAckSequences []uint64) (*ibcchanneltypes.QueryUnreceivedAcksResponse, error) 270 FetchIBCNextSequenceReceive(ctx context.Context, portId string, channelId string) (*ibcchanneltypes.QueryNextSequenceReceiveResponse, error) 271 272 // IBC Core Chain module 273 FetchIBCClientState(ctx context.Context, clientId string) (*ibcclienttypes.QueryClientStateResponse, error) 274 FetchIBCClientStates(ctx context.Context, pagination *query.PageRequest) (*ibcclienttypes.QueryClientStatesResponse, error) 275 FetchIBCConsensusState(ctx context.Context, clientId string, revisionNumber uint64, revisionHeight uint64, latestHeight bool) (*ibcclienttypes.QueryConsensusStateResponse, error) 276 FetchIBCConsensusStates(ctx context.Context, clientId string, pagination *query.PageRequest) (*ibcclienttypes.QueryConsensusStatesResponse, error) 277 FetchIBCConsensusStateHeights(ctx context.Context, clientId string, pagination *query.PageRequest) (*ibcclienttypes.QueryConsensusStateHeightsResponse, error) 278 FetchIBCClientStatus(ctx context.Context, clientId string) (*ibcclienttypes.QueryClientStatusResponse, error) 279 FetchIBCClientParams(ctx context.Context) (*ibcclienttypes.QueryClientParamsResponse, error) 280 FetchIBCUpgradedClientState(ctx context.Context) (*ibcclienttypes.QueryUpgradedClientStateResponse, error) 281 FetchIBCUpgradedConsensusState(ctx context.Context) (*ibcclienttypes.QueryUpgradedConsensusStateResponse, error) 282 283 // IBC Core Connection module 284 FetchIBCConnection(ctx context.Context, connectionId string) (*ibcconnectiontypes.QueryConnectionResponse, error) 285 FetchIBCConnections(ctx context.Context, pagination *query.PageRequest) (*ibcconnectiontypes.QueryConnectionsResponse, error) 286 FetchIBCClientConnections(ctx context.Context, clientId string) (*ibcconnectiontypes.QueryClientConnectionsResponse, error) 287 FetchIBCConnectionClientState(ctx context.Context, connectionId string) (*ibcconnectiontypes.QueryConnectionClientStateResponse, error) 288 FetchIBCConnectionConsensusState(ctx context.Context, connectionId string, revisionNumber uint64, revisionHeight uint64) (*ibcconnectiontypes.QueryConnectionConsensusStateResponse, error) 289 FetchIBCConnectionParams(ctx context.Context) (*ibcconnectiontypes.QueryConnectionParamsResponse, error) 290 291 // Permissions module 292 FetchAllNamespaces(ctx context.Context) (*permissionstypes.QueryAllNamespacesResponse, error) 293 FetchNamespaceByDenom(ctx context.Context, denom string, includeRoles bool) (*permissionstypes.QueryNamespaceByDenomResponse, error) 294 FetchAddressRoles(ctx context.Context, denom, address string) (*permissionstypes.QueryAddressRolesResponse, error) 295 FetchAddressesByRole(ctx context.Context, denom, role string) (*permissionstypes.QueryAddressesByRoleResponse, error) 296 FetchVouchersForAddress(ctx context.Context, address string) (*permissionstypes.QueryVouchersForAddressResponse, error) 297 298 Close() 299 } 300 301 type chainClient struct { 302 ctx client.Context 303 network common.Network 304 opts *common.ClientOptions 305 logger log.Logger 306 conn *grpc.ClientConn 307 chainStreamConn *grpc.ClientConn 308 txFactory tx.Factory 309 310 doneC chan bool 311 msgC chan sdk.Msg 312 syncMux *sync.Mutex 313 314 cancelCtx context.Context 315 cancelFn func() 316 317 accNum uint64 318 accSeq uint64 319 gasWanted uint64 320 gasFee string 321 322 sessionEnabled bool 323 324 ofacChecker *OfacChecker 325 326 authQueryClient authtypes.QueryClient 327 authzQueryClient authztypes.QueryClient 328 bankQueryClient banktypes.QueryClient 329 chainStreamClient chainstreamtypes.StreamClient 330 distributionQueryClient distributiontypes.QueryClient 331 exchangeQueryClient exchangetypes.QueryClient 332 ibcChannelQueryClient ibcchanneltypes.QueryClient 333 ibcClientQueryClient ibcclienttypes.QueryClient 334 ibcConnectionQueryClient ibcconnectiontypes.QueryClient 335 ibcTransferQueryClient ibctransfertypes.QueryClient 336 permissionsQueryClient permissionstypes.QueryClient 337 tendermintQueryClient cmtservice.ServiceClient 338 tokenfactoryQueryClient tokenfactorytypes.QueryClient 339 txClient txtypes.ServiceClient 340 wasmQueryClient wasmtypes.QueryClient 341 subaccountToNonce map[ethcommon.Hash]uint32 342 343 closed int64 344 canSign bool 345 } 346 347 func NewChainClient( 348 ctx client.Context, 349 network common.Network, 350 options ...common.ClientOption, 351 ) (ChainClient, error) { 352 353 // process options 354 opts := common.DefaultClientOptions() 355 356 if network.ChainTLSCert != nil { 357 options = append(options, common.OptionTLSCert(network.ChainTLSCert)) 358 } 359 for _, opt := range options { 360 if err := opt(opts); err != nil { 361 err = errors.Wrap(err, "error in client option") 362 return nil, err 363 } 364 } 365 366 // init tx factory 367 var txFactory tx.Factory 368 if opts.TxFactory == nil { 369 txFactory = NewTxFactory(ctx) 370 if opts.GasPrices != "" { 371 txFactory = txFactory.WithGasPrices(opts.GasPrices) 372 } 373 } else { 374 txFactory = *opts.TxFactory 375 } 376 377 // init grpc connection 378 var conn *grpc.ClientConn 379 var err error 380 stickySessionEnabled := true 381 if opts.TLSCert != nil { 382 conn, err = grpc.Dial(network.ChainGrpcEndpoint, grpc.WithTransportCredentials(opts.TLSCert), grpc.WithContextDialer(common.DialerFunc)) 383 } else { 384 conn, err = grpc.Dial(network.ChainGrpcEndpoint, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithContextDialer(common.DialerFunc)) 385 stickySessionEnabled = false 386 } 387 if err != nil { 388 err = errors.Wrapf(err, "failed to connect to the gRPC: %s", network.ChainGrpcEndpoint) 389 return nil, err 390 } 391 392 var chainStreamConn *grpc.ClientConn 393 if opts.TLSCert != nil { 394 chainStreamConn, err = grpc.Dial(network.ChainStreamGrpcEndpoint, grpc.WithTransportCredentials(opts.TLSCert), grpc.WithContextDialer(common.DialerFunc)) 395 } else { 396 chainStreamConn, err = grpc.Dial(network.ChainStreamGrpcEndpoint, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithContextDialer(common.DialerFunc)) 397 } 398 if err != nil { 399 err = errors.Wrapf(err, "failed to connect to the chain stream gRPC: %s", network.ChainStreamGrpcEndpoint) 400 return nil, err 401 } 402 403 cancelCtx, cancelFn := context.WithCancel(context.Background()) 404 // build client 405 cc := &chainClient{ 406 ctx: ctx, 407 network: network, 408 opts: opts, 409 410 logger: log.WithFields(log.Fields{ 411 "module": "sdk-go", 412 "svc": "chainClient", 413 }), 414 415 conn: conn, 416 chainStreamConn: chainStreamConn, 417 txFactory: txFactory, 418 canSign: ctx.Keyring != nil, 419 syncMux: new(sync.Mutex), 420 msgC: make(chan sdk.Msg, msgCommitBatchSizeLimit), 421 doneC: make(chan bool, 1), 422 cancelCtx: cancelCtx, 423 cancelFn: cancelFn, 424 425 sessionEnabled: stickySessionEnabled, 426 427 authQueryClient: authtypes.NewQueryClient(conn), 428 authzQueryClient: authztypes.NewQueryClient(conn), 429 bankQueryClient: banktypes.NewQueryClient(conn), 430 chainStreamClient: chainstreamtypes.NewStreamClient(chainStreamConn), 431 distributionQueryClient: distributiontypes.NewQueryClient(conn), 432 exchangeQueryClient: exchangetypes.NewQueryClient(conn), 433 ibcChannelQueryClient: ibcchanneltypes.NewQueryClient(conn), 434 ibcClientQueryClient: ibcclienttypes.NewQueryClient(conn), 435 ibcConnectionQueryClient: ibcconnectiontypes.NewQueryClient(conn), 436 ibcTransferQueryClient: ibctransfertypes.NewQueryClient(conn), 437 permissionsQueryClient: permissionstypes.NewQueryClient(conn), 438 tendermintQueryClient: cmtservice.NewServiceClient(conn), 439 tokenfactoryQueryClient: tokenfactorytypes.NewQueryClient(conn), 440 txClient: txtypes.NewServiceClient(conn), 441 wasmQueryClient: wasmtypes.NewQueryClient(conn), 442 subaccountToNonce: make(map[ethcommon.Hash]uint32), 443 } 444 445 cc.ofacChecker, err = NewOfacChecker() 446 if err != nil { 447 return nil, errors.Wrap(err, "Error creating OFAC checker") 448 } 449 if cc.canSign { 450 var err error 451 account, err := cc.txFactory.AccountRetriever().GetAccount(ctx, ctx.GetFromAddress()) 452 if err != nil { 453 err = errors.Wrapf(err, "failed to get account") 454 return nil, err 455 } 456 if cc.ofacChecker.IsBlacklisted(account.GetAddress().String()) { 457 return nil, errors.Errorf("Address %s is in the OFAC list", account.GetAddress()) 458 } 459 cc.accNum, cc.accSeq = account.GetAccountNumber(), account.GetSequence() 460 go cc.runBatchBroadcast() 461 go cc.syncTimeoutHeight() 462 } 463 464 return cc, nil 465 } 466 func (c *chainClient) syncNonce() { 467 num, seq, err := c.txFactory.AccountRetriever().GetAccountNumberSequence(c.ctx, c.ctx.GetFromAddress()) 468 if err != nil { 469 c.logger.WithError(err).Errorln("failed to get account seq") 470 return 471 } else if num != c.accNum { 472 c.logger.WithFields(log.Fields{ 473 "expected": c.accNum, 474 "actual": num, 475 }).Panic("account number changed during nonce sync") 476 } 477 478 c.accSeq = seq 479 } 480 481 func (c *chainClient) syncTimeoutHeight() { 482 t := time.NewTicker(defaultTimeoutHeightSyncInterval) 483 defer t.Stop() 484 485 for { 486 block, err := c.ctx.Client.Block(c.cancelCtx, nil) 487 if err != nil { 488 c.logger.WithError(err).Errorln("failed to get current block") 489 return 490 } 491 c.txFactory.WithTimeoutHeight(uint64(block.Block.Height) + defaultTimeoutHeight) 492 493 select { 494 case <-c.cancelCtx.Done(): 495 return 496 case <-t.C: 497 continue 498 } 499 } 500 } 501 502 // PrepareFactory ensures the account defined by ctx.GetFromAddress() exists and 503 // if the account number and/or the account sequence number are zero (not set), 504 // they will be queried for and set on the provided Factory. A new Factory with 505 // the updated fields will be returned. 506 func PrepareFactory(clientCtx client.Context, txf tx.Factory) (tx.Factory, error) { 507 from := clientCtx.GetFromAddress() 508 509 if err := txf.AccountRetriever().EnsureExists(clientCtx, from); err != nil { 510 return txf, err 511 } 512 513 initNum, initSeq := txf.AccountNumber(), txf.Sequence() 514 if initNum == 0 || initSeq == 0 { 515 num, seq, err := txf.AccountRetriever().GetAccountNumberSequence(clientCtx, from) 516 if err != nil { 517 return txf, err 518 } 519 520 if initNum == 0 { 521 txf = txf.WithAccountNumber(num) 522 } 523 524 if initSeq == 0 { 525 txf = txf.WithSequence(seq) 526 } 527 } 528 529 return txf, nil 530 } 531 532 func (c *chainClient) getAccSeq() uint64 { 533 defer func() { 534 c.accSeq += 1 535 }() 536 return c.accSeq 537 } 538 539 func (c *chainClient) GetAccNonce() (accNum, accSeq uint64) { 540 return c.accNum, c.accSeq 541 } 542 543 func (c *chainClient) QueryClient() *grpc.ClientConn { 544 return c.conn 545 } 546 547 func (c *chainClient) ClientContext() client.Context { 548 return c.ctx 549 } 550 551 func (c *chainClient) CanSignTransactions() bool { 552 return c.canSign 553 } 554 555 func (c *chainClient) FromAddress() sdk.AccAddress { 556 if !c.canSign { 557 return sdk.AccAddress{} 558 } 559 560 return c.ctx.FromAddress 561 } 562 563 func (c *chainClient) Close() { 564 if !c.canSign { 565 return 566 } 567 if atomic.CompareAndSwapInt64(&c.closed, 0, 1) { 568 close(c.msgC) 569 } 570 571 if c.cancelFn != nil { 572 c.cancelFn() 573 } 574 <-c.doneC 575 if c.conn != nil { 576 c.conn.Close() 577 } 578 if c.chainStreamConn != nil { 579 c.chainStreamConn.Close() 580 } 581 } 582 583 // Bank Module 584 585 func (c *chainClient) GetBankBalances(ctx context.Context, address string) (*banktypes.QueryAllBalancesResponse, error) { 586 req := &banktypes.QueryAllBalancesRequest{ 587 Address: address, 588 } 589 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.bankQueryClient.AllBalances, req) 590 591 return res, err 592 } 593 594 func (c *chainClient) GetBankBalance(ctx context.Context, address, denom string) (*banktypes.QueryBalanceResponse, error) { 595 req := &banktypes.QueryBalanceRequest{ 596 Address: address, 597 Denom: denom, 598 } 599 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.bankQueryClient.Balance, req) 600 601 return res, err 602 } 603 604 func (c *chainClient) GetBankSpendableBalances(ctx context.Context, address string, pagination *query.PageRequest) (*banktypes.QuerySpendableBalancesResponse, error) { 605 req := &banktypes.QuerySpendableBalancesRequest{ 606 Address: address, 607 Pagination: pagination, 608 } 609 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.bankQueryClient.SpendableBalances, req) 610 611 return res, err 612 } 613 614 func (c *chainClient) GetBankSpendableBalancesByDenom(ctx context.Context, address, denom string) (*banktypes.QuerySpendableBalanceByDenomResponse, error) { 615 req := &banktypes.QuerySpendableBalanceByDenomRequest{ 616 Address: address, 617 Denom: denom, 618 } 619 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.bankQueryClient.SpendableBalanceByDenom, req) 620 621 return res, err 622 } 623 624 func (c *chainClient) GetBankTotalSupply(ctx context.Context, pagination *query.PageRequest) (*banktypes.QueryTotalSupplyResponse, error) { 625 req := &banktypes.QueryTotalSupplyRequest{Pagination: pagination} 626 resp, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.bankQueryClient.TotalSupply, req) 627 628 return resp, err 629 } 630 631 func (c *chainClient) GetBankSupplyOf(ctx context.Context, denom string) (*banktypes.QuerySupplyOfResponse, error) { 632 req := &banktypes.QuerySupplyOfRequest{Denom: denom} 633 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.bankQueryClient.SupplyOf, req) 634 635 return res, err 636 } 637 638 func (c *chainClient) GetDenomMetadata(ctx context.Context, denom string) (*banktypes.QueryDenomMetadataResponse, error) { 639 req := &banktypes.QueryDenomMetadataRequest{Denom: denom} 640 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.bankQueryClient.DenomMetadata, req) 641 642 return res, err 643 } 644 645 func (c *chainClient) GetDenomsMetadata(ctx context.Context, pagination *query.PageRequest) (*banktypes.QueryDenomsMetadataResponse, error) { 646 req := &banktypes.QueryDenomsMetadataRequest{Pagination: pagination} 647 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.bankQueryClient.DenomsMetadata, req) 648 649 return res, err 650 } 651 652 func (c *chainClient) GetDenomOwners(ctx context.Context, denom string, pagination *query.PageRequest) (*banktypes.QueryDenomOwnersResponse, error) { 653 req := &banktypes.QueryDenomOwnersRequest{ 654 Denom: denom, 655 Pagination: pagination, 656 } 657 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.bankQueryClient.DenomOwners, req) 658 659 return res, err 660 } 661 662 func (c *chainClient) GetBankSendEnabled(ctx context.Context, denoms []string, pagination *query.PageRequest) (*banktypes.QuerySendEnabledResponse, error) { 663 req := &banktypes.QuerySendEnabledRequest{ 664 Denoms: denoms, 665 Pagination: pagination, 666 } 667 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.bankQueryClient.SendEnabled, req) 668 669 return res, err 670 } 671 672 // Auth Module 673 674 func (c *chainClient) GetAccount(ctx context.Context, address string) (*authtypes.QueryAccountResponse, error) { 675 req := &authtypes.QueryAccountRequest{ 676 Address: address, 677 } 678 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.authQueryClient.Account, req) 679 680 return res, err 681 } 682 683 // SyncBroadcastMsg sends Tx to chain and waits until Tx is included in block. 684 func (c *chainClient) SyncBroadcastMsg(msgs ...sdk.Msg) (*txtypes.BroadcastTxResponse, error) { 685 c.syncMux.Lock() 686 defer c.syncMux.Unlock() 687 688 sequence := c.getAccSeq() 689 c.txFactory = c.txFactory.WithSequence(sequence) 690 c.txFactory = c.txFactory.WithAccountNumber(c.accNum) 691 res, err := c.broadcastTx(c.ctx, c.txFactory, true, msgs...) 692 693 if err != nil { 694 if c.opts.ShouldFixSequenceMismatch && strings.Contains(err.Error(), "account sequence mismatch") { 695 c.syncNonce() 696 sequence := c.getAccSeq() 697 c.txFactory = c.txFactory.WithSequence(sequence) 698 c.txFactory = c.txFactory.WithAccountNumber(c.accNum) 699 log.Debugln("retrying broadcastTx with nonce", sequence) 700 res, err = c.broadcastTx(c.ctx, c.txFactory, true, msgs...) 701 } 702 if err != nil { 703 resJSON, _ := json.MarshalIndent(res, "", "\t") 704 c.logger.WithField("size", len(msgs)).WithError(err).Errorln("failed synchronously broadcast messages:", string(resJSON)) 705 return nil, err 706 } 707 } 708 709 return res, nil 710 } 711 712 func (c *chainClient) GetFeeDiscountInfo(ctx context.Context, account string) (*exchangetypes.QueryFeeDiscountAccountInfoResponse, error) { 713 req := &exchangetypes.QueryFeeDiscountAccountInfoRequest{ 714 Account: account, 715 } 716 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.FeeDiscountAccountInfo, req) 717 718 return res, err 719 } 720 721 func (c *chainClient) SimulateMsg(clientCtx client.Context, msgs ...sdk.Msg) (*txtypes.SimulateResponse, error) { 722 c.txFactory = c.txFactory.WithSequence(c.accSeq) 723 c.txFactory = c.txFactory.WithAccountNumber(c.accNum) 724 txf, err := PrepareFactory(clientCtx, c.txFactory) 725 if err != nil { 726 err = errors.Wrap(err, "failed to prepareFactory") 727 return nil, err 728 } 729 730 simTxBytes, err := txf.BuildSimTx(msgs...) 731 if err != nil { 732 err = errors.Wrap(err, "failed to build sim tx bytes") 733 return nil, err 734 } 735 736 ctx := context.Background() 737 req := &txtypes.SimulateRequest{TxBytes: simTxBytes} 738 simRes, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.txClient.Simulate, req) 739 740 if err != nil { 741 err = errors.Wrap(err, "failed to CalculateGas") 742 return nil, err 743 } 744 745 return simRes, nil 746 } 747 748 // AsyncBroadcastMsg sends Tx to chain and doesn't wait until Tx is included in block. This method 749 // cannot be used for rapid Tx sending, it is expected that you wait for transaction status with 750 // external tools. If you want sdk to wait for it, use SyncBroadcastMsg. 751 func (c *chainClient) AsyncBroadcastMsg(msgs ...sdk.Msg) (*txtypes.BroadcastTxResponse, error) { 752 c.syncMux.Lock() 753 defer c.syncMux.Unlock() 754 755 sequence := c.getAccSeq() 756 c.txFactory = c.txFactory.WithSequence(sequence) 757 c.txFactory = c.txFactory.WithAccountNumber(c.accNum) 758 res, err := c.broadcastTx(c.ctx, c.txFactory, false, msgs...) 759 if err != nil { 760 if c.opts.ShouldFixSequenceMismatch && strings.Contains(err.Error(), "account sequence mismatch") { 761 c.syncNonce() 762 sequence := c.getAccSeq() 763 c.txFactory = c.txFactory.WithSequence(sequence) 764 c.txFactory = c.txFactory.WithAccountNumber(c.accNum) 765 log.Debugln("retrying broadcastTx with nonce", sequence) 766 res, err = c.broadcastTx(c.ctx, c.txFactory, false, msgs...) 767 } 768 if err != nil { 769 resJSON, _ := json.MarshalIndent(res, "", "\t") 770 c.logger.WithField("size", len(msgs)).WithError(err).Errorln("failed to asynchronously broadcast messagess:", string(resJSON)) 771 return nil, err 772 } 773 } 774 775 return res, nil 776 } 777 778 func (c *chainClient) BuildSignedTx(clientCtx client.Context, accNum, accSeq, initialGas uint64, msgs ...sdk.Msg) ([]byte, error) { 779 txf := NewTxFactory(clientCtx).WithSequence(accSeq).WithAccountNumber(accNum).WithGas(initialGas) 780 return c.buildSignedTx(clientCtx, txf, msgs...) 781 } 782 783 func (c *chainClient) buildSignedTx(clientCtx client.Context, txf tx.Factory, msgs ...sdk.Msg) ([]byte, error) { 784 ctx := context.Background() 785 if clientCtx.Simulate { 786 simTxBytes, err := txf.BuildSimTx(msgs...) 787 if err != nil { 788 err = errors.Wrap(err, "failed to build sim tx bytes") 789 return nil, err 790 } 791 792 req := &txtypes.SimulateRequest{TxBytes: simTxBytes} 793 simRes, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.txClient.Simulate, req) 794 795 if err != nil { 796 err = errors.Wrap(err, "failed to CalculateGas") 797 return nil, err 798 } 799 800 adjustedGas := uint64(txf.GasAdjustment() * float64(simRes.GasInfo.GasUsed)) 801 txf = txf.WithGas(adjustedGas) 802 803 c.gasWanted = adjustedGas 804 } 805 806 txf, err := PrepareFactory(clientCtx, txf) 807 if err != nil { 808 return nil, errors.Wrap(err, "failed to prepareFactory") 809 } 810 811 txn, err := txf.BuildUnsignedTx(msgs...) 812 if err != nil { 813 err = errors.Wrap(err, "failed to BuildUnsignedTx") 814 return nil, err 815 } 816 817 txn.SetFeeGranter(clientCtx.GetFeeGranterAddress()) 818 err = tx.Sign(ctx, txf, clientCtx.GetFromName(), txn, true) 819 if err != nil { 820 err = errors.Wrap(err, "failed to Sign Tx") 821 return nil, err 822 } 823 824 return clientCtx.TxConfig.TxEncoder()(txn.GetTx()) 825 } 826 827 func (c *chainClient) SyncBroadcastSignedTx(txBytes []byte) (*txtypes.BroadcastTxResponse, error) { 828 req := txtypes.BroadcastTxRequest{ 829 TxBytes: txBytes, 830 Mode: txtypes.BroadcastMode_BROADCAST_MODE_SYNC, 831 } 832 833 ctx := context.Background() 834 835 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.txClient.BroadcastTx, &req) 836 if err != nil || res.TxResponse.Code != 0 { 837 return res, err 838 } 839 840 awaitCtx, cancelFn := context.WithTimeout(context.Background(), defaultBroadcastTimeout) 841 defer cancelFn() 842 843 txHash, _ := hex.DecodeString(res.TxResponse.TxHash) 844 t := time.NewTimer(defaultBroadcastStatusPoll) 845 846 for { 847 select { 848 case <-awaitCtx.Done(): 849 err := errors.Wrapf(ErrTimedOut, "%s", res.TxResponse.TxHash) 850 t.Stop() 851 return nil, err 852 case <-t.C: 853 resultTx, err := c.ctx.Client.Tx(awaitCtx, txHash, false) 854 if err != nil { 855 if errRes := client.CheckCometError(err, txBytes); errRes != nil { 856 return &txtypes.BroadcastTxResponse{TxResponse: errRes}, err 857 } 858 859 t.Reset(defaultBroadcastStatusPoll) 860 continue 861 862 } else if resultTx.Height > 0 { 863 resResultTx := sdk.NewResponseResultTx(resultTx, res.TxResponse.Tx, res.TxResponse.Timestamp) 864 res = &txtypes.BroadcastTxResponse{TxResponse: resResultTx} 865 t.Stop() 866 return res, err 867 } 868 869 t.Reset(defaultBroadcastStatusPoll) 870 } 871 } 872 } 873 874 func (c *chainClient) AsyncBroadcastSignedTx(txBytes []byte) (*txtypes.BroadcastTxResponse, error) { 875 req := txtypes.BroadcastTxRequest{ 876 TxBytes: txBytes, 877 Mode: txtypes.BroadcastMode_BROADCAST_MODE_SYNC, 878 } 879 880 ctx := context.Background() 881 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.txClient.BroadcastTx, &req) 882 if err != nil { 883 return nil, err 884 } 885 886 return res, nil 887 } 888 889 func (c *chainClient) broadcastTx( 890 clientCtx client.Context, 891 txf tx.Factory, 892 await bool, 893 msgs ...sdk.Msg, 894 ) (*txtypes.BroadcastTxResponse, error) { 895 txBytes, err := c.buildSignedTx(clientCtx, txf, msgs...) 896 if err != nil { 897 err = errors.Wrap(err, "failed to build signed Tx") 898 return nil, err 899 } 900 901 req := txtypes.BroadcastTxRequest{ 902 TxBytes: txBytes, 903 Mode: txtypes.BroadcastMode_BROADCAST_MODE_SYNC, 904 } 905 906 res, err := common.ExecuteCall(context.Background(), c.network.ChainCookieAssistant, c.txClient.BroadcastTx, &req) 907 if err != nil || res.TxResponse.Code != 0 || !await { 908 return res, err 909 } 910 911 awaitCtx, cancelFn := context.WithTimeout(context.Background(), defaultBroadcastTimeout) 912 defer cancelFn() 913 914 txHash, _ := hex.DecodeString(res.TxResponse.TxHash) 915 t := time.NewTimer(defaultBroadcastStatusPoll) 916 917 for { 918 select { 919 case <-awaitCtx.Done(): 920 err := errors.Wrapf(ErrTimedOut, "%s", res.TxResponse.TxHash) 921 t.Stop() 922 return nil, err 923 case <-t.C: 924 resultTx, err := clientCtx.Client.Tx(awaitCtx, txHash, false) 925 if err != nil { 926 if errRes := client.CheckCometError(err, txBytes); errRes != nil { 927 return &txtypes.BroadcastTxResponse{TxResponse: errRes}, err 928 } 929 930 t.Reset(defaultBroadcastStatusPoll) 931 continue 932 933 } else if resultTx.Height > 0 { 934 resResultTx := sdk.NewResponseResultTx(resultTx, res.TxResponse.Tx, res.TxResponse.Timestamp) 935 res = &txtypes.BroadcastTxResponse{TxResponse: resResultTx} 936 t.Stop() 937 return res, err 938 } 939 940 t.Reset(defaultBroadcastStatusPoll) 941 } 942 } 943 } 944 945 // QueueBroadcastMsg enqueues a list of messages. Messages will added to the queue 946 // and grouped into Txns in chunks. Use this method to mass broadcast Txns with efficiency. 947 func (c *chainClient) QueueBroadcastMsg(msgs ...sdk.Msg) error { 948 if !c.canSign { 949 return ErrReadOnly 950 } else if atomic.LoadInt64(&c.closed) == 1 { 951 return ErrQueueClosed 952 } 953 954 t := time.NewTimer(10 * time.Second) 955 for _, msg := range msgs { 956 select { 957 case <-t.C: 958 return ErrEnqueueTimeout 959 case c.msgC <- msg: 960 } 961 } 962 t.Stop() 963 964 return nil 965 } 966 967 func (c *chainClient) runBatchBroadcast() { 968 expirationTimer := time.NewTimer(msgCommitBatchTimeLimit) 969 msgBatch := make([]sdk.Msg, 0, msgCommitBatchSizeLimit) 970 971 submitBatch := func(toSubmit []sdk.Msg) { 972 c.syncMux.Lock() 973 defer c.syncMux.Unlock() 974 sequence := c.getAccSeq() 975 c.txFactory = c.txFactory.WithSequence(sequence) 976 c.txFactory = c.txFactory.WithAccountNumber(c.accNum) 977 log.Debugln("broadcastTx with nonce", sequence) 978 res, err := c.broadcastTx(c.ctx, c.txFactory, true, toSubmit...) 979 if err != nil { 980 if c.opts.ShouldFixSequenceMismatch && strings.Contains(err.Error(), "account sequence mismatch") { 981 c.syncNonce() 982 sequence := c.getAccSeq() 983 c.txFactory = c.txFactory.WithSequence(sequence) 984 c.txFactory = c.txFactory.WithAccountNumber(c.accNum) 985 log.Debugln("retrying broadcastTx with nonce", sequence) 986 res, err = c.broadcastTx(c.ctx, c.txFactory, true, toSubmit...) 987 } 988 if err != nil { 989 resJSON, _ := json.MarshalIndent(res, "", "\t") 990 c.logger.WithField("size", len(toSubmit)).WithError(err).Errorln("failed to broadcast messages batch:", string(resJSON)) 991 return 992 } 993 } 994 995 if res.TxResponse.Code != 0 { 996 err = errors.Errorf("error %d (%s): %s", res.TxResponse.Code, res.TxResponse.Codespace, res.TxResponse.RawLog) 997 log.WithField("txHash", res.TxResponse.TxHash).WithError(err).Errorln("failed to broadcast messages batch") 998 } else { 999 log.WithField("txHash", res.TxResponse.TxHash).Debugln("msg batch broadcasted successfully at height", res.TxResponse.Height) 1000 } 1001 1002 log.Debugln("gas wanted: ", c.gasWanted) 1003 } 1004 1005 for { 1006 select { 1007 case msg, ok := <-c.msgC: 1008 if !ok { 1009 // exit required 1010 if len(msgBatch) > 0 { 1011 submitBatch(msgBatch) 1012 } 1013 1014 close(c.doneC) 1015 return 1016 } 1017 1018 msgBatch = append(msgBatch, msg) 1019 1020 if len(msgBatch) >= msgCommitBatchSizeLimit { 1021 toSubmit := msgBatch 1022 msgBatch = msgBatch[:0] 1023 expirationTimer.Reset(msgCommitBatchTimeLimit) 1024 1025 submitBatch(toSubmit) 1026 } 1027 case <-expirationTimer.C: 1028 if len(msgBatch) > 0 { 1029 toSubmit := msgBatch 1030 msgBatch = msgBatch[:0] 1031 expirationTimer.Reset(msgCommitBatchTimeLimit) 1032 submitBatch(toSubmit) 1033 } else { 1034 expirationTimer.Reset(msgCommitBatchTimeLimit) 1035 } 1036 } 1037 } 1038 } 1039 1040 func (c *chainClient) GetGasFee() (string, error) { 1041 gasPrices := strings.Trim(c.opts.GasPrices, "inj") 1042 1043 gas, err := strconv.ParseFloat(gasPrices, 64) 1044 1045 if err != nil { 1046 return "", err 1047 } 1048 1049 gasFeeAdjusted := gas * float64(c.gasWanted) / math.Pow(10, 18) 1050 gasFeeFormatted := strconv.FormatFloat(gasFeeAdjusted, 'f', -1, 64) 1051 c.gasFee = gasFeeFormatted 1052 1053 return c.gasFee, err 1054 } 1055 1056 func (c *chainClient) DefaultSubaccount(acc sdk.AccAddress) ethcommon.Hash { 1057 return c.Subaccount(acc, 0) 1058 } 1059 1060 func (c *chainClient) Subaccount(account sdk.AccAddress, index int) ethcommon.Hash { 1061 ethAddress := ethcommon.BytesToAddress(account.Bytes()) 1062 ethLowerAddress := strings.ToLower(ethAddress.String()) 1063 1064 subaccountId := fmt.Sprintf("%s%024x", ethLowerAddress, index) 1065 return ethcommon.HexToHash(subaccountId) 1066 } 1067 1068 func (c *chainClient) GetSubAccountNonce(ctx context.Context, subaccountId ethcommon.Hash) (*exchangetypes.QuerySubaccountTradeNonceResponse, error) { 1069 req := &exchangetypes.QuerySubaccountTradeNonceRequest{SubaccountId: subaccountId.String()} 1070 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.SubaccountTradeNonce, req) 1071 1072 return res, err 1073 } 1074 1075 // Deprecated: Use CreateSpotOrder instead 1076 func (c *chainClient) SpotOrder(defaultSubaccountID ethcommon.Hash, network common.Network, d *SpotOrderData) *exchangetypes.SpotOrder { 1077 assistant, err := NewMarketsAssistant(network.Name) 1078 if err != nil { 1079 panic(err) 1080 } 1081 1082 return c.CreateSpotOrder(defaultSubaccountID, d, assistant) 1083 } 1084 1085 func (c *chainClient) CreateSpotOrder(defaultSubaccountID ethcommon.Hash, d *SpotOrderData, marketsAssistant MarketsAssistant) *exchangetypes.SpotOrder { 1086 1087 market, isPresent := marketsAssistant.AllSpotMarkets()[d.MarketId] 1088 if !isPresent { 1089 panic(errors.Errorf("Invalid spot market id for %s network (%s)", c.network.Name, d.MarketId)) 1090 } 1091 1092 orderSize := market.QuantityToChainFormat(d.Quantity) 1093 orderPrice := market.PriceToChainFormat(d.Price) 1094 1095 return &exchangetypes.SpotOrder{ 1096 MarketId: d.MarketId, 1097 OrderType: d.OrderType, 1098 OrderInfo: exchangetypes.OrderInfo{ 1099 SubaccountId: defaultSubaccountID.Hex(), 1100 FeeRecipient: d.FeeRecipient, 1101 Price: orderPrice, 1102 Quantity: orderSize, 1103 Cid: d.Cid, 1104 }, 1105 } 1106 } 1107 1108 // Deprecated: Use CreateDerivativeOrder instead 1109 func (c *chainClient) DerivativeOrder(defaultSubaccountID ethcommon.Hash, network common.Network, d *DerivativeOrderData) *exchangetypes.DerivativeOrder { 1110 1111 assistant, err := NewMarketsAssistant(network.Name) 1112 if err != nil { 1113 panic(err) 1114 } 1115 1116 return c.CreateDerivativeOrder(defaultSubaccountID, d, assistant) 1117 } 1118 1119 func (c *chainClient) CreateDerivativeOrder(defaultSubaccountID ethcommon.Hash, d *DerivativeOrderData, marketAssistant MarketsAssistant) *exchangetypes.DerivativeOrder { 1120 market, isPresent := marketAssistant.AllDerivativeMarkets()[d.MarketId] 1121 if !isPresent { 1122 panic(errors.Errorf("Invalid derivative market id for %s network (%s)", c.network.Name, d.MarketId)) 1123 } 1124 1125 orderSize := market.QuantityToChainFormat(d.Quantity) 1126 orderPrice := market.PriceToChainFormat(d.Price) 1127 orderMargin := sdkmath.LegacyMustNewDecFromStr("0") 1128 1129 if !d.IsReduceOnly { 1130 orderMargin = market.CalculateMarginInChainFormat(d.Quantity, d.Price, d.Leverage) 1131 } 1132 1133 return &exchangetypes.DerivativeOrder{ 1134 MarketId: d.MarketId, 1135 OrderType: d.OrderType, 1136 Margin: orderMargin, 1137 OrderInfo: exchangetypes.OrderInfo{ 1138 SubaccountId: defaultSubaccountID.Hex(), 1139 FeeRecipient: d.FeeRecipient, 1140 Price: orderPrice, 1141 Quantity: orderSize, 1142 Cid: d.Cid, 1143 }, 1144 } 1145 } 1146 1147 func (c *chainClient) OrderCancel(defaultSubaccountID ethcommon.Hash, d *OrderCancelData) *exchangetypes.OrderData { 1148 return &exchangetypes.OrderData{ 1149 MarketId: d.MarketId, 1150 OrderHash: d.OrderHash, 1151 SubaccountId: defaultSubaccountID.Hex(), 1152 Cid: d.Cid, 1153 } 1154 } 1155 1156 func (c *chainClient) GetAuthzGrants(ctx context.Context, req authztypes.QueryGrantsRequest) (*authztypes.QueryGrantsResponse, error) { 1157 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.authzQueryClient.Grants, &req) 1158 1159 return res, err 1160 } 1161 1162 func (c *chainClient) BuildGenericAuthz(granter, grantee, msgtype string, expireIn time.Time) *authztypes.MsgGrant { 1163 if c.ofacChecker.IsBlacklisted(granter) { 1164 panic("Address is in the OFAC list") // panics should generally be avoided, but otherwise function signature should be changed 1165 } 1166 authz := authztypes.NewGenericAuthorization(msgtype) 1167 authzAny := codectypes.UnsafePackAny(authz) 1168 return &authztypes.MsgGrant{ 1169 Granter: granter, 1170 Grantee: grantee, 1171 Grant: authztypes.Grant{ 1172 Authorization: authzAny, 1173 Expiration: &expireIn, 1174 }, 1175 } 1176 } 1177 1178 type ExchangeAuthz string 1179 1180 var ( 1181 CreateSpotLimitOrderAuthz = ExchangeAuthz("/" + proto.MessageName(&exchangetypes.CreateSpotLimitOrderAuthz{})) 1182 CreateSpotMarketOrderAuthz = ExchangeAuthz("/" + proto.MessageName(&exchangetypes.CreateSpotMarketOrderAuthz{})) 1183 BatchCreateSpotLimitOrdersAuthz = ExchangeAuthz("/" + proto.MessageName(&exchangetypes.BatchCreateSpotLimitOrdersAuthz{})) 1184 CancelSpotOrderAuthz = ExchangeAuthz("/" + proto.MessageName(&exchangetypes.CancelSpotOrderAuthz{})) 1185 BatchCancelSpotOrdersAuthz = ExchangeAuthz("/" + proto.MessageName(&exchangetypes.BatchCancelSpotOrdersAuthz{})) 1186 1187 CreateDerivativeLimitOrderAuthz = ExchangeAuthz("/" + proto.MessageName(&exchangetypes.CreateDerivativeLimitOrderAuthz{})) 1188 CreateDerivativeMarketOrderAuthz = ExchangeAuthz("/" + proto.MessageName(&exchangetypes.CreateDerivativeMarketOrderAuthz{})) 1189 BatchCreateDerivativeLimitOrdersAuthz = ExchangeAuthz("/" + proto.MessageName(&exchangetypes.BatchCreateDerivativeLimitOrdersAuthz{})) 1190 CancelDerivativeOrderAuthz = ExchangeAuthz("/" + proto.MessageName(&exchangetypes.CancelDerivativeOrderAuthz{})) 1191 BatchCancelDerivativeOrdersAuthz = ExchangeAuthz("/" + proto.MessageName(&exchangetypes.BatchCancelDerivativeOrdersAuthz{})) 1192 1193 BatchUpdateOrdersAuthz = ExchangeAuthz("/" + proto.MessageName(&exchangetypes.BatchUpdateOrdersAuthz{})) 1194 ) 1195 1196 func (c *chainClient) BuildExchangeAuthz(granter, grantee string, authzType ExchangeAuthz, subaccountId string, markets []string, expireIn time.Time) *authztypes.MsgGrant { 1197 if c.ofacChecker.IsBlacklisted(granter) { 1198 panic("Address is in the OFAC list") // panics should generally be avoided, but otherwise function signature should be changed 1199 } 1200 var typedAuthzAny codectypes.Any 1201 var typedAuthzBytes []byte 1202 switch authzType { 1203 // spot msgs 1204 case CreateSpotLimitOrderAuthz: 1205 typedAuthz := &exchangetypes.CreateSpotLimitOrderAuthz{ 1206 SubaccountId: subaccountId, 1207 MarketIds: markets, 1208 } 1209 typedAuthzBytes, _ = typedAuthz.Marshal() 1210 case CreateSpotMarketOrderAuthz: 1211 typedAuthz := &exchangetypes.CreateSpotMarketOrderAuthz{ 1212 SubaccountId: subaccountId, 1213 MarketIds: markets, 1214 } 1215 typedAuthzBytes, _ = typedAuthz.Marshal() 1216 case BatchCreateSpotLimitOrdersAuthz: 1217 typedAuthz := &exchangetypes.BatchCreateSpotLimitOrdersAuthz{ 1218 SubaccountId: subaccountId, 1219 MarketIds: markets, 1220 } 1221 typedAuthzBytes, _ = typedAuthz.Marshal() 1222 case CancelSpotOrderAuthz: 1223 typedAuthz := &exchangetypes.CancelSpotOrderAuthz{ 1224 SubaccountId: subaccountId, 1225 MarketIds: markets, 1226 } 1227 typedAuthzBytes, _ = typedAuthz.Marshal() 1228 case BatchCancelSpotOrdersAuthz: 1229 typedAuthz := &exchangetypes.BatchCancelSpotOrdersAuthz{ 1230 SubaccountId: subaccountId, 1231 MarketIds: markets, 1232 } 1233 typedAuthzBytes, _ = typedAuthz.Marshal() 1234 // derivative msgs 1235 case CreateDerivativeLimitOrderAuthz: 1236 typedAuthz := &exchangetypes.CreateDerivativeLimitOrderAuthz{ 1237 SubaccountId: subaccountId, 1238 MarketIds: markets, 1239 } 1240 typedAuthzBytes, _ = typedAuthz.Marshal() 1241 case CreateDerivativeMarketOrderAuthz: 1242 typedAuthz := &exchangetypes.CreateDerivativeMarketOrderAuthz{ 1243 SubaccountId: subaccountId, 1244 MarketIds: markets, 1245 } 1246 typedAuthzBytes, _ = typedAuthz.Marshal() 1247 case BatchCreateDerivativeLimitOrdersAuthz: 1248 typedAuthz := &exchangetypes.BatchCreateDerivativeLimitOrdersAuthz{ 1249 SubaccountId: subaccountId, 1250 MarketIds: markets, 1251 } 1252 typedAuthzBytes, _ = typedAuthz.Marshal() 1253 case CancelDerivativeOrderAuthz: 1254 typedAuthz := &exchangetypes.CancelDerivativeOrderAuthz{ 1255 SubaccountId: subaccountId, 1256 MarketIds: markets, 1257 } 1258 typedAuthzBytes, _ = typedAuthz.Marshal() 1259 case BatchCancelDerivativeOrdersAuthz: 1260 typedAuthz := &exchangetypes.BatchCancelDerivativeOrdersAuthz{ 1261 SubaccountId: subaccountId, 1262 MarketIds: markets, 1263 } 1264 typedAuthzBytes, _ = typedAuthz.Marshal() 1265 // common msgs 1266 case BatchUpdateOrdersAuthz: 1267 panic("please use BuildExchangeBatchUpdateOrdersAuthz for BatchUpdateOrdersAuthz") 1268 default: 1269 panic("unsupported exchange authz type") 1270 } 1271 1272 typedAuthzAny = codectypes.Any{ 1273 TypeUrl: string(authzType), 1274 Value: typedAuthzBytes, 1275 } 1276 1277 return &authztypes.MsgGrant{ 1278 Granter: granter, 1279 Grantee: grantee, 1280 Grant: authztypes.Grant{ 1281 Authorization: &typedAuthzAny, 1282 Expiration: &expireIn, 1283 }, 1284 } 1285 } 1286 1287 func (c *chainClient) BuildExchangeBatchUpdateOrdersAuthz( 1288 granter string, 1289 grantee string, 1290 subaccountId string, 1291 spotMarkets []string, 1292 derivativeMarkets []string, 1293 expireIn time.Time, 1294 ) *authztypes.MsgGrant { 1295 if c.ofacChecker.IsBlacklisted(granter) { 1296 panic("Address is in the OFAC list") // panics should generally be avoided, but otherwise function signature should be changed 1297 } 1298 typedAuthz := &exchangetypes.BatchUpdateOrdersAuthz{ 1299 SubaccountId: subaccountId, 1300 SpotMarkets: spotMarkets, 1301 DerivativeMarkets: derivativeMarkets, 1302 } 1303 typedAuthzBytes, _ := typedAuthz.Marshal() 1304 typedAuthzAny := codectypes.Any{ 1305 TypeUrl: string(BatchUpdateOrdersAuthz), 1306 Value: typedAuthzBytes, 1307 } 1308 return &authztypes.MsgGrant{ 1309 Granter: granter, 1310 Grantee: grantee, 1311 Grant: authztypes.Grant{ 1312 Authorization: &typedAuthzAny, 1313 Expiration: &expireIn, 1314 }, 1315 } 1316 } 1317 1318 func (c *chainClient) StreamEventOrderFail(sender string, failEventCh chan map[string]uint) { 1319 var cometbftClient *rpchttp.HTTP 1320 var err error 1321 1322 cometbftClient, err = rpchttp.New(c.network.TmEndpoint, "/websocket") 1323 if err != nil { 1324 panic(err) 1325 } 1326 1327 if !cometbftClient.IsRunning() { 1328 err = cometbftClient.Start() 1329 if err != nil { 1330 panic(err) 1331 } 1332 } 1333 defer func() { 1334 err := cometbftClient.Stop() 1335 if err != nil { 1336 panic(err) 1337 } 1338 }() 1339 1340 c.StreamEventOrderFailWithWebsocket(sender, cometbftClient, failEventCh) 1341 } 1342 1343 func (c *chainClient) StreamEventOrderFailWithWebsocket(sender string, websocket *rpchttp.HTTP, failEventCh chan map[string]uint) { 1344 filter := fmt.Sprintf("tm.event='Tx' AND message.sender='%s' AND message.action='/injective.exchange.v1beta1.MsgBatchUpdateOrders' AND injective.exchange.v1beta1.EventOrderFail.flags EXISTS", sender) 1345 eventCh, err := websocket.Subscribe(context.Background(), "OrderFail", filter, 10000) 1346 if err != nil { 1347 panic(err) 1348 } 1349 1350 // stream and extract fail events 1351 for { 1352 e := <-eventCh 1353 1354 var failedOrderHashes []string 1355 err = json.Unmarshal([]byte(e.Events["injective.exchange.v1beta1.EventOrderFail.hashes"][0]), &failedOrderHashes) 1356 if err != nil { 1357 panic(err) 1358 } 1359 1360 var failedOrderCodes []uint 1361 err = json.Unmarshal([]byte(e.Events["injective.exchange.v1beta1.EventOrderFail.flags"][0]), &failedOrderCodes) 1362 if err != nil { 1363 panic(err) 1364 } 1365 1366 results := map[string]uint{} 1367 for i, hash := range failedOrderHashes { 1368 orderHashBytes, _ := base64.StdEncoding.DecodeString(hash) 1369 orderHash := ethcommon.BytesToHash(orderHashBytes).String() 1370 results[orderHash] = failedOrderCodes[i] 1371 } 1372 1373 failEventCh <- results 1374 } 1375 } 1376 1377 func (c *chainClient) StreamOrderbookUpdateEvents(orderbookType OrderbookType, marketIDs []string, orderbookCh chan exchangetypes.Orderbook) { 1378 var cometbftClient *rpchttp.HTTP 1379 var err error 1380 1381 cometbftClient, err = rpchttp.New(c.network.TmEndpoint, "/websocket") 1382 if err != nil { 1383 panic(err) 1384 } 1385 1386 if !cometbftClient.IsRunning() { 1387 err = cometbftClient.Start() 1388 if err != nil { 1389 panic(err) 1390 } 1391 } 1392 defer func() { 1393 err := cometbftClient.Stop() 1394 if err != nil { 1395 panic(err) 1396 } 1397 }() 1398 1399 c.StreamOrderbookUpdateEventsWithWebsocket(orderbookType, marketIDs, cometbftClient, orderbookCh) 1400 1401 } 1402 1403 func (c *chainClient) StreamOrderbookUpdateEventsWithWebsocket(orderbookType OrderbookType, marketIDs []string, websocket *rpchttp.HTTP, orderbookCh chan exchangetypes.Orderbook) { 1404 filter := fmt.Sprintf("tm.event='NewBlock' AND %s EXISTS", orderbookType) 1405 eventCh, err := websocket.Subscribe(context.Background(), "OrderbookUpdate", filter, 10000) 1406 if err != nil { 1407 panic(err) 1408 } 1409 1410 // turn array into map for convenient lookup 1411 marketIDsMap := map[string]bool{} 1412 for _, id := range marketIDs { 1413 marketIDsMap[id] = true 1414 } 1415 1416 filteredOrderbookUpdateCh := make(chan exchangetypes.Orderbook, 10000) 1417 1418 // stream and filter orderbooks 1419 go func() { 1420 for { 1421 e := <-eventCh 1422 1423 var allOrderbookUpdates []exchangetypes.Orderbook 1424 err = json.Unmarshal([]byte(e.Events[string(orderbookType)][0]), &allOrderbookUpdates) 1425 if err != nil { 1426 panic(err) 1427 } 1428 1429 for _, ob := range allOrderbookUpdates { 1430 id := ethcommon.BytesToHash(ob.MarketId).String() 1431 if marketIDsMap[id] { 1432 filteredOrderbookUpdateCh <- ob 1433 } 1434 } 1435 } 1436 }() 1437 1438 // fetch the orderbooks 1439 1440 // consume from filtered orderbooks channel 1441 for { 1442 ob := <-filteredOrderbookUpdateCh 1443 1444 // skip update id until it's good to consume 1445 1446 // construct up-to-date orderbook 1447 1448 // send results to channel 1449 orderbookCh <- ob 1450 } 1451 } 1452 1453 func (c *chainClient) GetTx(ctx context.Context, txHash string) (*txtypes.GetTxResponse, error) { 1454 req := &txtypes.GetTxRequest{ 1455 Hash: txHash, 1456 } 1457 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.txClient.GetTx, req) 1458 1459 return res, err 1460 } 1461 1462 func (c *chainClient) ChainStream(ctx context.Context, req chainstreamtypes.StreamRequest) (chainstreamtypes.Stream_StreamClient, error) { 1463 stream, err := common.ExecuteStreamCall(ctx, c.network.ChainCookieAssistant, c.chainStreamClient.Stream, &req) 1464 1465 if err != nil { 1466 fmt.Println(err) 1467 return nil, err 1468 } 1469 1470 return stream, nil 1471 } 1472 1473 // wasm module 1474 1475 func (c *chainClient) FetchContractInfo(ctx context.Context, address string) (*wasmtypes.QueryContractInfoResponse, error) { 1476 req := &wasmtypes.QueryContractInfoRequest{ 1477 Address: address, 1478 } 1479 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.wasmQueryClient.ContractInfo, req) 1480 1481 return res, err 1482 } 1483 1484 func (c *chainClient) FetchContractHistory(ctx context.Context, address string, pagination *query.PageRequest) (*wasmtypes.QueryContractHistoryResponse, error) { 1485 req := &wasmtypes.QueryContractHistoryRequest{ 1486 Address: address, 1487 Pagination: pagination, 1488 } 1489 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.wasmQueryClient.ContractHistory, req) 1490 1491 return res, err 1492 } 1493 1494 func (c *chainClient) FetchContractsByCode(ctx context.Context, codeId uint64, pagination *query.PageRequest) (*wasmtypes.QueryContractsByCodeResponse, error) { 1495 req := &wasmtypes.QueryContractsByCodeRequest{ 1496 CodeId: codeId, 1497 Pagination: pagination, 1498 } 1499 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.wasmQueryClient.ContractsByCode, req) 1500 1501 return res, err 1502 } 1503 1504 func (c *chainClient) FetchAllContractsState(ctx context.Context, address string, pagination *query.PageRequest) (*wasmtypes.QueryAllContractStateResponse, error) { 1505 req := &wasmtypes.QueryAllContractStateRequest{ 1506 Address: address, 1507 Pagination: pagination, 1508 } 1509 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.wasmQueryClient.AllContractState, req) 1510 1511 return res, err 1512 } 1513 1514 func (c *chainClient) RawContractState( 1515 ctx context.Context, 1516 contractAddress string, 1517 queryData []byte, 1518 ) (*wasmtypes.QueryRawContractStateResponse, error) { 1519 req := &wasmtypes.QueryRawContractStateRequest{ 1520 Address: contractAddress, 1521 QueryData: queryData, 1522 } 1523 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.wasmQueryClient.RawContractState, req) 1524 1525 return res, err 1526 } 1527 1528 func (c *chainClient) SmartContractState( 1529 ctx context.Context, 1530 contractAddress string, 1531 queryData []byte, 1532 ) (*wasmtypes.QuerySmartContractStateResponse, error) { 1533 req := &wasmtypes.QuerySmartContractStateRequest{ 1534 Address: contractAddress, 1535 QueryData: queryData, 1536 } 1537 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.wasmQueryClient.SmartContractState, req) 1538 1539 return res, err 1540 } 1541 1542 func (c *chainClient) FetchCode(ctx context.Context, codeId uint64) (*wasmtypes.QueryCodeResponse, error) { 1543 req := &wasmtypes.QueryCodeRequest{ 1544 CodeId: codeId, 1545 } 1546 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.wasmQueryClient.Code, req) 1547 1548 return res, err 1549 } 1550 1551 func (c *chainClient) FetchCodes(ctx context.Context, pagination *query.PageRequest) (*wasmtypes.QueryCodesResponse, error) { 1552 req := &wasmtypes.QueryCodesRequest{ 1553 Pagination: pagination, 1554 } 1555 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.wasmQueryClient.Codes, req) 1556 1557 return res, err 1558 } 1559 1560 func (c *chainClient) FetchPinnedCodes(ctx context.Context, pagination *query.PageRequest) (*wasmtypes.QueryPinnedCodesResponse, error) { 1561 req := &wasmtypes.QueryPinnedCodesRequest{ 1562 Pagination: pagination, 1563 } 1564 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.wasmQueryClient.PinnedCodes, req) 1565 1566 return res, err 1567 } 1568 1569 func (c *chainClient) FetchContractsByCreator(ctx context.Context, creator string, pagination *query.PageRequest) (*wasmtypes.QueryContractsByCreatorResponse, error) { 1570 req := &wasmtypes.QueryContractsByCreatorRequest{ 1571 CreatorAddress: creator, 1572 Pagination: pagination, 1573 } 1574 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.wasmQueryClient.ContractsByCreator, req) 1575 1576 return res, err 1577 } 1578 1579 // Tokenfactory module 1580 1581 func (c *chainClient) FetchDenomAuthorityMetadata(ctx context.Context, creator, subDenom string) (*tokenfactorytypes.QueryDenomAuthorityMetadataResponse, error) { 1582 req := &tokenfactorytypes.QueryDenomAuthorityMetadataRequest{ 1583 Creator: creator, 1584 } 1585 1586 if subDenom != "" { 1587 req.SubDenom = subDenom 1588 } 1589 1590 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.tokenfactoryQueryClient.DenomAuthorityMetadata, req) 1591 1592 return res, err 1593 } 1594 1595 func (c *chainClient) FetchDenomsFromCreator(ctx context.Context, creator string) (*tokenfactorytypes.QueryDenomsFromCreatorResponse, error) { 1596 req := &tokenfactorytypes.QueryDenomsFromCreatorRequest{ 1597 Creator: creator, 1598 } 1599 1600 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.tokenfactoryQueryClient.DenomsFromCreator, req) 1601 1602 return res, err 1603 } 1604 1605 func (c *chainClient) FetchTokenfactoryModuleState(ctx context.Context) (*tokenfactorytypes.QueryModuleStateResponse, error) { 1606 req := &tokenfactorytypes.QueryModuleStateRequest{} 1607 1608 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.tokenfactoryQueryClient.TokenfactoryModuleState, req) 1609 1610 return res, err 1611 } 1612 1613 type DerivativeOrderData struct { 1614 OrderType exchangetypes.OrderType 1615 Price decimal.Decimal 1616 Quantity decimal.Decimal 1617 Leverage decimal.Decimal 1618 FeeRecipient string 1619 MarketId string 1620 IsReduceOnly bool 1621 Cid string 1622 } 1623 1624 type SpotOrderData struct { 1625 OrderType exchangetypes.OrderType 1626 Price decimal.Decimal 1627 Quantity decimal.Decimal 1628 FeeRecipient string 1629 MarketId string 1630 Cid string 1631 } 1632 1633 type OrderCancelData struct { 1634 MarketId string 1635 OrderHash string 1636 Cid string 1637 } 1638 1639 // Distribution module 1640 func (c *chainClient) FetchValidatorDistributionInfo(ctx context.Context, validatorAddress string) (*distributiontypes.QueryValidatorDistributionInfoResponse, error) { 1641 req := &distributiontypes.QueryValidatorDistributionInfoRequest{ 1642 ValidatorAddress: validatorAddress, 1643 } 1644 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.distributionQueryClient.ValidatorDistributionInfo, req) 1645 1646 return res, err 1647 } 1648 1649 func (c *chainClient) FetchValidatorOutstandingRewards(ctx context.Context, validatorAddress string) (*distributiontypes.QueryValidatorOutstandingRewardsResponse, error) { 1650 req := &distributiontypes.QueryValidatorOutstandingRewardsRequest{ 1651 ValidatorAddress: validatorAddress, 1652 } 1653 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.distributionQueryClient.ValidatorOutstandingRewards, req) 1654 1655 return res, err 1656 } 1657 1658 func (c *chainClient) FetchValidatorCommission(ctx context.Context, validatorAddress string) (*distributiontypes.QueryValidatorCommissionResponse, error) { 1659 req := &distributiontypes.QueryValidatorCommissionRequest{ 1660 ValidatorAddress: validatorAddress, 1661 } 1662 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.distributionQueryClient.ValidatorCommission, req) 1663 1664 return res, err 1665 } 1666 1667 func (c *chainClient) FetchValidatorSlashes(ctx context.Context, validatorAddress string, startingHeight, endingHeight uint64, pagination *query.PageRequest) (*distributiontypes.QueryValidatorSlashesResponse, error) { 1668 req := &distributiontypes.QueryValidatorSlashesRequest{ 1669 ValidatorAddress: validatorAddress, 1670 StartingHeight: startingHeight, 1671 EndingHeight: endingHeight, 1672 Pagination: pagination, 1673 } 1674 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.distributionQueryClient.ValidatorSlashes, req) 1675 1676 return res, err 1677 } 1678 1679 func (c *chainClient) FetchDelegationRewards(ctx context.Context, delegatorAddress, validatorAddress string) (*distributiontypes.QueryDelegationRewardsResponse, error) { 1680 req := &distributiontypes.QueryDelegationRewardsRequest{ 1681 DelegatorAddress: delegatorAddress, 1682 ValidatorAddress: validatorAddress, 1683 } 1684 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.distributionQueryClient.DelegationRewards, req) 1685 1686 return res, err 1687 } 1688 1689 func (c *chainClient) FetchDelegationTotalRewards(ctx context.Context, delegatorAddress string) (*distributiontypes.QueryDelegationTotalRewardsResponse, error) { 1690 req := &distributiontypes.QueryDelegationTotalRewardsRequest{ 1691 DelegatorAddress: delegatorAddress, 1692 } 1693 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.distributionQueryClient.DelegationTotalRewards, req) 1694 1695 return res, err 1696 } 1697 1698 func (c *chainClient) FetchDelegatorValidators(ctx context.Context, delegatorAddress string) (*distributiontypes.QueryDelegatorValidatorsResponse, error) { 1699 req := &distributiontypes.QueryDelegatorValidatorsRequest{ 1700 DelegatorAddress: delegatorAddress, 1701 } 1702 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.distributionQueryClient.DelegatorValidators, req) 1703 1704 return res, err 1705 } 1706 1707 func (c *chainClient) FetchDelegatorWithdrawAddress(ctx context.Context, delegatorAddress string) (*distributiontypes.QueryDelegatorWithdrawAddressResponse, error) { 1708 req := &distributiontypes.QueryDelegatorWithdrawAddressRequest{ 1709 DelegatorAddress: delegatorAddress, 1710 } 1711 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.distributionQueryClient.DelegatorWithdrawAddress, req) 1712 1713 return res, err 1714 } 1715 1716 func (c *chainClient) FetchCommunityPool(ctx context.Context) (*distributiontypes.QueryCommunityPoolResponse, error) { 1717 req := &distributiontypes.QueryCommunityPoolRequest{} 1718 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.distributionQueryClient.CommunityPool, req) 1719 1720 return res, err 1721 } 1722 1723 // Chain exchange module 1724 func (c *chainClient) FetchSubaccountDeposits(ctx context.Context, subaccountId string) (*exchangetypes.QuerySubaccountDepositsResponse, error) { 1725 req := &exchangetypes.QuerySubaccountDepositsRequest{ 1726 SubaccountId: subaccountId, 1727 } 1728 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.SubaccountDeposits, req) 1729 1730 return res, err 1731 } 1732 1733 func (c *chainClient) FetchSubaccountDeposit(ctx context.Context, subaccountId, denom string) (*exchangetypes.QuerySubaccountDepositResponse, error) { 1734 req := &exchangetypes.QuerySubaccountDepositRequest{ 1735 SubaccountId: subaccountId, 1736 Denom: denom, 1737 } 1738 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.SubaccountDeposit, req) 1739 1740 return res, err 1741 } 1742 1743 func (c *chainClient) FetchExchangeBalances(ctx context.Context) (*exchangetypes.QueryExchangeBalancesResponse, error) { 1744 req := &exchangetypes.QueryExchangeBalancesRequest{} 1745 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.ExchangeBalances, req) 1746 1747 return res, err 1748 } 1749 1750 func (c *chainClient) FetchAggregateVolume(ctx context.Context, account string) (*exchangetypes.QueryAggregateVolumeResponse, error) { 1751 req := &exchangetypes.QueryAggregateVolumeRequest{ 1752 Account: account, 1753 } 1754 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.AggregateVolume, req) 1755 1756 return res, err 1757 } 1758 1759 func (c *chainClient) FetchAggregateVolumes(ctx context.Context, accounts, marketIDs []string) (*exchangetypes.QueryAggregateVolumesResponse, error) { 1760 req := &exchangetypes.QueryAggregateVolumesRequest{ 1761 Accounts: accounts, 1762 MarketIds: marketIDs, 1763 } 1764 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.AggregateVolumes, req) 1765 1766 return res, err 1767 } 1768 1769 func (c *chainClient) FetchAggregateMarketVolume(ctx context.Context, marketId string) (*exchangetypes.QueryAggregateMarketVolumeResponse, error) { 1770 req := &exchangetypes.QueryAggregateMarketVolumeRequest{ 1771 MarketId: marketId, 1772 } 1773 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.AggregateMarketVolume, req) 1774 1775 return res, err 1776 } 1777 1778 func (c *chainClient) FetchAggregateMarketVolumes(ctx context.Context, marketIDs []string) (*exchangetypes.QueryAggregateMarketVolumesResponse, error) { 1779 req := &exchangetypes.QueryAggregateMarketVolumesRequest{ 1780 MarketIds: marketIDs, 1781 } 1782 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.AggregateMarketVolumes, req) 1783 1784 return res, err 1785 } 1786 1787 func (c *chainClient) FetchDenomDecimal(ctx context.Context, denom string) (*exchangetypes.QueryDenomDecimalResponse, error) { 1788 req := &exchangetypes.QueryDenomDecimalRequest{ 1789 Denom: denom, 1790 } 1791 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.DenomDecimal, req) 1792 1793 return res, err 1794 } 1795 1796 func (c *chainClient) FetchDenomDecimals(ctx context.Context, denoms []string) (*exchangetypes.QueryDenomDecimalsResponse, error) { 1797 req := &exchangetypes.QueryDenomDecimalsRequest{ 1798 Denoms: denoms, 1799 } 1800 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.DenomDecimals, req) 1801 1802 return res, err 1803 } 1804 1805 func (c *chainClient) FetchChainSpotMarkets(ctx context.Context, status string, marketIDs []string) (*exchangetypes.QuerySpotMarketsResponse, error) { 1806 req := &exchangetypes.QuerySpotMarketsRequest{ 1807 MarketIds: marketIDs, 1808 } 1809 if status != "" { 1810 req.Status = status 1811 } 1812 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.SpotMarkets, req) 1813 1814 return res, err 1815 } 1816 1817 func (c *chainClient) FetchChainSpotMarket(ctx context.Context, marketId string) (*exchangetypes.QuerySpotMarketResponse, error) { 1818 req := &exchangetypes.QuerySpotMarketRequest{ 1819 MarketId: marketId, 1820 } 1821 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.SpotMarket, req) 1822 1823 return res, err 1824 } 1825 1826 func (c *chainClient) FetchChainFullSpotMarkets(ctx context.Context, status string, marketIDs []string, withMidPriceAndTob bool) (*exchangetypes.QueryFullSpotMarketsResponse, error) { 1827 req := &exchangetypes.QueryFullSpotMarketsRequest{ 1828 MarketIds: marketIDs, 1829 WithMidPriceAndTob: withMidPriceAndTob, 1830 } 1831 if status != "" { 1832 req.Status = status 1833 } 1834 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.FullSpotMarkets, req) 1835 1836 return res, err 1837 } 1838 1839 func (c *chainClient) FetchChainFullSpotMarket(ctx context.Context, marketId string, withMidPriceAndTob bool) (*exchangetypes.QueryFullSpotMarketResponse, error) { 1840 req := &exchangetypes.QueryFullSpotMarketRequest{ 1841 MarketId: marketId, 1842 WithMidPriceAndTob: withMidPriceAndTob, 1843 } 1844 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.FullSpotMarket, req) 1845 1846 return res, err 1847 } 1848 1849 func (c *chainClient) FetchChainSpotOrderbook(ctx context.Context, marketId string, limit uint64, orderSide exchangetypes.OrderSide, limitCumulativeNotional, limitCumulativeQuantity sdkmath.LegacyDec) (*exchangetypes.QuerySpotOrderbookResponse, error) { 1850 req := &exchangetypes.QuerySpotOrderbookRequest{ 1851 MarketId: marketId, 1852 Limit: limit, 1853 OrderSide: orderSide, 1854 LimitCumulativeNotional: &limitCumulativeNotional, 1855 LimitCumulativeQuantity: &limitCumulativeQuantity, 1856 } 1857 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.SpotOrderbook, req) 1858 1859 return res, err 1860 } 1861 1862 func (c *chainClient) FetchChainTraderSpotOrders(ctx context.Context, marketId, subaccountId string) (*exchangetypes.QueryTraderSpotOrdersResponse, error) { 1863 req := &exchangetypes.QueryTraderSpotOrdersRequest{ 1864 MarketId: marketId, 1865 SubaccountId: subaccountId, 1866 } 1867 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.TraderSpotOrders, req) 1868 1869 return res, err 1870 } 1871 1872 func (c *chainClient) FetchChainAccountAddressSpotOrders(ctx context.Context, marketId, address string) (*exchangetypes.QueryAccountAddressSpotOrdersResponse, error) { 1873 req := &exchangetypes.QueryAccountAddressSpotOrdersRequest{ 1874 MarketId: marketId, 1875 AccountAddress: address, 1876 } 1877 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.AccountAddressSpotOrders, req) 1878 1879 return res, err 1880 } 1881 1882 func (c *chainClient) FetchChainSpotOrdersByHashes(ctx context.Context, marketId, subaccountId string, orderHashes []string) (*exchangetypes.QuerySpotOrdersByHashesResponse, error) { 1883 req := &exchangetypes.QuerySpotOrdersByHashesRequest{ 1884 MarketId: marketId, 1885 SubaccountId: subaccountId, 1886 OrderHashes: orderHashes, 1887 } 1888 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.SpotOrdersByHashes, req) 1889 1890 return res, err 1891 } 1892 1893 func (c *chainClient) FetchChainSubaccountOrders(ctx context.Context, subaccountId, marketId string) (*exchangetypes.QuerySubaccountOrdersResponse, error) { 1894 req := &exchangetypes.QuerySubaccountOrdersRequest{ 1895 SubaccountId: subaccountId, 1896 MarketId: marketId, 1897 } 1898 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.SubaccountOrders, req) 1899 1900 return res, err 1901 } 1902 1903 func (c *chainClient) FetchChainTraderSpotTransientOrders(ctx context.Context, marketId, subaccountId string) (*exchangetypes.QueryTraderSpotOrdersResponse, error) { 1904 req := &exchangetypes.QueryTraderSpotOrdersRequest{ 1905 MarketId: marketId, 1906 SubaccountId: subaccountId, 1907 } 1908 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.TraderSpotTransientOrders, req) 1909 1910 return res, err 1911 } 1912 1913 func (c *chainClient) FetchSpotMidPriceAndTOB(ctx context.Context, marketId string) (*exchangetypes.QuerySpotMidPriceAndTOBResponse, error) { 1914 req := &exchangetypes.QuerySpotMidPriceAndTOBRequest{ 1915 MarketId: marketId, 1916 } 1917 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.SpotMidPriceAndTOB, req) 1918 1919 return res, err 1920 } 1921 1922 func (c *chainClient) FetchDerivativeMidPriceAndTOB(ctx context.Context, marketId string) (*exchangetypes.QueryDerivativeMidPriceAndTOBResponse, error) { 1923 req := &exchangetypes.QueryDerivativeMidPriceAndTOBRequest{ 1924 MarketId: marketId, 1925 } 1926 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.DerivativeMidPriceAndTOB, req) 1927 1928 return res, err 1929 } 1930 1931 func (c *chainClient) FetchChainDerivativeOrderbook(ctx context.Context, marketId string, limit uint64, limitCumulativeNotional sdkmath.LegacyDec) (*exchangetypes.QueryDerivativeOrderbookResponse, error) { 1932 req := &exchangetypes.QueryDerivativeOrderbookRequest{ 1933 MarketId: marketId, 1934 Limit: limit, 1935 LimitCumulativeNotional: &limitCumulativeNotional, 1936 } 1937 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.DerivativeOrderbook, req) 1938 1939 return res, err 1940 } 1941 1942 func (c *chainClient) FetchChainTraderDerivativeOrders(ctx context.Context, marketId, subaccountId string) (*exchangetypes.QueryTraderDerivativeOrdersResponse, error) { 1943 req := &exchangetypes.QueryTraderDerivativeOrdersRequest{ 1944 MarketId: marketId, 1945 SubaccountId: subaccountId, 1946 } 1947 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.TraderDerivativeOrders, req) 1948 1949 return res, err 1950 } 1951 1952 func (c *chainClient) FetchChainAccountAddressDerivativeOrders(ctx context.Context, marketId, address string) (*exchangetypes.QueryAccountAddressDerivativeOrdersResponse, error) { 1953 req := &exchangetypes.QueryAccountAddressDerivativeOrdersRequest{ 1954 MarketId: marketId, 1955 AccountAddress: address, 1956 } 1957 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.AccountAddressDerivativeOrders, req) 1958 1959 return res, err 1960 } 1961 1962 func (c *chainClient) FetchChainDerivativeOrdersByHashes(ctx context.Context, marketId, subaccountId string, orderHashes []string) (*exchangetypes.QueryDerivativeOrdersByHashesResponse, error) { 1963 req := &exchangetypes.QueryDerivativeOrdersByHashesRequest{ 1964 MarketId: marketId, 1965 SubaccountId: subaccountId, 1966 OrderHashes: orderHashes, 1967 } 1968 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.DerivativeOrdersByHashes, req) 1969 1970 return res, err 1971 } 1972 1973 func (c *chainClient) FetchChainTraderDerivativeTransientOrders(ctx context.Context, marketId, subaccountId string) (*exchangetypes.QueryTraderDerivativeOrdersResponse, error) { 1974 req := &exchangetypes.QueryTraderDerivativeOrdersRequest{ 1975 MarketId: marketId, 1976 SubaccountId: subaccountId, 1977 } 1978 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.TraderDerivativeTransientOrders, req) 1979 1980 return res, err 1981 } 1982 1983 func (c *chainClient) FetchChainDerivativeMarkets(ctx context.Context, status string, marketIDs []string, withMidPriceAndTob bool) (*exchangetypes.QueryDerivativeMarketsResponse, error) { 1984 req := &exchangetypes.QueryDerivativeMarketsRequest{ 1985 MarketIds: marketIDs, 1986 WithMidPriceAndTob: withMidPriceAndTob, 1987 } 1988 if status != "" { 1989 req.Status = status 1990 } 1991 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.DerivativeMarkets, req) 1992 1993 return res, err 1994 } 1995 1996 func (c *chainClient) FetchChainDerivativeMarket(ctx context.Context, marketId string) (*exchangetypes.QueryDerivativeMarketResponse, error) { 1997 req := &exchangetypes.QueryDerivativeMarketRequest{ 1998 MarketId: marketId, 1999 } 2000 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.DerivativeMarket, req) 2001 2002 return res, err 2003 } 2004 2005 func (c *chainClient) FetchDerivativeMarketAddress(ctx context.Context, marketId string) (*exchangetypes.QueryDerivativeMarketAddressResponse, error) { 2006 req := &exchangetypes.QueryDerivativeMarketAddressRequest{ 2007 MarketId: marketId, 2008 } 2009 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.DerivativeMarketAddress, req) 2010 2011 return res, err 2012 } 2013 2014 func (c *chainClient) FetchSubaccountTradeNonce(ctx context.Context, subaccountId string) (*exchangetypes.QuerySubaccountTradeNonceResponse, error) { 2015 req := &exchangetypes.QuerySubaccountTradeNonceRequest{ 2016 SubaccountId: subaccountId, 2017 } 2018 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.SubaccountTradeNonce, req) 2019 2020 return res, err 2021 } 2022 2023 func (c *chainClient) FetchChainPositions(ctx context.Context) (*exchangetypes.QueryPositionsResponse, error) { 2024 req := &exchangetypes.QueryPositionsRequest{} 2025 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.Positions, req) 2026 2027 return res, err 2028 } 2029 2030 func (c *chainClient) FetchChainSubaccountPositions(ctx context.Context, subaccountId string) (*exchangetypes.QuerySubaccountPositionsResponse, error) { 2031 req := &exchangetypes.QuerySubaccountPositionsRequest{ 2032 SubaccountId: subaccountId, 2033 } 2034 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.SubaccountPositions, req) 2035 2036 return res, err 2037 } 2038 2039 func (c *chainClient) FetchChainSubaccountPositionInMarket(ctx context.Context, subaccountId, marketId string) (*exchangetypes.QuerySubaccountPositionInMarketResponse, error) { 2040 req := &exchangetypes.QuerySubaccountPositionInMarketRequest{ 2041 SubaccountId: subaccountId, 2042 MarketId: marketId, 2043 } 2044 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.SubaccountPositionInMarket, req) 2045 2046 return res, err 2047 } 2048 2049 func (c *chainClient) FetchChainSubaccountEffectivePositionInMarket(ctx context.Context, subaccountId, marketId string) (*exchangetypes.QuerySubaccountEffectivePositionInMarketResponse, error) { 2050 req := &exchangetypes.QuerySubaccountEffectivePositionInMarketRequest{ 2051 SubaccountId: subaccountId, 2052 MarketId: marketId, 2053 } 2054 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.SubaccountEffectivePositionInMarket, req) 2055 2056 return res, err 2057 } 2058 2059 func (c *chainClient) FetchChainPerpetualMarketInfo(ctx context.Context, marketId string) (*exchangetypes.QueryPerpetualMarketInfoResponse, error) { 2060 req := &exchangetypes.QueryPerpetualMarketInfoRequest{ 2061 MarketId: marketId, 2062 } 2063 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.PerpetualMarketInfo, req) 2064 2065 return res, err 2066 } 2067 2068 func (c *chainClient) FetchChainExpiryFuturesMarketInfo(ctx context.Context, marketId string) (*exchangetypes.QueryExpiryFuturesMarketInfoResponse, error) { 2069 req := &exchangetypes.QueryExpiryFuturesMarketInfoRequest{ 2070 MarketId: marketId, 2071 } 2072 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.ExpiryFuturesMarketInfo, req) 2073 2074 return res, err 2075 } 2076 2077 func (c *chainClient) FetchChainPerpetualMarketFunding(ctx context.Context, marketId string) (*exchangetypes.QueryPerpetualMarketFundingResponse, error) { 2078 req := &exchangetypes.QueryPerpetualMarketFundingRequest{ 2079 MarketId: marketId, 2080 } 2081 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.PerpetualMarketFunding, req) 2082 2083 return res, err 2084 } 2085 2086 func (c *chainClient) FetchSubaccountOrderMetadata(ctx context.Context, subaccountId string) (*exchangetypes.QuerySubaccountOrderMetadataResponse, error) { 2087 req := &exchangetypes.QuerySubaccountOrderMetadataRequest{ 2088 SubaccountId: subaccountId, 2089 } 2090 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.SubaccountOrderMetadata, req) 2091 2092 return res, err 2093 } 2094 2095 func (c *chainClient) FetchTradeRewardPoints(ctx context.Context, accounts []string) (*exchangetypes.QueryTradeRewardPointsResponse, error) { 2096 req := &exchangetypes.QueryTradeRewardPointsRequest{ 2097 Accounts: accounts, 2098 } 2099 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.TradeRewardPoints, req) 2100 2101 return res, err 2102 } 2103 2104 func (c *chainClient) FetchPendingTradeRewardPoints(ctx context.Context, accounts []string) (*exchangetypes.QueryTradeRewardPointsResponse, error) { 2105 req := &exchangetypes.QueryTradeRewardPointsRequest{ 2106 Accounts: accounts, 2107 } 2108 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.PendingTradeRewardPoints, req) 2109 2110 return res, err 2111 } 2112 2113 func (c *chainClient) FetchTradeRewardCampaign(ctx context.Context) (*exchangetypes.QueryTradeRewardCampaignResponse, error) { 2114 req := &exchangetypes.QueryTradeRewardCampaignRequest{} 2115 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.TradeRewardCampaign, req) 2116 2117 return res, err 2118 } 2119 2120 func (c *chainClient) FetchFeeDiscountAccountInfo(ctx context.Context, account string) (*exchangetypes.QueryFeeDiscountAccountInfoResponse, error) { 2121 req := &exchangetypes.QueryFeeDiscountAccountInfoRequest{ 2122 Account: account, 2123 } 2124 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.FeeDiscountAccountInfo, req) 2125 2126 return res, err 2127 } 2128 2129 func (c *chainClient) FetchFeeDiscountSchedule(ctx context.Context) (*exchangetypes.QueryFeeDiscountScheduleResponse, error) { 2130 req := &exchangetypes.QueryFeeDiscountScheduleRequest{} 2131 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.FeeDiscountSchedule, req) 2132 2133 return res, err 2134 } 2135 2136 func (c *chainClient) FetchBalanceMismatches(ctx context.Context, dustFactor int64) (*exchangetypes.QueryBalanceMismatchesResponse, error) { 2137 req := &exchangetypes.QueryBalanceMismatchesRequest{ 2138 DustFactor: dustFactor, 2139 } 2140 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.BalanceMismatches, req) 2141 2142 return res, err 2143 } 2144 2145 func (c *chainClient) FetchBalanceWithBalanceHolds(ctx context.Context) (*exchangetypes.QueryBalanceWithBalanceHoldsResponse, error) { 2146 req := &exchangetypes.QueryBalanceWithBalanceHoldsRequest{} 2147 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.BalanceWithBalanceHolds, req) 2148 2149 return res, err 2150 } 2151 2152 func (c *chainClient) FetchFeeDiscountTierStatistics(ctx context.Context) (*exchangetypes.QueryFeeDiscountTierStatisticsResponse, error) { 2153 req := &exchangetypes.QueryFeeDiscountTierStatisticsRequest{} 2154 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.FeeDiscountTierStatistics, req) 2155 2156 return res, err 2157 } 2158 2159 func (c *chainClient) FetchMitoVaultInfos(ctx context.Context) (*exchangetypes.MitoVaultInfosResponse, error) { 2160 req := &exchangetypes.MitoVaultInfosRequest{} 2161 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.MitoVaultInfos, req) 2162 2163 return res, err 2164 } 2165 2166 func (c *chainClient) FetchMarketIDFromVault(ctx context.Context, vaultAddress string) (*exchangetypes.QueryMarketIDFromVaultResponse, error) { 2167 req := &exchangetypes.QueryMarketIDFromVaultRequest{ 2168 VaultAddress: vaultAddress, 2169 } 2170 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.QueryMarketIDFromVault, req) 2171 2172 return res, err 2173 } 2174 2175 func (c *chainClient) FetchHistoricalTradeRecords(ctx context.Context, marketId string) (*exchangetypes.QueryHistoricalTradeRecordsResponse, error) { 2176 req := &exchangetypes.QueryHistoricalTradeRecordsRequest{ 2177 MarketId: marketId, 2178 } 2179 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.HistoricalTradeRecords, req) 2180 2181 return res, err 2182 } 2183 2184 func (c *chainClient) FetchIsOptedOutOfRewards(ctx context.Context, account string) (*exchangetypes.QueryIsOptedOutOfRewardsResponse, error) { 2185 req := &exchangetypes.QueryIsOptedOutOfRewardsRequest{ 2186 Account: account, 2187 } 2188 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.IsOptedOutOfRewards, req) 2189 2190 return res, err 2191 } 2192 2193 func (c *chainClient) FetchOptedOutOfRewardsAccounts(ctx context.Context) (*exchangetypes.QueryOptedOutOfRewardsAccountsResponse, error) { 2194 req := &exchangetypes.QueryOptedOutOfRewardsAccountsRequest{} 2195 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.OptedOutOfRewardsAccounts, req) 2196 2197 return res, err 2198 } 2199 2200 func (c *chainClient) FetchMarketVolatility(ctx context.Context, marketId string, tradeHistoryOptions *exchangetypes.TradeHistoryOptions) (*exchangetypes.QueryMarketVolatilityResponse, error) { 2201 req := &exchangetypes.QueryMarketVolatilityRequest{ 2202 MarketId: marketId, 2203 TradeHistoryOptions: tradeHistoryOptions, 2204 } 2205 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.MarketVolatility, req) 2206 2207 return res, err 2208 } 2209 2210 func (c *chainClient) FetchChainBinaryOptionsMarkets(ctx context.Context, status string) (*exchangetypes.QueryBinaryMarketsResponse, error) { 2211 req := &exchangetypes.QueryBinaryMarketsRequest{} 2212 if status != "" { 2213 req.Status = status 2214 } 2215 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.BinaryOptionsMarkets, req) 2216 2217 return res, err 2218 } 2219 2220 func (c *chainClient) FetchTraderDerivativeConditionalOrders(ctx context.Context, subaccountId, marketId string) (*exchangetypes.QueryTraderDerivativeConditionalOrdersResponse, error) { 2221 req := &exchangetypes.QueryTraderDerivativeConditionalOrdersRequest{ 2222 SubaccountId: subaccountId, 2223 MarketId: marketId, 2224 } 2225 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.TraderDerivativeConditionalOrders, req) 2226 2227 return res, err 2228 } 2229 2230 func (c *chainClient) FetchMarketAtomicExecutionFeeMultiplier(ctx context.Context, marketId string) (*exchangetypes.QueryMarketAtomicExecutionFeeMultiplierResponse, error) { 2231 req := &exchangetypes.QueryMarketAtomicExecutionFeeMultiplierRequest{ 2232 MarketId: marketId, 2233 } 2234 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.exchangeQueryClient.MarketAtomicExecutionFeeMultiplier, req) 2235 2236 return res, err 2237 } 2238 2239 // Tendermint module 2240 2241 func (c *chainClient) FetchNodeInfo(ctx context.Context) (*cmtservice.GetNodeInfoResponse, error) { 2242 req := &cmtservice.GetNodeInfoRequest{} 2243 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.tendermintQueryClient.GetNodeInfo, req) 2244 2245 return res, err 2246 } 2247 2248 func (c *chainClient) FetchSyncing(ctx context.Context) (*cmtservice.GetSyncingResponse, error) { 2249 req := &cmtservice.GetSyncingRequest{} 2250 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.tendermintQueryClient.GetSyncing, req) 2251 2252 return res, err 2253 } 2254 2255 func (c *chainClient) FetchLatestBlock(ctx context.Context) (*cmtservice.GetLatestBlockResponse, error) { 2256 req := &cmtservice.GetLatestBlockRequest{} 2257 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.tendermintQueryClient.GetLatestBlock, req) 2258 2259 return res, err 2260 } 2261 2262 func (c *chainClient) FetchBlockByHeight(ctx context.Context, height int64) (*cmtservice.GetBlockByHeightResponse, error) { 2263 req := &cmtservice.GetBlockByHeightRequest{ 2264 Height: height, 2265 } 2266 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.tendermintQueryClient.GetBlockByHeight, req) 2267 2268 return res, err 2269 } 2270 2271 func (c *chainClient) FetchLatestValidatorSet(ctx context.Context) (*cmtservice.GetLatestValidatorSetResponse, error) { 2272 req := &cmtservice.GetLatestValidatorSetRequest{} 2273 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.tendermintQueryClient.GetLatestValidatorSet, req) 2274 2275 return res, err 2276 } 2277 2278 func (c *chainClient) FetchValidatorSetByHeight(ctx context.Context, height int64, pagination *query.PageRequest) (*cmtservice.GetValidatorSetByHeightResponse, error) { 2279 req := &cmtservice.GetValidatorSetByHeightRequest{ 2280 Height: height, 2281 Pagination: pagination, 2282 } 2283 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.tendermintQueryClient.GetValidatorSetByHeight, req) 2284 2285 return res, err 2286 } 2287 2288 func (c *chainClient) ABCIQuery(ctx context.Context, path string, data []byte, height int64, prove bool) (*cmtservice.ABCIQueryResponse, error) { 2289 req := &cmtservice.ABCIQueryRequest{ 2290 Path: path, 2291 Data: data, 2292 Height: height, 2293 Prove: prove, 2294 } 2295 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.tendermintQueryClient.ABCIQuery, req) 2296 2297 return res, err 2298 } 2299 2300 // IBC Transfer module 2301 func (c *chainClient) FetchDenomTrace(ctx context.Context, hash string) (*ibctransfertypes.QueryDenomTraceResponse, error) { 2302 req := &ibctransfertypes.QueryDenomTraceRequest{ 2303 Hash: hash, 2304 } 2305 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcTransferQueryClient.DenomTrace, req) 2306 2307 return res, err 2308 } 2309 2310 func (c *chainClient) FetchDenomTraces(ctx context.Context, pagination *query.PageRequest) (*ibctransfertypes.QueryDenomTracesResponse, error) { 2311 req := &ibctransfertypes.QueryDenomTracesRequest{ 2312 Pagination: pagination, 2313 } 2314 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcTransferQueryClient.DenomTraces, req) 2315 2316 return res, err 2317 } 2318 2319 func (c *chainClient) FetchDenomHash(ctx context.Context, trace string) (*ibctransfertypes.QueryDenomHashResponse, error) { 2320 req := &ibctransfertypes.QueryDenomHashRequest{ 2321 Trace: trace, 2322 } 2323 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcTransferQueryClient.DenomHash, req) 2324 2325 return res, err 2326 } 2327 2328 func (c *chainClient) FetchEscrowAddress(ctx context.Context, portId, channelId string) (*ibctransfertypes.QueryEscrowAddressResponse, error) { 2329 req := &ibctransfertypes.QueryEscrowAddressRequest{ 2330 PortId: portId, 2331 ChannelId: channelId, 2332 } 2333 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcTransferQueryClient.EscrowAddress, req) 2334 2335 return res, err 2336 } 2337 2338 func (c *chainClient) FetchTotalEscrowForDenom(ctx context.Context, denom string) (*ibctransfertypes.QueryTotalEscrowForDenomResponse, error) { 2339 req := &ibctransfertypes.QueryTotalEscrowForDenomRequest{ 2340 Denom: denom, 2341 } 2342 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcTransferQueryClient.TotalEscrowForDenom, req) 2343 2344 return res, err 2345 } 2346 2347 // IBC Core Channel module 2348 func (c *chainClient) FetchIBCChannel(ctx context.Context, portId, channelId string) (*ibcchanneltypes.QueryChannelResponse, error) { 2349 req := &ibcchanneltypes.QueryChannelRequest{ 2350 PortId: portId, 2351 ChannelId: channelId, 2352 } 2353 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcChannelQueryClient.Channel, req) 2354 2355 return res, err 2356 } 2357 2358 func (c *chainClient) FetchIBCChannels(ctx context.Context, pagination *query.PageRequest) (*ibcchanneltypes.QueryChannelsResponse, error) { 2359 req := &ibcchanneltypes.QueryChannelsRequest{ 2360 Pagination: pagination, 2361 } 2362 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcChannelQueryClient.Channels, req) 2363 2364 return res, err 2365 } 2366 2367 func (c *chainClient) FetchIBCConnectionChannels(ctx context.Context, connection string, pagination *query.PageRequest) (*ibcchanneltypes.QueryConnectionChannelsResponse, error) { 2368 req := &ibcchanneltypes.QueryConnectionChannelsRequest{ 2369 Connection: connection, 2370 Pagination: pagination, 2371 } 2372 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcChannelQueryClient.ConnectionChannels, req) 2373 2374 return res, err 2375 } 2376 2377 func (c *chainClient) FetchIBCChannelClientState(ctx context.Context, portId, channelId string) (*ibcchanneltypes.QueryChannelClientStateResponse, error) { 2378 req := &ibcchanneltypes.QueryChannelClientStateRequest{ 2379 PortId: portId, 2380 ChannelId: channelId, 2381 } 2382 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcChannelQueryClient.ChannelClientState, req) 2383 2384 return res, err 2385 } 2386 2387 func (c *chainClient) FetchIBCChannelConsensusState(ctx context.Context, portId, channelId string, revisionNumber, revisionHeight uint64) (*ibcchanneltypes.QueryChannelConsensusStateResponse, error) { 2388 req := &ibcchanneltypes.QueryChannelConsensusStateRequest{ 2389 PortId: portId, 2390 ChannelId: channelId, 2391 RevisionNumber: revisionNumber, 2392 RevisionHeight: revisionHeight, 2393 } 2394 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcChannelQueryClient.ChannelConsensusState, req) 2395 2396 return res, err 2397 } 2398 2399 func (c *chainClient) FetchIBCPacketCommitment(ctx context.Context, portId, channelId string, sequence uint64) (*ibcchanneltypes.QueryPacketCommitmentResponse, error) { 2400 req := &ibcchanneltypes.QueryPacketCommitmentRequest{ 2401 PortId: portId, 2402 ChannelId: channelId, 2403 Sequence: sequence, 2404 } 2405 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcChannelQueryClient.PacketCommitment, req) 2406 2407 return res, err 2408 } 2409 2410 func (c *chainClient) FetchIBCPacketCommitments(ctx context.Context, portId, channelId string, pagination *query.PageRequest) (*ibcchanneltypes.QueryPacketCommitmentsResponse, error) { 2411 req := &ibcchanneltypes.QueryPacketCommitmentsRequest{ 2412 PortId: portId, 2413 ChannelId: channelId, 2414 Pagination: pagination, 2415 } 2416 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcChannelQueryClient.PacketCommitments, req) 2417 2418 return res, err 2419 } 2420 2421 func (c *chainClient) FetchIBCPacketReceipt(ctx context.Context, portId, channelId string, sequence uint64) (*ibcchanneltypes.QueryPacketReceiptResponse, error) { 2422 req := &ibcchanneltypes.QueryPacketReceiptRequest{ 2423 PortId: portId, 2424 ChannelId: channelId, 2425 Sequence: sequence, 2426 } 2427 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcChannelQueryClient.PacketReceipt, req) 2428 2429 return res, err 2430 } 2431 2432 func (c *chainClient) FetchIBCPacketAcknowledgement(ctx context.Context, portId, channelId string, sequence uint64) (*ibcchanneltypes.QueryPacketAcknowledgementResponse, error) { 2433 req := &ibcchanneltypes.QueryPacketAcknowledgementRequest{ 2434 PortId: portId, 2435 ChannelId: channelId, 2436 Sequence: sequence, 2437 } 2438 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcChannelQueryClient.PacketAcknowledgement, req) 2439 2440 return res, err 2441 } 2442 2443 func (c *chainClient) FetchIBCPacketAcknowledgements(ctx context.Context, portId, channelId string, packetCommitmentSequences []uint64, pagination *query.PageRequest) (*ibcchanneltypes.QueryPacketAcknowledgementsResponse, error) { 2444 req := &ibcchanneltypes.QueryPacketAcknowledgementsRequest{ 2445 PortId: portId, 2446 ChannelId: channelId, 2447 Pagination: pagination, 2448 PacketCommitmentSequences: packetCommitmentSequences, 2449 } 2450 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcChannelQueryClient.PacketAcknowledgements, req) 2451 2452 return res, err 2453 } 2454 2455 func (c *chainClient) FetchIBCUnreceivedPackets(ctx context.Context, portId, channelId string, packetCommitmentSequences []uint64) (*ibcchanneltypes.QueryUnreceivedPacketsResponse, error) { 2456 req := &ibcchanneltypes.QueryUnreceivedPacketsRequest{ 2457 PortId: portId, 2458 ChannelId: channelId, 2459 PacketCommitmentSequences: packetCommitmentSequences, 2460 } 2461 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcChannelQueryClient.UnreceivedPackets, req) 2462 2463 return res, err 2464 } 2465 2466 func (c *chainClient) FetchIBCUnreceivedAcks(ctx context.Context, portId, channelId string, packetAckSequences []uint64) (*ibcchanneltypes.QueryUnreceivedAcksResponse, error) { 2467 req := &ibcchanneltypes.QueryUnreceivedAcksRequest{ 2468 PortId: portId, 2469 ChannelId: channelId, 2470 PacketAckSequences: packetAckSequences, 2471 } 2472 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcChannelQueryClient.UnreceivedAcks, req) 2473 2474 return res, err 2475 } 2476 2477 func (c *chainClient) FetchIBCNextSequenceReceive(ctx context.Context, portId, channelId string) (*ibcchanneltypes.QueryNextSequenceReceiveResponse, error) { 2478 req := &ibcchanneltypes.QueryNextSequenceReceiveRequest{ 2479 PortId: portId, 2480 ChannelId: channelId, 2481 } 2482 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcChannelQueryClient.NextSequenceReceive, req) 2483 2484 return res, err 2485 } 2486 2487 // IBC Core Chain module 2488 func (c *chainClient) FetchIBCClientState(ctx context.Context, clientId string) (*ibcclienttypes.QueryClientStateResponse, error) { 2489 req := &ibcclienttypes.QueryClientStateRequest{ 2490 ClientId: clientId, 2491 } 2492 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcClientQueryClient.ClientState, req) 2493 2494 return res, err 2495 } 2496 2497 func (c *chainClient) FetchIBCClientStates(ctx context.Context, pagination *query.PageRequest) (*ibcclienttypes.QueryClientStatesResponse, error) { 2498 req := &ibcclienttypes.QueryClientStatesRequest{ 2499 Pagination: pagination, 2500 } 2501 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcClientQueryClient.ClientStates, req) 2502 2503 return res, err 2504 } 2505 2506 func (c *chainClient) FetchIBCConsensusState(ctx context.Context, clientId string, revisionNumber, revisionHeight uint64, latestHeight bool) (*ibcclienttypes.QueryConsensusStateResponse, error) { 2507 req := &ibcclienttypes.QueryConsensusStateRequest{ 2508 ClientId: clientId, 2509 RevisionNumber: revisionNumber, 2510 RevisionHeight: revisionHeight, 2511 LatestHeight: latestHeight, 2512 } 2513 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcClientQueryClient.ConsensusState, req) 2514 2515 return res, err 2516 } 2517 2518 func (c *chainClient) FetchIBCConsensusStates(ctx context.Context, clientId string, pagination *query.PageRequest) (*ibcclienttypes.QueryConsensusStatesResponse, error) { 2519 req := &ibcclienttypes.QueryConsensusStatesRequest{ 2520 ClientId: clientId, 2521 Pagination: pagination, 2522 } 2523 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcClientQueryClient.ConsensusStates, req) 2524 2525 return res, err 2526 } 2527 2528 func (c *chainClient) FetchIBCConsensusStateHeights(ctx context.Context, clientId string, pagination *query.PageRequest) (*ibcclienttypes.QueryConsensusStateHeightsResponse, error) { 2529 req := &ibcclienttypes.QueryConsensusStateHeightsRequest{ 2530 ClientId: clientId, 2531 Pagination: pagination, 2532 } 2533 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcClientQueryClient.ConsensusStateHeights, req) 2534 2535 return res, err 2536 } 2537 2538 func (c *chainClient) FetchIBCClientStatus(ctx context.Context, clientId string) (*ibcclienttypes.QueryClientStatusResponse, error) { 2539 req := &ibcclienttypes.QueryClientStatusRequest{ 2540 ClientId: clientId, 2541 } 2542 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcClientQueryClient.ClientStatus, req) 2543 2544 return res, err 2545 } 2546 2547 func (c *chainClient) FetchIBCClientParams(ctx context.Context) (*ibcclienttypes.QueryClientParamsResponse, error) { 2548 req := &ibcclienttypes.QueryClientParamsRequest{} 2549 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcClientQueryClient.ClientParams, req) 2550 2551 return res, err 2552 } 2553 2554 func (c *chainClient) FetchIBCUpgradedClientState(ctx context.Context) (*ibcclienttypes.QueryUpgradedClientStateResponse, error) { 2555 req := &ibcclienttypes.QueryUpgradedClientStateRequest{} 2556 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcClientQueryClient.UpgradedClientState, req) 2557 2558 return res, err 2559 } 2560 2561 func (c *chainClient) FetchIBCUpgradedConsensusState(ctx context.Context) (*ibcclienttypes.QueryUpgradedConsensusStateResponse, error) { 2562 req := &ibcclienttypes.QueryUpgradedConsensusStateRequest{} 2563 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcClientQueryClient.UpgradedConsensusState, req) 2564 2565 return res, err 2566 } 2567 2568 // IBC Core Connection module 2569 func (c *chainClient) FetchIBCConnection(ctx context.Context, connectionId string) (*ibcconnectiontypes.QueryConnectionResponse, error) { 2570 req := &ibcconnectiontypes.QueryConnectionRequest{ 2571 ConnectionId: connectionId, 2572 } 2573 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcConnectionQueryClient.Connection, req) 2574 2575 return res, err 2576 } 2577 2578 func (c *chainClient) FetchIBCConnections(ctx context.Context, pagination *query.PageRequest) (*ibcconnectiontypes.QueryConnectionsResponse, error) { 2579 req := &ibcconnectiontypes.QueryConnectionsRequest{ 2580 Pagination: pagination, 2581 } 2582 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcConnectionQueryClient.Connections, req) 2583 2584 return res, err 2585 } 2586 2587 func (c *chainClient) FetchIBCClientConnections(ctx context.Context, clientId string) (*ibcconnectiontypes.QueryClientConnectionsResponse, error) { 2588 req := &ibcconnectiontypes.QueryClientConnectionsRequest{ 2589 ClientId: clientId, 2590 } 2591 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcConnectionQueryClient.ClientConnections, req) 2592 2593 return res, err 2594 } 2595 2596 func (c *chainClient) FetchIBCConnectionClientState(ctx context.Context, connectionId string) (*ibcconnectiontypes.QueryConnectionClientStateResponse, error) { 2597 req := &ibcconnectiontypes.QueryConnectionClientStateRequest{ 2598 ConnectionId: connectionId, 2599 } 2600 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcConnectionQueryClient.ConnectionClientState, req) 2601 2602 return res, err 2603 } 2604 2605 func (c *chainClient) FetchIBCConnectionConsensusState(ctx context.Context, connectionId string, revisionNumber, revisionHeight uint64) (*ibcconnectiontypes.QueryConnectionConsensusStateResponse, error) { 2606 req := &ibcconnectiontypes.QueryConnectionConsensusStateRequest{ 2607 ConnectionId: connectionId, 2608 RevisionNumber: revisionNumber, 2609 RevisionHeight: revisionHeight, 2610 } 2611 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcConnectionQueryClient.ConnectionConsensusState, req) 2612 2613 return res, err 2614 } 2615 2616 func (c *chainClient) FetchIBCConnectionParams(ctx context.Context) (*ibcconnectiontypes.QueryConnectionParamsResponse, error) { 2617 req := &ibcconnectiontypes.QueryConnectionParamsRequest{} 2618 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.ibcConnectionQueryClient.ConnectionParams, req) 2619 2620 return res, err 2621 } 2622 2623 // Permissions module 2624 2625 func (c *chainClient) FetchAllNamespaces(ctx context.Context) (*permissionstypes.QueryAllNamespacesResponse, error) { 2626 req := &permissionstypes.QueryAllNamespacesRequest{} 2627 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.permissionsQueryClient.AllNamespaces, req) 2628 2629 return res, err 2630 } 2631 2632 func (c *chainClient) FetchNamespaceByDenom(ctx context.Context, denom string, includeRoles bool) (*permissionstypes.QueryNamespaceByDenomResponse, error) { 2633 req := &permissionstypes.QueryNamespaceByDenomRequest{ 2634 Denom: denom, 2635 IncludeRoles: includeRoles, 2636 } 2637 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.permissionsQueryClient.NamespaceByDenom, req) 2638 2639 return res, err 2640 } 2641 2642 func (c *chainClient) FetchAddressRoles(ctx context.Context, denom, address string) (*permissionstypes.QueryAddressRolesResponse, error) { 2643 req := &permissionstypes.QueryAddressRolesRequest{ 2644 Denom: denom, 2645 Address: address, 2646 } 2647 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.permissionsQueryClient.AddressRoles, req) 2648 2649 return res, err 2650 } 2651 2652 func (c *chainClient) FetchAddressesByRole(ctx context.Context, denom, role string) (*permissionstypes.QueryAddressesByRoleResponse, error) { 2653 req := &permissionstypes.QueryAddressesByRoleRequest{ 2654 Denom: denom, 2655 Role: role, 2656 } 2657 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.permissionsQueryClient.AddressesByRole, req) 2658 2659 return res, err 2660 } 2661 2662 func (c *chainClient) FetchVouchersForAddress(ctx context.Context, address string) (*permissionstypes.QueryVouchersForAddressResponse, error) { 2663 req := &permissionstypes.QueryVouchersForAddressRequest{ 2664 Address: address, 2665 } 2666 res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.permissionsQueryClient.VouchersForAddress, req) 2667 2668 return res, err 2669 }