From 2a8ab24b4a24a8dc4f5e5472c861dc55aa731af4 Mon Sep 17 00:00:00 2001 From: Tony Stark Date: Wed, 22 Jan 2025 07:12:41 +0530 Subject: [PATCH] feat: add node client for interacting with nodes --- client/auth.go | 4 +- client/client.go | 125 ++++++++++++++++++++++++----------------- client/key.go | 12 ++-- client/lease.go | 8 +-- client/node.go | 104 ++++++++++++++++++++++++---------- client/plan.go | 6 +- client/provider.go | 4 +- client/query.go | 10 ++-- client/session.go | 12 ++-- client/subscription.go | 12 ++-- client/tx.go | 14 ++--- cmd/keys.go | 10 ++-- 12 files changed, 194 insertions(+), 127 deletions(-) diff --git a/client/auth.go b/client/auth.go index cebcc28..0719a3d 100644 --- a/client/auth.go +++ b/client/auth.go @@ -16,7 +16,7 @@ const ( // Account retrieves an account by its address using a gRPC query. // Returns the account interface and any potential error encountered. -func (c *Client) Account(ctx context.Context, accAddr cosmossdk.AccAddress) (res auth.AccountI, err error) { +func (c *BaseClient) Account(ctx context.Context, accAddr cosmossdk.AccAddress) (res auth.AccountI, err error) { var ( resp auth.QueryAccountResponse req = &auth.QueryAccountRequest{Address: accAddr.String()} @@ -37,7 +37,7 @@ func (c *Client) Account(ctx context.Context, accAddr cosmossdk.AccAddress) (res // Accounts retrieves a list of accounts with pagination support using a gRPC query. // Returns a slice of account interfaces, pagination details, and any potential error. -func (c *Client) Accounts(ctx context.Context, pageReq *query.PageRequest) (res []auth.AccountI, pageRes *query.PageResponse, err error) { +func (c *BaseClient) Accounts(ctx context.Context, pageReq *query.PageRequest) (res []auth.AccountI, pageRes *query.PageResponse, err error) { var ( resp auth.QueryAccountsResponse req = &auth.QueryAccountsRequest{Pagination: pageReq} diff --git a/client/client.go b/client/client.go index 3e3c38b..4dba6f9 100644 --- a/client/client.go +++ b/client/client.go @@ -7,17 +7,12 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/cosmos/cosmos-sdk/types" + cosmossdk "github.com/cosmos/cosmos-sdk/types" + "github.com/sentinel-official/hub/v12/types" ) -// contextKey is a custom type used as a key to store the Client struct in a context. -type contextKey byte - -// ContextKey is the constant key value used for storing and retrieving the Client struct from a context. -const ContextKey contextKey = 0 - -// Client contains all necessary components for transaction handling, query management, and configuration settings. -type Client struct { +// BaseClient contains all necessary components for transaction handling, query management, and configuration settings. +type BaseClient struct { chainID string // The chain ID used to identify the blockchain network keyring keyring.Keyring // Keyring for managing private keys and signatures protoCodec codec.ProtoCodecMarshaler // Used for marshaling and unmarshaling protobuf data @@ -28,133 +23,159 @@ type Client struct { rpcAddr string // RPC server address rpcTimeout time.Duration // RPC timeout duration txConfig client.TxConfig // Configuration related to transactions (e.g., signing modes) - txFeeGranterAddr types.AccAddress // Address that grants transaction fees - txFees types.Coins // Fees for transactions + txFeeGranterAddr cosmossdk.AccAddress // Address that grants transaction fees + txFees cosmossdk.Coins // Fees for transactions txFromName string // Sender name for transactions txGasAdjustment float64 // Adjustment factor for gas estimation - txGasPrices types.DecCoins // Gas price settings for transactions + txGasPrices cosmossdk.DecCoins // Gas price settings for transactions txGas uint64 // Gas limit for transactions txMemo string // Memo attached to transactions txSimulateAndExecute bool // Flag for simulating and executing transactions txTimeoutHeight uint64 // Transaction timeout height } -// New initializes a new Client instance. -func New() *Client { - return &Client{} +// NewBaseClient initializes a new BaseClient instance. +func NewBaseClient() *BaseClient { + return &BaseClient{} } -// WithChainID sets the blockchain chain ID and returns the updated Client. -func (c *Client) WithChainID(chainID string) *Client { +// WithChainID sets the blockchain chain ID and returns the updated BaseClient. +func (c *BaseClient) WithChainID(chainID string) *BaseClient { c.chainID = chainID return c } -// WithKeyring assigns the keyring to the Client and returns the updated Client. -func (c *Client) WithKeyring(keyring keyring.Keyring) *Client { +// WithKeyring assigns the keyring to the BaseClient and returns the updated BaseClient. +func (c *BaseClient) WithKeyring(keyring keyring.Keyring) *BaseClient { c.keyring = keyring return c } -// WithProtoCodec sets the protobuf codec and returns the updated Client. -func (c *Client) WithProtoCodec(protoCodec codec.ProtoCodecMarshaler) *Client { +// WithProtoCodec sets the protobuf codec and returns the updated BaseClient. +func (c *BaseClient) WithProtoCodec(protoCodec codec.ProtoCodecMarshaler) *BaseClient { c.protoCodec = protoCodec return c } -// WithQueryProve sets the prove flag for queries and returns the updated Client. -func (c *Client) WithQueryProve(prove bool) *Client { +// WithQueryProve sets the prove flag for queries and returns the updated BaseClient. +func (c *BaseClient) WithQueryProve(prove bool) *BaseClient { c.queryProve = prove return c } -// WithQueryRetries sets the number of retries for queries and returns the updated Client. -func (c *Client) WithQueryRetries(retries uint) *Client { +// WithQueryRetries sets the number of retries for queries and returns the updated BaseClient. +func (c *BaseClient) WithQueryRetries(retries uint) *BaseClient { c.queryRetries = retries return c } -// WithQueryRetryDelay sets the retry delay duration for queries and returns the updated Client. -func (c *Client) WithQueryRetryDelay(delay time.Duration) *Client { +// WithQueryRetryDelay sets the retry delay duration for queries and returns the updated BaseClient. +func (c *BaseClient) WithQueryRetryDelay(delay time.Duration) *BaseClient { c.queryRetryDelay = delay return c } -// WithRPCAddr sets the RPC server address and returns the updated Client. -func (c *Client) WithRPCAddr(rpcAddr string) *Client { +// WithRPCAddr sets the RPC server address and returns the updated BaseClient. +func (c *BaseClient) WithRPCAddr(rpcAddr string) *BaseClient { c.rpcAddr = rpcAddr return c } -// WithRPCTimeout sets the RPC timeout duration and returns the updated Client. -func (c *Client) WithRPCTimeout(timeout time.Duration) *Client { +// WithRPCTimeout sets the RPC timeout duration and returns the updated BaseClient. +func (c *BaseClient) WithRPCTimeout(timeout time.Duration) *BaseClient { c.rpcTimeout = timeout return c } -// WithTxConfig sets the transaction configuration and returns the updated Client. -func (c *Client) WithTxConfig(txConfig client.TxConfig) *Client { +// WithTxConfig sets the transaction configuration and returns the updated BaseClient. +func (c *BaseClient) WithTxConfig(txConfig client.TxConfig) *BaseClient { c.txConfig = txConfig return c } -// WithTxFeeGranterAddr sets the transaction fee granter address and returns the updated Client. -func (c *Client) WithTxFeeGranterAddr(addr types.AccAddress) *Client { +// WithTxFeeGranterAddr sets the transaction fee granter address and returns the updated BaseClient. +func (c *BaseClient) WithTxFeeGranterAddr(addr cosmossdk.AccAddress) *BaseClient { c.txFeeGranterAddr = addr return c } -// WithTxFees assigns transaction fees and returns the updated Client. -func (c *Client) WithTxFees(fees types.Coins) *Client { +// WithTxFees assigns transaction fees and returns the updated BaseClient. +func (c *BaseClient) WithTxFees(fees cosmossdk.Coins) *BaseClient { c.txFees = fees return c } -// WithTxFromName sets the "from" name for transactions and returns the updated Client. -func (c *Client) WithTxFromName(name string) *Client { +// WithTxFromName sets the "from" name for transactions and returns the updated BaseClient. +func (c *BaseClient) WithTxFromName(name string) *BaseClient { c.txFromName = name return c } -// WithTxGasAdjustment sets the gas adjustment factor for transactions and returns the updated Client. -func (c *Client) WithTxGasAdjustment(adjustment float64) *Client { +// WithTxGasAdjustment sets the gas adjustment factor for transactions and returns the updated BaseClient. +func (c *BaseClient) WithTxGasAdjustment(adjustment float64) *BaseClient { c.txGasAdjustment = adjustment return c } -// WithTxGasPrices sets the gas prices for transactions and returns the updated Client. -func (c *Client) WithTxGasPrices(prices types.DecCoins) *Client { +// WithTxGasPrices sets the gas prices for transactions and returns the updated BaseClient. +func (c *BaseClient) WithTxGasPrices(prices cosmossdk.DecCoins) *BaseClient { c.txGasPrices = prices return c } -// WithTxGas sets the gas limit for transactions and returns the updated Client. -func (c *Client) WithTxGas(gas uint64) *Client { +// WithTxGas sets the gas limit for transactions and returns the updated BaseClient. +func (c *BaseClient) WithTxGas(gas uint64) *BaseClient { c.txGas = gas return c } -// WithTxMemo sets the memo for transactions and returns the updated Client. -func (c *Client) WithTxMemo(memo string) *Client { +// WithTxMemo sets the memo for transactions and returns the updated BaseClient. +func (c *BaseClient) WithTxMemo(memo string) *BaseClient { c.txMemo = memo return c } -// WithTxSimulateAndExecute sets the simulate and execute flag and returns the updated Client. -func (c *Client) WithTxSimulateAndExecute(simulate bool) *Client { +// WithTxSimulateAndExecute sets the simulate and execute flag and returns the updated BaseClient. +func (c *BaseClient) WithTxSimulateAndExecute(simulate bool) *BaseClient { c.txSimulateAndExecute = simulate return c } -// WithTxTimeoutHeight sets the timeout height for transactions and returns the updated Client. -func (c *Client) WithTxTimeoutHeight(height uint64) *Client { +// WithTxTimeoutHeight sets the timeout height for transactions and returns the updated BaseClient. +func (c *BaseClient) WithTxTimeoutHeight(height uint64) *BaseClient { c.txTimeoutHeight = height return c } // HTTP creates an HTTP client for the given RPC address and timeout configuration. // Returns the HTTP client or an error if initialization fails. -func (c *Client) HTTP() (*http.HTTP, error) { +func (c *BaseClient) HTTP() (*http.HTTP, error) { timeout := uint(c.rpcTimeout / time.Second) return http.NewWithTimeout(c.rpcAddr, "/websocket", timeout) } + +// NodeClient is a struct for interacting with nodes. +type NodeClient struct { + *BaseClient + addr types.NodeAddress + timeout time.Duration +} + +// NewNodeClient creates a new instance of NodeClient. +func NewNodeClient(base *BaseClient) *NodeClient { + return &NodeClient{ + BaseClient: base, + } +} + +// WithAddr sets the address of the NodeClient and returns the updated instance. +func (c *NodeClient) WithAddr(addr types.NodeAddress) *NodeClient { + c.addr = addr + return c +} + +// WithTimeout sets the timeout of the NodeClient and returns the updated instance. +func (c *NodeClient) WithTimeout(timeout time.Duration) *NodeClient { + c.timeout = timeout + return c +} diff --git a/client/key.go b/client/key.go index 0a0b134..bf633aa 100644 --- a/client/key.go +++ b/client/key.go @@ -11,7 +11,7 @@ import ( // Key retrieves key information from the keyring based on the provided name. // Returns the key record or an error if the key cannot be found. -func (c *Client) Key(name string) (*keyring.Record, error) { +func (c *BaseClient) Key(name string) (*keyring.Record, error) { key, err := c.keyring.Key(name) if err != nil { return nil, fmt.Errorf("failed to retrieve key: %w", err) @@ -22,7 +22,7 @@ func (c *Client) Key(name string) (*keyring.Record, error) { // Sign signs the provided data using the key from the keyring identified by the given name. // Returns the signed bytes, the public key, and any error encountered. -func (c *Client) Sign(name string, buf []byte) ([]byte, types.PubKey, error) { +func (c *BaseClient) Sign(name string, buf []byte) ([]byte, types.PubKey, error) { sig, pubKey, err := c.keyring.Sign(name, buf) if err != nil { return nil, nil, fmt.Errorf("failed to sign data: %w", err) @@ -33,7 +33,7 @@ func (c *Client) Sign(name string, buf []byte) ([]byte, types.PubKey, error) { // Keys retrieves a list of all keys from the keyring. // Returns the list of key records or an error if the operation fails. -func (c *Client) Keys() ([]*keyring.Record, error) { +func (c *BaseClient) Keys() ([]*keyring.Record, error) { keys, err := c.keyring.List() if err != nil { return nil, fmt.Errorf("failed to retrieve keys: %w", err) @@ -44,7 +44,7 @@ func (c *Client) Keys() ([]*keyring.Record, error) { // DeleteKey removes a key from the keyring based on the provided name. // Returns an error if the key cannot be deleted. -func (c *Client) DeleteKey(name string) error { +func (c *BaseClient) DeleteKey(name string) error { if err := c.keyring.Delete(name); err != nil { return fmt.Errorf("failed to delete key: %w", err) } @@ -54,7 +54,7 @@ func (c *Client) DeleteKey(name string) error { // NewMnemonic generates a new mnemonic phrase using bip39 with 256 bits of entropy. // Returns the mnemonic or an error if the operation fails. -func (c *Client) NewMnemonic() (string, error) { +func (c *BaseClient) NewMnemonic() (string, error) { // Generate new entropy for the mnemonic. entropy, err := bip39.NewEntropy(256) if err != nil { @@ -73,7 +73,7 @@ func (c *Client) NewMnemonic() (string, error) { // CreateKey generates and stores a new key in the keyring with the provided name, mnemonic, and options. // If no mnemonic is provided, it generates a new one. // Returns the mnemonic, the created key record, and any error encountered. -func (c *Client) CreateKey(name, mnemonic, bip39Pass string, coinType, account, index uint32) (s string, k *keyring.Record, err error) { +func (c *BaseClient) CreateKey(name, mnemonic, bip39Pass string, coinType, account, index uint32) (s string, k *keyring.Record, err error) { // Generate a new mnemonic if none is provided. if mnemonic == "" { mnemonic, err = c.NewMnemonic() diff --git a/client/lease.go b/client/lease.go index 3b9fc08..76f4b0d 100644 --- a/client/lease.go +++ b/client/lease.go @@ -18,7 +18,7 @@ const ( // Lease retrieves details of a specific lease by ID. // Returns the lease information and any error encountered. -func (c *Client) Lease(ctx context.Context, id uint64) (res *v1.Lease, err error) { +func (c *BaseClient) Lease(ctx context.Context, id uint64) (res *v1.Lease, err error) { var ( resp v1.QueryLeaseResponse req = &v1.QueryLeaseRequest{Id: id} @@ -34,7 +34,7 @@ func (c *Client) Lease(ctx context.Context, id uint64) (res *v1.Lease, err error // Leases retrieves a paginated list of all leases. // Returns the leases, pagination details, and any error encountered. -func (c *Client) Leases(ctx context.Context, pageReq *query.PageRequest) (res []v1.Lease, pageRes *query.PageResponse, err error) { +func (c *BaseClient) Leases(ctx context.Context, pageReq *query.PageRequest) (res []v1.Lease, pageRes *query.PageResponse, err error) { var ( resp v1.QueryLeasesResponse req = &v1.QueryLeasesRequest{Pagination: pageReq} @@ -50,7 +50,7 @@ func (c *Client) Leases(ctx context.Context, pageReq *query.PageRequest) (res [] // LeasesForNode retrieves leases associated with a specific node address. // Returns the leases, pagination details, and any error encountered. -func (c *Client) LeasesForNode(ctx context.Context, nodeAddr types.NodeAddress, pageReq *query.PageRequest) (res []v1.Lease, pageRes *query.PageResponse, err error) { +func (c *BaseClient) LeasesForNode(ctx context.Context, nodeAddr types.NodeAddress, pageReq *query.PageRequest) (res []v1.Lease, pageRes *query.PageResponse, err error) { var ( resp v1.QueryLeasesForNodeResponse req = &v1.QueryLeasesForNodeRequest{ @@ -69,7 +69,7 @@ func (c *Client) LeasesForNode(ctx context.Context, nodeAddr types.NodeAddress, // LeasesForProvider retrieves leases associated with a specific provider address. // Returns the leases, pagination details, and any error encountered. -func (c *Client) LeasesForProvider(ctx context.Context, provAddr types.ProvAddress, pageReq *query.PageRequest) (res []v1.Lease, pageRes *query.PageResponse, err error) { +func (c *BaseClient) LeasesForProvider(ctx context.Context, provAddr types.ProvAddress, pageReq *query.PageRequest) (res []v1.Lease, pageRes *query.PageResponse, err error) { var ( resp v1.QueryLeasesForProviderResponse req = &v1.QueryLeasesForProviderRequest{ diff --git a/client/node.go b/client/node.go index e689d6e..fc5ad1f 100644 --- a/client/node.go +++ b/client/node.go @@ -1,11 +1,14 @@ package client import ( + "bytes" "context" "crypto/tls" "encoding/json" "fmt" + "io" "net/http" + "net/url" "github.com/cosmos/cosmos-sdk/types/query" sentinelhub "github.com/sentinel-official/hub/v12/types" @@ -24,7 +27,7 @@ const ( // Node retrieves details of a specific node by its address. // Returns the node details and any error encountered. -func (c *Client) Node(ctx context.Context, nodeAddr sentinelhub.NodeAddress) (res *v3.Node, err error) { +func (c *BaseClient) Node(ctx context.Context, nodeAddr sentinelhub.NodeAddress) (res *v3.Node, err error) { var ( resp v3.QueryNodeResponse req = &v3.QueryNodeRequest{Address: nodeAddr.String()} @@ -40,7 +43,7 @@ func (c *Client) Node(ctx context.Context, nodeAddr sentinelhub.NodeAddress) (re // Nodes retrieves a paginated list of nodes filtered by their status. // Returns the nodes, pagination details, and any error encountered. -func (c *Client) Nodes(ctx context.Context, status v1.Status, pageReq *query.PageRequest) (res []v3.Node, pageRes *query.PageResponse, err error) { +func (c *BaseClient) Nodes(ctx context.Context, status v1.Status, pageReq *query.PageRequest) (res []v3.Node, pageRes *query.PageResponse, err error) { var ( resp v3.QueryNodesResponse req = &v3.QueryNodesRequest{ @@ -60,7 +63,7 @@ func (c *Client) Nodes(ctx context.Context, status v1.Status, pageReq *query.Pag // NodesForPlan retrieves a list of nodes associated with a specific plan ID. // Filters results by status and supports pagination. // Returns the nodes, pagination details, and any error encountered. -func (c *Client) NodesForPlan(ctx context.Context, id uint64, status v1.Status, pageReq *query.PageRequest) (res []v3.Node, pageRes *query.PageResponse, err error) { +func (c *BaseClient) NodesForPlan(ctx context.Context, id uint64, status v1.Status, pageReq *query.PageRequest) (res []v3.Node, pageRes *query.PageResponse, err error) { var ( resp v3.QueryNodesForPlanResponse req = &v3.QueryNodesForPlanRequest{ @@ -78,16 +81,10 @@ func (c *Client) NodesForPlan(ctx context.Context, id uint64, status v1.Status, return resp.Nodes, resp.Pagination, nil } -// NodeInfo retrieves detailed information about a specific node by querying its remote URL. -func (c *Client) NodeInfo(ctx context.Context, nodeAddr sentinelhub.NodeAddress, target interface{}) error { - // Query the node details. - node, err := c.Node(ctx, nodeAddr) - if err != nil { - return fmt.Errorf("failed to query node: %w", err) - } - +// do performs an HTTP request with the given parameters and decodes the response. +func (c *NodeClient) do(ctx context.Context, method, url string, reqBody, result interface{}) error { // Create a context with timeout for the HTTP request. - ctx, cancel := context.WithTimeout(ctx, c.rpcTimeout) + ctx, cancel := context.WithTimeout(ctx, c.timeout) defer cancel() // Configure the HTTP client with TLS settings. @@ -99,43 +96,92 @@ func (c *Client) NodeInfo(ctx context.Context, nodeAddr sentinelhub.NodeAddress, }, } - // Perform the HTTP GET request. - req, err := http.NewRequestWithContext(ctx, http.MethodGet, node.RemoteURL, nil) + // Marshal the request body if provided. + var body io.Reader + if reqBody != nil { + buf, err := json.Marshal(reqBody) + if err != nil { + return fmt.Errorf("failed to encode request body: %w", err) + } + + body = bytes.NewReader(buf) + } + + // Create the HTTP request. + req, err := http.NewRequestWithContext(ctx, method, url, body) if err != nil { return fmt.Errorf("failed to create request: %w", err) } + // Perform the HTTP request. resp, err := client.Do(req) if err != nil { - return fmt.Errorf("failed to get response: %w", err) + return fmt.Errorf("failed to perform request: %w", err) } defer resp.Body.Close() - // Check the response status code. + // Check for a successful status code. if resp.StatusCode != http.StatusOK { - return fmt.Errorf("invalid response status code %d", resp.StatusCode) + return fmt.Errorf("unexpected response status code: %d", resp.StatusCode) } - // Decode the json response into the Response struct - var body types.Response - if err := json.NewDecoder(resp.Body).Decode(&body); err != nil { + // Decode the JSON response into a predefined structure. + var respBody types.Response + if err := json.NewDecoder(resp.Body).Decode(&respBody); err != nil { return fmt.Errorf("failed to decode response body: %w", err) } - // Check the response for success or error - if err := body.Err(); err != nil { - return err + // Check for errors in the response. + if err := respBody.Err(); err != nil { + return fmt.Errorf("response error: %w", err) } - // Decode the Result field into the provided target - result, err := json.Marshal(body.Result) + // Decode the Result field if a result target is provided. + if result != nil { + buf, err := json.Marshal(respBody.Result) + if err != nil { + return fmt.Errorf("failed to encode data: %w", err) + } + if err := json.Unmarshal(buf, result); err != nil { + return fmt.Errorf("failed to decode result: %w", err) + } + } + + return nil +} + +// getURL constructs the full URL for a node with an optional path. +func (c *NodeClient) getURL(ctx context.Context, pathSuffix string) (string, error) { + node, err := c.Node(ctx, c.addr) if err != nil { - return fmt.Errorf("failed to encode result: %w", err) + return "", fmt.Errorf("failed to query node: %w", err) } - if err := json.Unmarshal(result, target); err != nil { - return fmt.Errorf("failed to decode result: %w", err) + + path, err := url.JoinPath(node.RemoteURL, pathSuffix) + if err != nil { + return "", fmt.Errorf("failed to join url path: %w", err) } - return nil + return path, nil +} + +// GetInfo retrieves information about a specific node. +func (c *NodeClient) GetInfo(ctx context.Context, result interface{}) error { + path, err := c.getURL(ctx, "") + if err != nil { + return fmt.Errorf("failed to get url: %w", err) + } + + return c.do(ctx, http.MethodGet, path, nil, result) +} + +// AddSession adds a session to a node. +func (c *NodeClient) AddSession(ctx context.Context, id uint64, body, result interface{}) error { + path, err := c.getURL(ctx, fmt.Sprintf("sessions/%d/keys", id)) + if err != nil { + return fmt.Errorf("failed to get url: %w", err) + } + + return c.do(ctx, http.MethodPost, path, body, result) } diff --git a/client/plan.go b/client/plan.go index 2740403..efbc189 100644 --- a/client/plan.go +++ b/client/plan.go @@ -18,7 +18,7 @@ const ( // Plan retrieves details of a specific plan by its ID. // Returns the plan details and any error encountered. -func (c *Client) Plan(ctx context.Context, id uint64) (res *v3.Plan, err error) { +func (c *BaseClient) Plan(ctx context.Context, id uint64) (res *v3.Plan, err error) { var ( resp v3.QueryPlanResponse req = &v3.QueryPlanRequest{Id: id} @@ -34,7 +34,7 @@ func (c *Client) Plan(ctx context.Context, id uint64) (res *v3.Plan, err error) // Plans retrieves a paginated list of plans filtered by their status. // Returns the plans, pagination details, and any error encountered. -func (c *Client) Plans(ctx context.Context, status v1.Status, pageReq *query.PageRequest) (res []v3.Plan, pageRes *query.PageResponse, err error) { +func (c *BaseClient) Plans(ctx context.Context, status v1.Status, pageReq *query.PageRequest) (res []v3.Plan, pageRes *query.PageResponse, err error) { var ( resp v3.QueryPlansResponse req = &v3.QueryPlansRequest{ @@ -54,7 +54,7 @@ func (c *Client) Plans(ctx context.Context, status v1.Status, pageReq *query.Pag // PlansForProvider retrieves a list of plans associated with a specific provider address. // Filters results by status and supports pagination. // Returns the plans, pagination details, and any error encountered. -func (c *Client) PlansForProvider(ctx context.Context, provAddr types.ProvAddress, status v1.Status, pageReq *query.PageRequest) (res []v3.Plan, pageRes *query.PageResponse, err error) { +func (c *BaseClient) PlansForProvider(ctx context.Context, provAddr types.ProvAddress, status v1.Status, pageReq *query.PageRequest) (res []v3.Plan, pageRes *query.PageResponse, err error) { var ( resp v3.QueryPlansForProviderResponse req = &v3.QueryPlansForProviderRequest{ diff --git a/client/provider.go b/client/provider.go index ea64bfc..10ae7eb 100644 --- a/client/provider.go +++ b/client/provider.go @@ -17,7 +17,7 @@ const ( // Provider retrieves details of a specific provider by its address. // Returns the provider details and any error encountered. -func (c *Client) Provider(ctx context.Context, provAddr types.ProvAddress) (res *v2.Provider, err error) { +func (c *BaseClient) Provider(ctx context.Context, provAddr types.ProvAddress) (res *v2.Provider, err error) { var ( resp v2.QueryProviderResponse req = &v2.QueryProviderRequest{Address: provAddr.String()} @@ -33,7 +33,7 @@ func (c *Client) Provider(ctx context.Context, provAddr types.ProvAddress) (res // Providers retrieves a paginated list of providers filtered by their status. // Returns the providers, pagination details, and any error encountered. -func (c *Client) Providers(ctx context.Context, status v1.Status, pageReq *query.PageRequest) (res []v2.Provider, pageRes *query.PageResponse, err error) { +func (c *BaseClient) Providers(ctx context.Context, status v1.Status, pageReq *query.PageRequest) (res []v2.Provider, pageRes *query.PageResponse, err error) { var ( resp v2.QueryProvidersResponse req = &v2.QueryProvidersRequest{ diff --git a/client/query.go b/client/query.go index ed96c8a..7e453fd 100644 --- a/client/query.go +++ b/client/query.go @@ -25,9 +25,9 @@ func IsNotFoundError(err error) error { } // ABCIQueryWithOptions performs an ABCI query with configurable options. -// It retries the query in case of failures based on the Client's retry configuration. +// It retries the query in case of failures based on the BaseClient's retry configuration. // Returns the ABCI query response or an error. -func (c *Client) ABCIQueryWithOptions(ctx context.Context, path string, data bytes.HexBytes) (*abci.ResponseQuery, error) { +func (c *BaseClient) ABCIQueryWithOptions(ctx context.Context, path string, data bytes.HexBytes) (*abci.ResponseQuery, error) { var result *core.ResultABCIQuery // Define the function to perform the ABCI query. @@ -75,7 +75,7 @@ func (c *Client) ABCIQueryWithOptions(ctx context.Context, path string, data byt // QueryKey performs an ABCI query for a specific key in a store. // Constructs the query path and delegates the query to ABCIQueryWithOptions. // Returns the query response or an error. -func (c *Client) QueryKey(ctx context.Context, store string, data bytes.HexBytes) (*abci.ResponseQuery, error) { +func (c *BaseClient) QueryKey(ctx context.Context, store string, data bytes.HexBytes) (*abci.ResponseQuery, error) { // Construct the path for querying the key. path := fmt.Sprintf("/store/%s/key", store) @@ -91,7 +91,7 @@ func (c *Client) QueryKey(ctx context.Context, store string, data bytes.HexBytes // QuerySubspace performs an ABCI query for a subspace in a store. // Constructs the query path and delegates the query to ABCIQueryWithOptions. // Returns the query response or an error. -func (c *Client) QuerySubspace(ctx context.Context, store string, data bytes.HexBytes) (*abci.ResponseQuery, error) { +func (c *BaseClient) QuerySubspace(ctx context.Context, store string, data bytes.HexBytes) (*abci.ResponseQuery, error) { // Construct the path for querying the subspace. path := fmt.Sprintf("/store/%s/subspace", store) @@ -107,7 +107,7 @@ func (c *Client) QuerySubspace(ctx context.Context, store string, data bytes.Hex // QueryGRPC performs a gRPC query using ABCI with configurable options. // Marshals the request, queries via ABCI, and unmarshals the response. // Returns an error if any step fails. -func (c *Client) QueryGRPC(ctx context.Context, method string, req, resp codec.ProtoMarshaler) error { +func (c *BaseClient) QueryGRPC(ctx context.Context, method string, req, resp codec.ProtoMarshaler) error { // Marshal the request into bytes. data, err := c.protoCodec.Marshal(req) if err != nil { diff --git a/client/session.go b/client/session.go index 1d50d6f..c2cc3cf 100644 --- a/client/session.go +++ b/client/session.go @@ -21,7 +21,7 @@ const ( // Session retrieves details of a specific session by its ID. // Returns the session details and any error encountered. -func (c *Client) Session(ctx context.Context, id uint64) (res v3.Session, err error) { +func (c *BaseClient) Session(ctx context.Context, id uint64) (res v3.Session, err error) { var ( resp v3.QuerySessionResponse req = &v3.QuerySessionRequest{Id: id} @@ -42,7 +42,7 @@ func (c *Client) Session(ctx context.Context, id uint64) (res v3.Session, err er // Sessions retrieves a paginated list of all sessions. // Returns the sessions, pagination details, and any error encountered. -func (c *Client) Sessions(ctx context.Context, pageReq *query.PageRequest) (res []v3.Session, pageRes *query.PageResponse, err error) { +func (c *BaseClient) Sessions(ctx context.Context, pageReq *query.PageRequest) (res []v3.Session, pageRes *query.PageResponse, err error) { var ( resp v3.QuerySessionsResponse req = &v3.QuerySessionsRequest{Pagination: pageReq} @@ -66,7 +66,7 @@ func (c *Client) Sessions(ctx context.Context, pageReq *query.PageRequest) (res // SessionsForAccount retrieves sessions associated with a specific account address. // Returns the sessions, pagination details, and any error encountered. -func (c *Client) SessionsForAccount(ctx context.Context, accAddr cosmossdk.AccAddress, pageReq *query.PageRequest) (res []v3.Session, pageRes *query.PageResponse, err error) { +func (c *BaseClient) SessionsForAccount(ctx context.Context, accAddr cosmossdk.AccAddress, pageReq *query.PageRequest) (res []v3.Session, pageRes *query.PageResponse, err error) { var ( resp v3.QuerySessionsForAccountResponse req = &v3.QuerySessionsForAccountRequest{ @@ -93,7 +93,7 @@ func (c *Client) SessionsForAccount(ctx context.Context, accAddr cosmossdk.AccAd // SessionsForNode retrieves sessions associated with a specific node address. // Returns the sessions, pagination details, and any error encountered. -func (c *Client) SessionsForNode(ctx context.Context, nodeAddr sentinelhub.NodeAddress, pageReq *query.PageRequest) (res []v3.Session, pageRes *query.PageResponse, err error) { +func (c *BaseClient) SessionsForNode(ctx context.Context, nodeAddr sentinelhub.NodeAddress, pageReq *query.PageRequest) (res []v3.Session, pageRes *query.PageResponse, err error) { var ( resp v3.QuerySessionsForNodeResponse req = &v3.QuerySessionsForNodeRequest{ @@ -120,7 +120,7 @@ func (c *Client) SessionsForNode(ctx context.Context, nodeAddr sentinelhub.NodeA // SessionsForSubscription retrieves sessions associated with a specific subscription ID. // Returns the sessions, pagination details, and any error encountered. -func (c *Client) SessionsForSubscription(ctx context.Context, id uint64, pageReq *query.PageRequest) (res []v3.Session, pageRes *query.PageResponse, err error) { +func (c *BaseClient) SessionsForSubscription(ctx context.Context, id uint64, pageReq *query.PageRequest) (res []v3.Session, pageRes *query.PageResponse, err error) { var ( resp v3.QuerySessionsForSubscriptionResponse req = &v3.QuerySessionsForSubscriptionRequest{ @@ -147,7 +147,7 @@ func (c *Client) SessionsForSubscription(ctx context.Context, id uint64, pageReq // SessionsForSubscriptionAllocation retrieves sessions associated with a specific subscription ID and account address. // Returns the sessions, pagination details, and any error encountered. -func (c *Client) SessionsForSubscriptionAllocation(ctx context.Context, id uint64, accAddr cosmossdk.AccAddress, pageReq *query.PageRequest) (res []v3.Session, pageRes *query.PageResponse, err error) { +func (c *BaseClient) SessionsForSubscriptionAllocation(ctx context.Context, id uint64, accAddr cosmossdk.AccAddress, pageReq *query.PageRequest) (res []v3.Session, pageRes *query.PageResponse, err error) { var ( resp v3.QuerySessionsForAllocationResponse req = &v3.QuerySessionsForAllocationRequest{ diff --git a/client/subscription.go b/client/subscription.go index edf7a83..fc1dc4c 100644 --- a/client/subscription.go +++ b/client/subscription.go @@ -21,7 +21,7 @@ const ( // Subscription retrieves details of a specific subscription by its ID. // Returns the subscription details and any error encountered. -func (c *Client) Subscription(ctx context.Context, id uint64) (res *v3.Subscription, err error) { +func (c *BaseClient) Subscription(ctx context.Context, id uint64) (res *v3.Subscription, err error) { var ( resp v3.QuerySubscriptionResponse req = &v3.QuerySubscriptionRequest{Id: id} @@ -37,7 +37,7 @@ func (c *Client) Subscription(ctx context.Context, id uint64) (res *v3.Subscript // Subscriptions retrieves a paginated list of all subscriptions. // Returns the subscriptions, pagination details, and any error encountered. -func (c *Client) Subscriptions(ctx context.Context, pageReq *query.PageRequest) (res []v3.Subscription, pageRes *query.PageResponse, err error) { +func (c *BaseClient) Subscriptions(ctx context.Context, pageReq *query.PageRequest) (res []v3.Subscription, pageRes *query.PageResponse, err error) { var ( resp v3.QuerySubscriptionsResponse req = &v3.QuerySubscriptionsRequest{Pagination: pageReq} @@ -53,7 +53,7 @@ func (c *Client) Subscriptions(ctx context.Context, pageReq *query.PageRequest) // SubscriptionsForAccount retrieves subscriptions associated with a specific account. // Returns the subscriptions, pagination details, and any error encountered. -func (c *Client) SubscriptionsForAccount(ctx context.Context, accAddr types.AccAddress, pageReq *query.PageRequest) (res []v3.Subscription, pageRes *query.PageResponse, err error) { +func (c *BaseClient) SubscriptionsForAccount(ctx context.Context, accAddr types.AccAddress, pageReq *query.PageRequest) (res []v3.Subscription, pageRes *query.PageResponse, err error) { var ( resp v3.QuerySubscriptionsForAccountResponse req = &v3.QuerySubscriptionsForAccountRequest{ @@ -72,7 +72,7 @@ func (c *Client) SubscriptionsForAccount(ctx context.Context, accAddr types.AccA // SubscriptionsForPlan retrieves subscriptions associated with a specific plan. // Returns the subscriptions, pagination details, and any error encountered. -func (c *Client) SubscriptionsForPlan(ctx context.Context, id uint64, pageReq *query.PageRequest) (res []v3.Subscription, pageRes *query.PageResponse, err error) { +func (c *BaseClient) SubscriptionsForPlan(ctx context.Context, id uint64, pageReq *query.PageRequest) (res []v3.Subscription, pageRes *query.PageResponse, err error) { var ( resp v3.QuerySubscriptionsForPlanResponse req = &v3.QuerySubscriptionsForPlanRequest{ @@ -91,7 +91,7 @@ func (c *Client) SubscriptionsForPlan(ctx context.Context, id uint64, pageReq *q // SubscriptionAllocation retrieves details of a specific allocation within a subscription. // Returns the allocation details and any error encountered. -func (c *Client) SubscriptionAllocation(ctx context.Context, id uint64, accAddr types.AccAddress) (res *v2.Allocation, err error) { +func (c *BaseClient) SubscriptionAllocation(ctx context.Context, id uint64, accAddr types.AccAddress) (res *v2.Allocation, err error) { var ( resp v2.QueryAllocationResponse req = &v2.QueryAllocationRequest{ @@ -110,7 +110,7 @@ func (c *Client) SubscriptionAllocation(ctx context.Context, id uint64, accAddr // SubscriptionAllocations retrieves a paginated list of allocations within a specific subscription. // Returns the allocations, pagination details, and any error encountered. -func (c *Client) SubscriptionAllocations(ctx context.Context, id uint64, pageReq *query.PageRequest) (res []v2.Allocation, pageRes *query.PageResponse, err error) { +func (c *BaseClient) SubscriptionAllocations(ctx context.Context, id uint64, pageReq *query.PageRequest) (res []v2.Allocation, pageRes *query.PageResponse, err error) { var ( resp v2.QueryAllocationsResponse req = &v2.QueryAllocationsRequest{ diff --git a/client/tx.go b/client/tx.go index 1843dc2..522b73f 100644 --- a/client/tx.go +++ b/client/tx.go @@ -32,7 +32,7 @@ func calculateFees(gasPrices cosmossdk.DecCoins, gasLimit uint64) cosmossdk.Coin // Simulate simulates the execution of a transaction before broadcasting it. // Takes transaction bytes as input and returns the simulation response or an error. -func (c *Client) Simulate(ctx context.Context, buf []byte) (*tx.SimulateResponse, error) { +func (c *BaseClient) Simulate(ctx context.Context, buf []byte) (*tx.SimulateResponse, error) { var ( resp tx.SimulateResponse req = &tx.SimulateRequest{TxBytes: buf} @@ -48,7 +48,7 @@ func (c *Client) Simulate(ctx context.Context, buf []byte) (*tx.SimulateResponse // gasSimulateTx calculates the gas usage of a transaction. // Returns the gas used and any error encountered. -func (c *Client) gasSimulateTx(ctx context.Context, txb client.TxBuilder) (uint64, error) { +func (c *BaseClient) gasSimulateTx(ctx context.Context, txb client.TxBuilder) (uint64, error) { // Encode the transaction into bytes. buf, err := c.txConfig.TxEncoder()(txb.GetTx()) if err != nil { @@ -67,7 +67,7 @@ func (c *Client) gasSimulateTx(ctx context.Context, txb client.TxBuilder) (uint6 // broadcastTxSync broadcasts a transaction synchronously. // Returns the broadcast result or an error if the operation fails. -func (c *Client) broadcastTxSync(ctx context.Context, txb client.TxBuilder) (*core.ResultBroadcastTx, error) { +func (c *BaseClient) broadcastTxSync(ctx context.Context, txb client.TxBuilder) (*core.ResultBroadcastTx, error) { // Encode the transaction into bytes. buf, err := c.txConfig.TxEncoder()(txb.GetTx()) if err != nil { @@ -91,7 +91,7 @@ func (c *Client) broadcastTxSync(ctx context.Context, txb client.TxBuilder) (*co // signTx signs a transaction using the provided key and account information. // Returns an error if the signing process fails. -func (c *Client) signTx(txb client.TxBuilder, key *keyring.Record, account auth.AccountI) error { +func (c *BaseClient) signTx(txb client.TxBuilder, key *keyring.Record, account auth.AccountI) error { // Prepare the single signature data. singleSignatureData := txsigning.SingleSignatureData{ SignMode: txsigning.SignMode_SIGN_MODE_DIRECT, @@ -149,7 +149,7 @@ func (c *Client) signTx(txb client.TxBuilder, key *keyring.Record, account auth. // prepareTx prepares a transaction for broadcasting by setting fees, gas, and other parameters. // Returns the transaction builder and any error encountered. -func (c *Client) prepareTx(ctx context.Context, key *keyring.Record, account auth.AccountI, msgs []cosmossdk.Msg) (client.TxBuilder, error) { +func (c *BaseClient) prepareTx(ctx context.Context, key *keyring.Record, account auth.AccountI, msgs []cosmossdk.Msg) (client.TxBuilder, error) { // Create a new transaction builder. txb := c.txConfig.NewTxBuilder() if err := txb.SetMsgs(msgs...); err != nil { @@ -205,7 +205,7 @@ func (c *Client) prepareTx(ctx context.Context, key *keyring.Record, account aut } // BroadcastTx broadcasts a signed transaction and returns the broadcast result or an error. -func (c *Client) BroadcastTx(ctx context.Context, msgs []cosmossdk.Msg) (*core.ResultBroadcastTx, error) { +func (c *BaseClient) BroadcastTx(ctx context.Context, msgs []cosmossdk.Msg) (*core.ResultBroadcastTx, error) { // Retrieve the signing key. key, err := c.Key(c.txFromName) if err != nil { @@ -246,7 +246,7 @@ func (c *Client) BroadcastTx(ctx context.Context, msgs []cosmossdk.Msg) (*core.R // Tx retrieves a transaction from the blockchain using its hash. // Returns the transaction result or an error. -func (c *Client) Tx(ctx context.Context, hash []byte) (*core.ResultTx, error) { +func (c *BaseClient) Tx(ctx context.Context, hash []byte) (*core.ResultTx, error) { // Get the HTTP client for querying the blockchain. http, err := c.HTTP() if err != nil { diff --git a/cmd/keys.go b/cmd/keys.go index 25f03de..f89f2b8 100644 --- a/cmd/keys.go +++ b/cmd/keys.go @@ -17,7 +17,7 @@ import ( // KeysCmd returns a new Cobra command for key management sub-commands. func KeysCmd() *cobra.Command { - c := client.New() + c := client.NewBaseClient() rootCmd := &cobra.Command{ Use: "keys", Short: "Sub-commands for managing keys", @@ -61,7 +61,7 @@ func KeysCmd() *cobra.Command { } // keysAddCmd creates a new key with the specified name, mnemonic, and bip39 passphrase. -func keysAddCmd(c *client.Client) *cobra.Command { +func keysAddCmd(c *client.BaseClient) *cobra.Command { cmd := &cobra.Command{ Use: "add [name]", Short: "Add a new key with the specified name and optional mnemonic", @@ -142,7 +142,7 @@ func keysAddCmd(c *client.Client) *cobra.Command { } // keysDeleteCmd removes the key with the specified name. -func keysDeleteCmd(c *client.Client) *cobra.Command { +func keysDeleteCmd(c *client.BaseClient) *cobra.Command { cmd := &cobra.Command{ Use: "delete [name]", Short: "Delete the key with the specified name", @@ -176,7 +176,7 @@ func keysDeleteCmd(c *client.Client) *cobra.Command { } // keysListCmd lists all the available keys. -func keysListCmd(c *client.Client) *cobra.Command { +func keysListCmd(c *client.BaseClient) *cobra.Command { cmd := &cobra.Command{ Use: "list", Short: "List all available keys", @@ -209,7 +209,7 @@ func keysListCmd(c *client.Client) *cobra.Command { } // keysShowCmd displays details of the key with the specified name. -func keysShowCmd(c *client.Client) *cobra.Command { +func keysShowCmd(c *client.BaseClient) *cobra.Command { cmd := &cobra.Command{ Use: "show [name]", Short: "Show details of the key with the specified name",