diff --git a/auth_vote/authz_vote.go b/auth_vote/authz_vote.go index a253fc5d..00d0f028 100644 --- a/auth_vote/authz_vote.go +++ b/auth_vote/authz_vote.go @@ -1,17 +1,20 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "time" - chainclient "github.com/InjectiveLabs/sdk-go/client/chain" - "github.com/InjectiveLabs/sdk-go/client/common" rpchttp "github.com/cometbft/cometbft/rpc/client/http" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" authztypes "github.com/cosmos/cosmos-sdk/x/authz" "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" + + chainclient "github.com/InjectiveLabs/sdk-go/client/chain" + "github.com/InjectiveLabs/sdk-go/client/common" ) //revive:disable:function-length // this is an example script @@ -59,7 +62,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -93,7 +99,7 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - response, err := chainClient.AsyncBroadcastMsg(msgs...) + response, err := chainClient.AsyncBroadcastMsg(ctx, msgs...) if err != nil { panic(err) @@ -102,7 +108,7 @@ func main() { str, _ := json.MarshalIndent(response, "", "\t") fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/chain/exchange/types/key.go b/chain/exchange/types/key.go index bc4bd211..ca3d8551 100644 --- a/chain/exchange/types/key.go +++ b/chain/exchange/types/key.go @@ -426,7 +426,7 @@ func OrdersByMarketDirectionPriceOrderHashPrefix(marketID, orderHash common.Hash return append(ordersByMarketDirectionPricePrefix(marketID, price, isLong), orderHash.Bytes()...) } -// orderIndexByMarketDirectionSubaccountPrefix allows to obtain prefix of exchange against a particular marketID, direction and price +// ordersByMarketDirectionPricePrefix allows to obtain prefix of exchange against a particular marketID, direction and price func ordersByMarketDirectionPricePrefix(marketID common.Hash, price *big.Int, isLong bool) []byte { return append(MarketDirectionPrefix(marketID, isLong), common.LeftPadBytes(price.Bytes(), 32)...) } diff --git a/client/chain/chain.go b/client/chain/chain.go index 1be6a968..26d5d8cf 100644 --- a/client/chain/chain.go +++ b/client/chain/chain.go @@ -84,12 +84,24 @@ type ChainClient interface { SyncBroadcastMsg(msgs ...sdk.Msg) (*txtypes.BroadcastTxResponse, error) BroadcastMsg(broadcastMode txtypes.BroadcastMode, msgs ...sdk.Msg) (*txtypes.BroadcastTxRequest, *txtypes.BroadcastTxResponse, error) + // Enhanced broadcast methods with context support + SimulateMsgWithContext(ctx context.Context, msgs ...sdk.Msg) (*txtypes.SimulateResponse, error) + AsyncBroadcastMsgWithContext(ctx context.Context, msgs ...sdk.Msg) (*txtypes.BroadcastTxResponse, error) + SyncBroadcastMsgWithContext(ctx context.Context, pollInterval *time.Duration, maxRetries uint32, msgs ...sdk.Msg) (*txtypes.BroadcastTxResponse, error) + BroadcastMsgWithContext(ctx context.Context, broadcastMode txtypes.BroadcastMode, msgs ...sdk.Msg) (*txtypes.BroadcastTxRequest, *txtypes.BroadcastTxResponse, error) + // Build signed tx with given accNum and accSeq, useful for offline siging // If simulate is set to false, initialGas will be used BuildSignedTx(clientCtx sdkclient.Context, accNum, accSeq, initialGas uint64, gasPrice uint64, msg ...sdk.Msg) ([]byte, error) SyncBroadcastSignedTx(tyBytes []byte) (*txtypes.BroadcastTxResponse, error) AsyncBroadcastSignedTx(txBytes []byte) (*txtypes.BroadcastTxResponse, error) BroadcastSignedTx(txBytes []byte, broadcastMode txtypes.BroadcastMode) (*txtypes.BroadcastTxResponse, error) + + // Enhanced signed tx broadcast methods with context support + BuildSignedTxWithContext(ctx context.Context, accNum, accSeq, initialGas uint64, gasPrice uint64, msgs ...sdk.Msg) ([]byte, error) + SyncBroadcastSignedTxWithContext(ctx context.Context, txBytes []byte, pollInterval *time.Duration, maxRetries uint32) (*txtypes.BroadcastTxResponse, error) + AsyncBroadcastSignedTxWithContext(ctx context.Context, txBytes []byte) (*txtypes.BroadcastTxResponse, error) + BroadcastSignedTxWithContext(ctx context.Context, txBytes []byte, broadcastMode txtypes.BroadcastMode) (*txtypes.BroadcastTxResponse, error) QueueBroadcastMsg(msgs ...sdk.Msg) error // Bank Module @@ -312,6 +324,7 @@ type ChainClient interface { FetchEipBaseFee(ctx context.Context) (*txfeestypes.QueryEipBaseFeeResponse, error) CurrentChainGasPrice() int64 + CurrentChainGasPriceWithContext(ctx context.Context) int64 SetGasPrice(gasPrice int64) GetNetwork() common.Network @@ -765,6 +778,32 @@ func (c *chainClient) SimulateMsg(clientCtx sdkclient.Context, msgs ...sdk.Msg) return simRes, nil } +func (c *chainClient) SimulateMsgWithContext(ctx context.Context, msgs ...sdk.Msg) (*txtypes.SimulateResponse, error) { + c.txFactory = c.txFactory.WithSequence(c.accSeq) + c.txFactory = c.txFactory.WithAccountNumber(c.accNum) + txf, err := PrepareFactory(c.ctx, c.txFactory) + if err != nil { + err = errors.Wrap(err, "failed to prepareFactory") + return nil, err + } + + simTxBytes, err := txf.BuildSimTx(msgs...) + if err != nil { + err = errors.Wrap(err, "failed to build sim tx bytes") + return nil, err + } + + req := &txtypes.SimulateRequest{TxBytes: simTxBytes} + simRes, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.txClient.Simulate, req) + + if err != nil { + err = errors.Wrap(err, "failed to CalculateGas") + return nil, err + } + + return simRes, nil +} + func (c *chainClient) BuildSignedTx(clientCtx sdkclient.Context, accNum, accSeq, initialGas uint64, gasPrice uint64, msgs ...sdk.Msg) ([]byte, error) { txf := NewTxFactory(clientCtx).WithSequence(accSeq).WithAccountNumber(accNum) txf = txf.WithGas(initialGas) @@ -819,6 +858,59 @@ func (c *chainClient) buildSignedTx(clientCtx sdkclient.Context, txf tx.Factory, return clientCtx.TxConfig.TxEncoder()(txn.GetTx()) } +func (c *chainClient) BuildSignedTxWithContext(ctx context.Context, accNum, accSeq, initialGas uint64, gasPrice uint64, msgs ...sdk.Msg) ([]byte, error) { + txf := NewTxFactory(c.ctx).WithSequence(accSeq).WithAccountNumber(accNum) + txf = txf.WithGas(initialGas) + + gasPriceWithDenom := fmt.Sprintf("%d%s", gasPrice, client.InjDenom) + txf = txf.WithGasPrices(gasPriceWithDenom) + + return c.buildSignedTxWithContext(ctx, txf, msgs...) +} + +func (c *chainClient) buildSignedTxWithContext(ctx context.Context, txf tx.Factory, msgs ...sdk.Msg) ([]byte, error) { + if c.ctx.Simulate { + simTxBytes, err := txf.BuildSimTx(msgs...) + if err != nil { + err = errors.Wrap(err, "failed to build sim tx bytes") + return nil, err + } + + req := &txtypes.SimulateRequest{TxBytes: simTxBytes} + simRes, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.txClient.Simulate, req) + + if err != nil { + err = errors.Wrap(err, "failed to CalculateGas") + return nil, err + } + + adjustedGas := uint64(txf.GasAdjustment() * float64(simRes.GasInfo.GasUsed)) + txf = txf.WithGas(adjustedGas) + + c.gasWanted = adjustedGas + } + + txf, err := PrepareFactory(c.ctx, txf) + if err != nil { + return nil, errors.Wrap(err, "failed to prepareFactory") + } + + txn, err := txf.BuildUnsignedTx(msgs...) + if err != nil { + err = errors.Wrap(err, "failed to BuildUnsignedTx") + return nil, err + } + + txn.SetFeeGranter(c.ctx.GetFeeGranterAddress()) + err = tx.Sign(ctx, txf, c.ctx.GetFromName(), txn, true) + if err != nil { + err = errors.Wrap(err, "failed to Sign Tx") + return nil, err + } + + return c.ctx.TxConfig.TxEncoder()(txn.GetTx()) +} + func (c *chainClient) SyncBroadcastSignedTx(txBytes []byte) (*txtypes.BroadcastTxResponse, error) { res, err := c.BroadcastSignedTx(txBytes, txtypes.BroadcastMode_BROADCAST_MODE_SYNC) if err != nil || res.TxResponse.Code != 0 { @@ -2921,6 +3013,214 @@ func (c *chainClient) ComputeOrderHashes(spotOrders []exchangetypes.SpotOrder, d return orderHashes, nil } +// SyncBroadcastMsgWithContext sends Tx to chain and waits until Tx is included in block. +// This is the enhanced version with context support, configurable poll interval, and max retries. +func (c *chainClient) SyncBroadcastMsgWithContext(ctx context.Context, pollInterval *time.Duration, maxRetries uint32, msgs ...sdk.Msg) (*txtypes.BroadcastTxResponse, error) { + req, res, err := c.BroadcastMsgWithContext(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, msgs...) + + if err != nil || res.TxResponse.Code != 0 { + return res, err + } + + txHash, _ := hex.DecodeString(res.TxResponse.TxHash) + + statusPollInterval := defaultBroadcastStatusPoll + if pollInterval != nil { + statusPollInterval = *pollInterval + } + + totalAttempts := uint32(0) + t := time.NewTimer(statusPollInterval) + + for { + select { + case <-ctx.Done(): + err := errors.Wrapf(ErrTimedOut, "%s", res.TxResponse.TxHash) + t.Stop() + return nil, err + case <-t.C: + totalAttempts++ + resultTx, txErr := c.ctx.Client.Tx(ctx, txHash, false) + + if txErr != nil { + // Check if this is a fatal error that shouldn't be retried + if errRes := sdkclient.CheckCometError(txErr, req.TxBytes); errRes != nil { + return &txtypes.BroadcastTxResponse{TxResponse: errRes}, txErr + } + + // If we've reached max retries, return error + if totalAttempts >= maxRetries { + t.Stop() + return nil, errors.Wrapf(txErr, "failed to get transaction after %d retries: %s", maxRetries, res.TxResponse.TxHash) + } + + // Continue retrying with same interval + t.Reset(statusPollInterval) + continue + } else if resultTx.Height > 0 { + resResultTx := sdk.NewResponseResultTx(resultTx, res.TxResponse.Tx, res.TxResponse.Timestamp) + res = &txtypes.BroadcastTxResponse{TxResponse: resResultTx} + t.Stop() + return res, err + } + + // Transaction not yet in block, continue polling + t.Reset(statusPollInterval) + } + } +} + +// AsyncBroadcastMsgWithContext sends Tx to chain and doesn't wait until Tx is included in block. This method +// cannot be used for rapid Tx sending, it is expected that you wait for transaction status with +// external tools. If you want sdk to wait for it, use SyncBroadcastMsgWithContext. +func (c *chainClient) AsyncBroadcastMsgWithContext(ctx context.Context, msgs ...sdk.Msg) (*txtypes.BroadcastTxResponse, error) { + _, res, err := c.BroadcastMsgWithContext(ctx, txtypes.BroadcastMode_BROADCAST_MODE_ASYNC, msgs...) + return res, err +} + +// BroadcastMsgWithContext submits a group of messages in one transaction to the chain +// The function uses the broadcast mode specified with the broadcastMode parameter +func (c *chainClient) BroadcastMsgWithContext(ctx context.Context, broadcastMode txtypes.BroadcastMode, msgs ...sdk.Msg) (*txtypes.BroadcastTxRequest, *txtypes.BroadcastTxResponse, error) { + c.syncMux.Lock() + defer c.syncMux.Unlock() + + sequence := c.getAccSeq() + c.txFactory = c.txFactory.WithSequence(sequence) + c.txFactory = c.txFactory.WithAccountNumber(c.accNum) + req, res, err := c.broadcastTxWithContext(ctx, c.txFactory, broadcastMode, msgs...) + if err != nil { + if c.opts.ShouldFixSequenceMismatch && strings.Contains(err.Error(), "account sequence mismatch") { + c.syncNonce() + sequence := c.getAccSeq() + c.txFactory = c.txFactory.WithSequence(sequence) + c.txFactory = c.txFactory.WithAccountNumber(c.accNum) + c.logger.Debugln("retrying broadcastTx with nonce", sequence) + req, res, err = c.broadcastTxWithContext(ctx, c.txFactory, broadcastMode, msgs...) + } + if err != nil { + resJSON, _ := json.MarshalIndent(res, "", "\t") + c.logger.WithField("size", len(msgs)).WithError(err).Errorln("failed to asynchronously broadcast messagess:", string(resJSON)) + return nil, nil, err + } + } + + return req, res, nil +} + +func (c *chainClient) broadcastTxWithContext( + ctx context.Context, + txf tx.Factory, + broadcastMode txtypes.BroadcastMode, + msgs ...sdk.Msg, +) (*txtypes.BroadcastTxRequest, *txtypes.BroadcastTxResponse, error) { + txBytes, err := c.buildSignedTxWithContext(ctx, txf, msgs...) + if err != nil { + err = errors.Wrap(err, "failed to build signed Tx") + return nil, nil, err + } + + req := txtypes.BroadcastTxRequest{ + TxBytes: txBytes, + Mode: broadcastMode, + } + + res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.txClient.BroadcastTx, &req) + return &req, res, err +} + +// SyncBroadcastSignedTxWithContext broadcasts a signed transaction and waits until it's included in block. +// This is the enhanced version with context support, configurable poll interval, and max retries. +func (c *chainClient) SyncBroadcastSignedTxWithContext(ctx context.Context, txBytes []byte, pollInterval *time.Duration, maxRetries uint32) (*txtypes.BroadcastTxResponse, error) { + res, err := c.BroadcastSignedTxWithContext(ctx, txBytes, txtypes.BroadcastMode_BROADCAST_MODE_SYNC) + if err != nil || res.TxResponse.Code != 0 { + return res, err + } + + txHash, _ := hex.DecodeString(res.TxResponse.TxHash) + + statusPollInterval := defaultBroadcastStatusPoll + if pollInterval != nil { + statusPollInterval = *pollInterval + } + + totalAttempts := uint32(0) + t := time.NewTimer(statusPollInterval) + + for { + select { + case <-ctx.Done(): + err := errors.Wrapf(ErrTimedOut, "%s", res.TxResponse.TxHash) + t.Stop() + return nil, err + case <-t.C: + totalAttempts++ + resultTx, txErr := c.ctx.Client.Tx(ctx, txHash, false) + + if txErr != nil { + // Check if this is a fatal error that shouldn't be retried + if errRes := sdkclient.CheckCometError(txErr, txBytes); errRes != nil { + return &txtypes.BroadcastTxResponse{TxResponse: errRes}, txErr + } + + // If we've reached max retries, return error + if totalAttempts >= maxRetries { + t.Stop() + return nil, errors.Wrapf(txErr, "failed to get transaction after %d retries: %s", maxRetries, res.TxResponse.TxHash) + } + + // Continue retrying with same interval + t.Reset(statusPollInterval) + continue + } else if resultTx.Height > 0 { + resResultTx := sdk.NewResponseResultTx(resultTx, res.TxResponse.Tx, res.TxResponse.Timestamp) + res = &txtypes.BroadcastTxResponse{TxResponse: resResultTx} + t.Stop() + return res, err + } + + // Transaction not yet in block, continue polling + t.Reset(statusPollInterval) + } + } +} + +// AsyncBroadcastSignedTxWithContext broadcasts a signed transaction without waiting for inclusion in block. +func (c *chainClient) AsyncBroadcastSignedTxWithContext(ctx context.Context, txBytes []byte) (*txtypes.BroadcastTxResponse, error) { + return c.BroadcastSignedTxWithContext(ctx, txBytes, txtypes.BroadcastMode_BROADCAST_MODE_ASYNC) +} + +// BroadcastSignedTxWithContext broadcasts a signed transaction with the specified broadcast mode. +func (c *chainClient) BroadcastSignedTxWithContext(ctx context.Context, txBytes []byte, broadcastMode txtypes.BroadcastMode) (*txtypes.BroadcastTxResponse, error) { + req := txtypes.BroadcastTxRequest{ + TxBytes: txBytes, + Mode: broadcastMode, + } + + res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.txClient.BroadcastTx, &req) + if err != nil { + return nil, err + } + + return res, nil +} + +// CurrentChainGasPriceWithContext queries the current gas price from the chain with context support. +func (c *chainClient) CurrentChainGasPriceWithContext(ctx context.Context) int64 { + gasPrice := int64(client.DefaultGasPrice) + eipBaseFee, err := c.FetchEipBaseFee(ctx) + + if err != nil { + c.logger.Error("an error occurred when querying the gas price from the chain, using the default gas price") + c.logger.Debugf("error querying the gas price from chain %s", err) + } else { + if !eipBaseFee.BaseFee.BaseFee.IsNil() { + gasPrice = eipBaseFee.BaseFee.BaseFee.TruncateInt64() + } + } + + return gasPrice +} + func (c *chainClient) CurrentChainGasPrice() int64 { gasPrice := int64(client.DefaultGasPrice) eipBaseFee, err := c.FetchEipBaseFee(context.Background()) diff --git a/client/chain/chain_test_support.go b/client/chain/chain_test_support.go index 1043b40e..926a708a 100644 --- a/client/chain/chain_test_support.go +++ b/client/chain/chain_test_support.go @@ -66,35 +66,35 @@ func (c *MockChainClientV2) GetAccNonce() (accNum, accSeq uint64) { return 1, 2 } -func (c *MockChainClientV2) SimulateMsg(clientCtx client.Context, msgs ...sdk.Msg) (*txtypes.SimulateResponse, error) { +func (c *MockChainClientV2) SimulateMsg(ctx context.Context, msgs ...sdk.Msg) (*txtypes.SimulateResponse, error) { return &txtypes.SimulateResponse{}, nil } -func (c *MockChainClientV2) AsyncBroadcastMsg(msgs ...sdk.Msg) (*txtypes.BroadcastTxResponse, error) { +func (c *MockChainClientV2) AsyncBroadcastMsg(ctx context.Context, msgs ...sdk.Msg) (*txtypes.BroadcastTxResponse, error) { return &txtypes.BroadcastTxResponse{}, nil } -func (c *MockChainClientV2) SyncBroadcastMsg(msgs ...sdk.Msg) (*txtypes.BroadcastTxResponse, error) { +func (c *MockChainClientV2) SyncBroadcastMsg(ctx context.Context, pollInterval *time.Duration, maxRetries uint32, msgs ...sdk.Msg) (*txtypes.BroadcastTxResponse, error) { return &txtypes.BroadcastTxResponse{}, nil } -func (c *MockChainClientV2) BroadcastMsg(broadcastMode txtypes.BroadcastMode, msgs ...sdk.Msg) (*txtypes.BroadcastTxRequest, *txtypes.BroadcastTxResponse, error) { +func (c *MockChainClientV2) BroadcastMsg(ctx context.Context, broadcastMode txtypes.BroadcastMode, msgs ...sdk.Msg) (*txtypes.BroadcastTxRequest, *txtypes.BroadcastTxResponse, error) { return &txtypes.BroadcastTxRequest{}, &txtypes.BroadcastTxResponse{}, nil } -func (c *MockChainClientV2) BuildSignedTx(clientCtx client.Context, accNum, accSeq, initialGas uint64, gasPrice uint64, msg ...sdk.Msg) ([]byte, error) { +func (c *MockChainClientV2) BuildSignedTx(ctx context.Context, accNum, accSeq, initialGas uint64, gasPrice uint64, msg ...sdk.Msg) ([]byte, error) { return []byte(nil), nil } -func (c *MockChainClientV2) SyncBroadcastSignedTx(tyBytes []byte) (*txtypes.BroadcastTxResponse, error) { +func (c *MockChainClientV2) SyncBroadcastSignedTx(ctx context.Context, txBytes []byte, pollInterval *time.Duration, maxRetries uint32) (*txtypes.BroadcastTxResponse, error) { return &txtypes.BroadcastTxResponse{}, nil } -func (c *MockChainClientV2) AsyncBroadcastSignedTx(txBytes []byte) (*txtypes.BroadcastTxResponse, error) { +func (c *MockChainClientV2) AsyncBroadcastSignedTx(ctx context.Context, txBytes []byte) (*txtypes.BroadcastTxResponse, error) { return &txtypes.BroadcastTxResponse{}, nil } -func (c *MockChainClientV2) BroadcastSignedTx(txBytes []byte, broadcastMode txtypes.BroadcastMode) (*txtypes.BroadcastTxResponse, error) { +func (c *MockChainClientV2) BroadcastSignedTx(ctx context.Context, txBytes []byte, broadcastMode txtypes.BroadcastMode) (*txtypes.BroadcastTxResponse, error) { return &txtypes.BroadcastTxResponse{}, nil } @@ -915,7 +915,7 @@ func (c *MockChainClientV2) FetchEVMBaseFee(ctx context.Context) (*evmtypes.Quer return &evmtypes.QueryBaseFeeResponse{}, nil } -func (c *MockChainClientV2) CurrentChainGasPrice() int64 { +func (c *MockChainClientV2) CurrentChainGasPrice(ctx context.Context) int64 { return int64(injectiveclient.DefaultGasPrice) } diff --git a/client/chain/chain_test_support_v1.go b/client/chain/chain_test_support_v1.go index 1d701043..7d25932c 100644 --- a/client/chain/chain_test_support_v1.go +++ b/client/chain/chain_test_support_v1.go @@ -79,6 +79,22 @@ func (c *MockChainClient) BroadcastMsg(broadcastMode txtypes.BroadcastMode, msgs return &txtypes.BroadcastTxRequest{}, &txtypes.BroadcastTxResponse{}, nil } +func (c *MockChainClient) SimulateMsgWithContext(ctx context.Context, msgs ...sdk.Msg) (*txtypes.SimulateResponse, error) { + return &txtypes.SimulateResponse{}, nil +} + +func (c *MockChainClient) AsyncBroadcastMsgWithContext(ctx context.Context, msgs ...sdk.Msg) (*txtypes.BroadcastTxResponse, error) { + return &txtypes.BroadcastTxResponse{}, nil +} + +func (c *MockChainClient) SyncBroadcastMsgWithContext(ctx context.Context, pollInterval *time.Duration, maxRetries uint32, msgs ...sdk.Msg) (*txtypes.BroadcastTxResponse, error) { + return &txtypes.BroadcastTxResponse{}, nil +} + +func (c *MockChainClient) BroadcastMsgWithContext(ctx context.Context, broadcastMode txtypes.BroadcastMode, msgs ...sdk.Msg) (*txtypes.BroadcastTxRequest, *txtypes.BroadcastTxResponse, error) { + return &txtypes.BroadcastTxRequest{}, &txtypes.BroadcastTxResponse{}, nil +} + func (c *MockChainClient) BuildSignedTx(clientCtx client.Context, accNum, accSeq, initialGas uint64, gasPrice uint64, msg ...sdk.Msg) ([]byte, error) { return []byte(nil), nil } @@ -95,6 +111,22 @@ func (c *MockChainClient) BroadcastSignedTx(txBytes []byte, broadcastMode txtype return &txtypes.BroadcastTxResponse{}, nil } +func (c *MockChainClient) BuildSignedTxWithContext(ctx context.Context, accNum, accSeq, initialGas uint64, gasPrice uint64, msgs ...sdk.Msg) ([]byte, error) { + return []byte(nil), nil +} + +func (c *MockChainClient) SyncBroadcastSignedTxWithContext(ctx context.Context, txBytes []byte, pollInterval *time.Duration, maxRetries uint32) (*txtypes.BroadcastTxResponse, error) { + return &txtypes.BroadcastTxResponse{}, nil +} + +func (c *MockChainClient) AsyncBroadcastSignedTxWithContext(ctx context.Context, txBytes []byte) (*txtypes.BroadcastTxResponse, error) { + return &txtypes.BroadcastTxResponse{}, nil +} + +func (c *MockChainClient) BroadcastSignedTxWithContext(ctx context.Context, txBytes []byte, broadcastMode txtypes.BroadcastMode) (*txtypes.BroadcastTxResponse, error) { + return &txtypes.BroadcastTxResponse{}, nil +} + func (c *MockChainClient) QueueBroadcastMsg(msgs ...sdk.Msg) error { return nil } @@ -846,6 +878,10 @@ func (c *MockChainClient) CurrentChainGasPrice() int64 { return int64(injectiveclient.DefaultGasPrice) } +func (c *MockChainClient) CurrentChainGasPriceWithContext(ctx context.Context) int64 { + return int64(injectiveclient.DefaultGasPrice) +} + func (c *MockChainClient) SetGasPrice(gasPrice int64) { // do nothing } diff --git a/client/chain/chain_v2.go b/client/chain/chain_v2.go index d338c115..44af001f 100644 --- a/client/chain/chain_v2.go +++ b/client/chain/chain_v2.go @@ -10,7 +10,6 @@ import ( "strconv" "strings" "sync" - "sync/atomic" "time" sdkmath "cosmossdk.io/math" @@ -60,18 +59,17 @@ type ChainClientV2 interface { // return account number and sequence without increasing sequence GetAccNonce() (accNum uint64, accSeq uint64) - SimulateMsg(clientCtx sdkclient.Context, msgs ...sdk.Msg) (*txtypes.SimulateResponse, error) - AsyncBroadcastMsg(msgs ...sdk.Msg) (*txtypes.BroadcastTxResponse, error) - SyncBroadcastMsg(msgs ...sdk.Msg) (*txtypes.BroadcastTxResponse, error) - BroadcastMsg(broadcastMode txtypes.BroadcastMode, msgs ...sdk.Msg) (*txtypes.BroadcastTxRequest, *txtypes.BroadcastTxResponse, error) + SimulateMsg(ctx context.Context, msgs ...sdk.Msg) (*txtypes.SimulateResponse, error) + AsyncBroadcastMsg(ctx context.Context, msgs ...sdk.Msg) (*txtypes.BroadcastTxResponse, error) + SyncBroadcastMsg(ctx context.Context, pollInterval *time.Duration, maxRetries uint32, msgs ...sdk.Msg) (*txtypes.BroadcastTxResponse, error) + BroadcastMsg(ctx context.Context, broadcastMode txtypes.BroadcastMode, msgs ...sdk.Msg) (*txtypes.BroadcastTxRequest, *txtypes.BroadcastTxResponse, error) // Build signed tx with given accNum and accSeq, useful for offline siging // If simulate is set to false, initialGas will be used - BuildSignedTx(clientCtx sdkclient.Context, accNum, accSeq, initialGas uint64, gasPrice uint64, msg ...sdk.Msg) ([]byte, error) - SyncBroadcastSignedTx(tyBytes []byte) (*txtypes.BroadcastTxResponse, error) - AsyncBroadcastSignedTx(txBytes []byte) (*txtypes.BroadcastTxResponse, error) - BroadcastSignedTx(txBytes []byte, broadcastMode txtypes.BroadcastMode) (*txtypes.BroadcastTxResponse, error) - QueueBroadcastMsg(msgs ...sdk.Msg) error + BuildSignedTx(ctx context.Context, accNum, accSeq, initialGas uint64, gasPrice uint64, msg ...sdk.Msg) ([]byte, error) + SyncBroadcastSignedTx(ctx context.Context, txBytes []byte, pollInterval *time.Duration, maxRetries uint32) (*txtypes.BroadcastTxResponse, error) + AsyncBroadcastSignedTx(ctx context.Context, txBytes []byte) (*txtypes.BroadcastTxResponse, error) + BroadcastSignedTx(ctx context.Context, txBytes []byte, broadcastMode txtypes.BroadcastMode) (*txtypes.BroadcastTxResponse, error) // Bank Module GetBankBalances(ctx context.Context, address string) (*banktypes.QueryAllBalancesResponse, error) @@ -304,7 +302,7 @@ type ChainClientV2 interface { FetchEVMCode(ctx context.Context, address string) (*evmtypes.QueryCodeResponse, error) FetchEVMBaseFee(ctx context.Context) (*evmtypes.QueryBaseFeeResponse, error) - CurrentChainGasPrice() int64 + CurrentChainGasPrice(ctx context.Context) int64 SetGasPrice(gasPrice int64) GetNetwork() common.Network @@ -322,8 +320,6 @@ type chainClientV2 struct { chainStreamConn *grpc.ClientConn txFactory tx.Factory - doneC chan bool - msgC chan sdk.Msg syncMux *sync.Mutex cancelCtx context.Context @@ -461,8 +457,6 @@ func NewChainClientV2( txFactory: txFactory, canSign: ctx.Keyring != nil, syncMux: new(sync.Mutex), - msgC: make(chan sdk.Msg, msgCommitBatchSizeLimit), - doneC: make(chan bool, 1), cancelCtx: cancelCtx, cancelFn: cancelFn, @@ -504,7 +498,6 @@ func NewChainClientV2( return nil, errors.Errorf("Address %s is in the OFAC list", account.GetAddress()) } cc.accNum, cc.accSeq = account.GetAccountNumber(), account.GetSequence() - go cc.runBatchBroadcast() go cc.syncTimeoutHeight() } @@ -582,14 +575,11 @@ func (c *chainClientV2) Close() { if !c.canSign { return } - if atomic.CompareAndSwapInt64(&c.closed, 0, 1) { - close(c.msgC) - } if c.cancelFn != nil { c.cancelFn() } - <-c.doneC + if c.conn != nil { c.conn.Close() } @@ -698,10 +688,10 @@ func (c *chainClientV2) GetAccount(ctx context.Context, address string) (*authty return res, err } -func (c *chainClientV2) SimulateMsg(clientCtx sdkclient.Context, msgs ...sdk.Msg) (*txtypes.SimulateResponse, error) { +func (c *chainClientV2) SimulateMsg(ctx context.Context, msgs ...sdk.Msg) (*txtypes.SimulateResponse, error) { c.txFactory = c.txFactory.WithSequence(c.accSeq) c.txFactory = c.txFactory.WithAccountNumber(c.accNum) - txf, err := PrepareFactory(clientCtx, c.txFactory) + txf, err := PrepareFactory(c.ctx, c.txFactory) if err != nil { err = errors.Wrap(err, "failed to prepareFactory") return nil, err @@ -713,7 +703,6 @@ func (c *chainClientV2) SimulateMsg(clientCtx sdkclient.Context, msgs ...sdk.Msg return nil, err } - ctx := context.Background() req := &txtypes.SimulateRequest{TxBytes: simTxBytes} simRes, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.txClient.Simulate, req) @@ -725,19 +714,18 @@ func (c *chainClientV2) SimulateMsg(clientCtx sdkclient.Context, msgs ...sdk.Msg return simRes, nil } -func (c *chainClientV2) BuildSignedTx(clientCtx sdkclient.Context, accNum, accSeq, initialGas uint64, gasPrice uint64, msgs ...sdk.Msg) ([]byte, error) { - txf := NewTxFactory(clientCtx).WithSequence(accSeq).WithAccountNumber(accNum) +func (c *chainClientV2) BuildSignedTx(ctx context.Context, accNum, accSeq, initialGas uint64, gasPrice uint64, msgs ...sdk.Msg) ([]byte, error) { + txf := NewTxFactory(c.ctx).WithSequence(accSeq).WithAccountNumber(accNum) txf = txf.WithGas(initialGas) gasPriceWithDenom := fmt.Sprintf("%d%s", gasPrice, client.InjDenom) txf = txf.WithGasPrices(gasPriceWithDenom) - return c.buildSignedTx(clientCtx, txf, msgs...) + return c.buildSignedTx(ctx, txf, msgs...) } -func (c *chainClientV2) buildSignedTx(clientCtx sdkclient.Context, txf tx.Factory, msgs ...sdk.Msg) ([]byte, error) { - ctx := context.Background() - if clientCtx.Simulate { +func (c *chainClientV2) buildSignedTx(ctx context.Context, txf tx.Factory, msgs ...sdk.Msg) ([]byte, error) { + if c.ctx.Simulate { simTxBytes, err := txf.BuildSimTx(msgs...) if err != nil { err = errors.Wrap(err, "failed to build sim tx bytes") @@ -758,7 +746,7 @@ func (c *chainClientV2) buildSignedTx(clientCtx sdkclient.Context, txf tx.Factor c.gasWanted = adjustedGas } - txf, err := PrepareFactory(clientCtx, txf) + txf, err := PrepareFactory(c.ctx, txf) if err != nil { return nil, errors.Wrap(err, "failed to prepareFactory") } @@ -769,44 +757,57 @@ func (c *chainClientV2) buildSignedTx(clientCtx sdkclient.Context, txf tx.Factor return nil, err } - txn.SetFeeGranter(clientCtx.GetFeeGranterAddress()) - err = tx.Sign(ctx, txf, clientCtx.GetFromName(), txn, true) + txn.SetFeeGranter(c.ctx.GetFeeGranterAddress()) + err = tx.Sign(ctx, txf, c.ctx.GetFromName(), txn, true) if err != nil { err = errors.Wrap(err, "failed to Sign Tx") return nil, err } - return clientCtx.TxConfig.TxEncoder()(txn.GetTx()) + return c.ctx.TxConfig.TxEncoder()(txn.GetTx()) } -func (c *chainClientV2) SyncBroadcastSignedTx(txBytes []byte) (*txtypes.BroadcastTxResponse, error) { - res, err := c.BroadcastSignedTx(txBytes, txtypes.BroadcastMode_BROADCAST_MODE_SYNC) +func (c *chainClientV2) SyncBroadcastSignedTx(ctx context.Context, txBytes []byte, pollInterval *time.Duration, maxRetries uint32) (*txtypes.BroadcastTxResponse, error) { + res, err := c.BroadcastSignedTx(ctx, txBytes, txtypes.BroadcastMode_BROADCAST_MODE_SYNC) if err != nil || res.TxResponse.Code != 0 { return res, err } - awaitCtx, cancelFn := context.WithTimeout(context.Background(), defaultBroadcastTimeout) - defer cancelFn() - txHash, _ := hex.DecodeString(res.TxResponse.TxHash) - t := time.NewTimer(defaultBroadcastStatusPoll) + + statusPollInterval := defaultBroadcastStatusPoll + if pollInterval != nil { + statusPollInterval = *pollInterval + } + + totalAttempts := uint32(0) + t := time.NewTimer(statusPollInterval) for { select { - case <-awaitCtx.Done(): + case <-ctx.Done(): err := errors.Wrapf(ErrTimedOut, "%s", res.TxResponse.TxHash) t.Stop() return nil, err case <-t.C: - resultTx, err := c.ctx.Client.Tx(awaitCtx, txHash, false) - if err != nil { - if errRes := sdkclient.CheckCometError(err, txBytes); errRes != nil { - return &txtypes.BroadcastTxResponse{TxResponse: errRes}, err + totalAttempts++ + resultTx, txErr := c.ctx.Client.Tx(ctx, txHash, false) + + if txErr != nil { + // Check if this is a fatal error that shouldn't be retried + if errRes := sdkclient.CheckCometError(txErr, txBytes); errRes != nil { + return &txtypes.BroadcastTxResponse{TxResponse: errRes}, txErr } - t.Reset(defaultBroadcastStatusPoll) - continue + // If we've reached max retries, return error + if totalAttempts >= maxRetries { + t.Stop() + return nil, errors.Wrapf(txErr, "failed to get transaction after %d retries: %s", maxRetries, res.TxResponse.TxHash) + } + // Continue retrying with same interval + t.Reset(statusPollInterval) + continue } else if resultTx.Height > 0 { resResultTx := sdk.NewResponseResultTx(resultTx, res.TxResponse.Tx, res.TxResponse.Timestamp) res = &txtypes.BroadcastTxResponse{TxResponse: resResultTx} @@ -814,22 +815,22 @@ func (c *chainClientV2) SyncBroadcastSignedTx(txBytes []byte) (*txtypes.Broadcas return res, err } - t.Reset(defaultBroadcastStatusPoll) + // Transaction not yet in block, continue polling + t.Reset(statusPollInterval) } } } -func (c *chainClientV2) AsyncBroadcastSignedTx(txBytes []byte) (*txtypes.BroadcastTxResponse, error) { - return c.BroadcastSignedTx(txBytes, txtypes.BroadcastMode_BROADCAST_MODE_ASYNC) +func (c *chainClientV2) AsyncBroadcastSignedTx(ctx context.Context, txBytes []byte) (*txtypes.BroadcastTxResponse, error) { + return c.BroadcastSignedTx(ctx, txBytes, txtypes.BroadcastMode_BROADCAST_MODE_ASYNC) } -func (c *chainClientV2) BroadcastSignedTx(txBytes []byte, broadcastMode txtypes.BroadcastMode) (*txtypes.BroadcastTxResponse, error) { +func (c *chainClientV2) BroadcastSignedTx(ctx context.Context, txBytes []byte, broadcastMode txtypes.BroadcastMode) (*txtypes.BroadcastTxResponse, error) { req := txtypes.BroadcastTxRequest{ TxBytes: txBytes, Mode: broadcastMode, } - ctx := context.Background() res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.txClient.BroadcastTx, &req) if err != nil { return nil, err @@ -839,12 +840,12 @@ func (c *chainClientV2) BroadcastSignedTx(txBytes []byte, broadcastMode txtypes. } func (c *chainClientV2) broadcastTx( - clientCtx sdkclient.Context, + ctx context.Context, txf tx.Factory, broadcastMode txtypes.BroadcastMode, msgs ...sdk.Msg, ) (*txtypes.BroadcastTxRequest, *txtypes.BroadcastTxResponse, error) { - txBytes, err := c.buildSignedTx(clientCtx, txf, msgs...) + txBytes, err := c.buildSignedTx(ctx, txf, msgs...) if err != nil { err = errors.Wrap(err, "failed to build signed Tx") return nil, nil, err @@ -855,89 +856,11 @@ func (c *chainClientV2) broadcastTx( Mode: broadcastMode, } - res, err := common.ExecuteCall(context.Background(), c.network.ChainCookieAssistant, c.txClient.BroadcastTx, &req) + res, err := common.ExecuteCall(ctx, c.network.ChainCookieAssistant, c.txClient.BroadcastTx, &req) return &req, res, err } -// QueueBroadcastMsg enqueues a list of messages. Messages will added to the queue -// and grouped into Txns in chunks. Use this method to mass broadcast Txns with efficiency. -func (c *chainClientV2) QueueBroadcastMsg(msgs ...sdk.Msg) error { - if !c.canSign { - return ErrReadOnly - } else if atomic.LoadInt64(&c.closed) == 1 { - return ErrQueueClosed - } - - t := time.NewTimer(10 * time.Second) - for _, msg := range msgs { - select { - case <-t.C: - return ErrEnqueueTimeout - case c.msgC <- msg: - } - } - t.Stop() - - return nil -} - -func (c *chainClientV2) runBatchBroadcast() { - expirationTimer := time.NewTimer(msgCommitBatchTimeLimit) - msgBatch := make([]sdk.Msg, 0, msgCommitBatchSizeLimit) - - submitBatch := func(toSubmit []sdk.Msg) { - res, err := c.SyncBroadcastMsg(toSubmit...) - - if err != nil { - c.logger.WithError(err) - } else { - if res.TxResponse.Code != 0 { - err = errors.Errorf("error %d (%s): %s", res.TxResponse.Code, res.TxResponse.Codespace, res.TxResponse.RawLog) - c.logger.WithField("txHash", res.TxResponse.TxHash).WithError(err).Errorln("failed to broadcast messages batch") - } else { - c.logger.WithField("txHash", res.TxResponse.TxHash).Debugln("msg batch broadcasted successfully at height", res.TxResponse.Height) - } - } - - c.logger.Debugln("gas wanted: ", c.gasWanted) - } - - for { - select { - case msg, ok := <-c.msgC: - if !ok { - // exit required - if len(msgBatch) > 0 { - submitBatch(msgBatch) - } - - close(c.doneC) - return - } - - msgBatch = append(msgBatch, msg) - - if len(msgBatch) >= msgCommitBatchSizeLimit { - toSubmit := msgBatch - msgBatch = msgBatch[:0] - expirationTimer.Reset(msgCommitBatchTimeLimit) - - submitBatch(toSubmit) - } - case <-expirationTimer.C: - if len(msgBatch) > 0 { - toSubmit := msgBatch - msgBatch = msgBatch[:0] - expirationTimer.Reset(msgCommitBatchTimeLimit) - submitBatch(toSubmit) - } else { - expirationTimer.Reset(msgCommitBatchTimeLimit) - } - } - } -} - func (c *chainClientV2) GetGasFee() (string, error) { gasPrices := strings.TrimSuffix(c.txFactory.GasPrices().String(), client.InjDenom) @@ -2681,35 +2604,48 @@ func (c *chainClientV2) FetchEVMBaseFee(ctx context.Context) (*evmtypes.QueryBas } // SyncBroadcastMsg sends Tx to chain and waits until Tx is included in block. -func (c *chainClientV2) SyncBroadcastMsg(msgs ...sdk.Msg) (*txtypes.BroadcastTxResponse, error) { - req, res, err := c.BroadcastMsg(txtypes.BroadcastMode_BROADCAST_MODE_SYNC, msgs...) +func (c *chainClientV2) SyncBroadcastMsg(ctx context.Context, pollInterval *time.Duration, maxRetries uint32, msgs ...sdk.Msg) (*txtypes.BroadcastTxResponse, error) { + req, res, err := c.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, msgs...) if err != nil || res.TxResponse.Code != 0 { return res, err } - awaitCtx, cancelFn := context.WithTimeout(context.Background(), defaultBroadcastTimeout) - defer cancelFn() - txHash, _ := hex.DecodeString(res.TxResponse.TxHash) - t := time.NewTimer(defaultBroadcastStatusPoll) + + statusPollInterval := defaultBroadcastStatusPoll + if pollInterval != nil { + statusPollInterval = *pollInterval + } + + totalAttempts := uint32(0) + t := time.NewTimer(statusPollInterval) for { select { - case <-awaitCtx.Done(): + case <-ctx.Done(): err := errors.Wrapf(ErrTimedOut, "%s", res.TxResponse.TxHash) t.Stop() return nil, err case <-t.C: - resultTx, err := c.ctx.Client.Tx(awaitCtx, txHash, false) - if err != nil { - if errRes := sdkclient.CheckCometError(err, req.TxBytes); errRes != nil { - return &txtypes.BroadcastTxResponse{TxResponse: errRes}, err + totalAttempts++ + resultTx, txErr := c.ctx.Client.Tx(ctx, txHash, false) + + if txErr != nil { + // Check if this is a fatal error that shouldn't be retried + if errRes := sdkclient.CheckCometError(txErr, req.TxBytes); errRes != nil { + return &txtypes.BroadcastTxResponse{TxResponse: errRes}, txErr } - t.Reset(defaultBroadcastStatusPoll) - continue + // If we've reached max retries, return error + if totalAttempts >= maxRetries { + t.Stop() + return nil, errors.Wrapf(txErr, "failed to get transaction after %d retries: %s", maxRetries, res.TxResponse.TxHash) + } + // Continue retrying with same interval + t.Reset(statusPollInterval) + continue } else if resultTx.Height > 0 { resResultTx := sdk.NewResponseResultTx(resultTx, res.TxResponse.Tx, res.TxResponse.Timestamp) res = &txtypes.BroadcastTxResponse{TxResponse: resResultTx} @@ -2717,7 +2653,8 @@ func (c *chainClientV2) SyncBroadcastMsg(msgs ...sdk.Msg) (*txtypes.BroadcastTxR return res, err } - t.Reset(defaultBroadcastStatusPoll) + // Transaction not yet in block, continue polling + t.Reset(statusPollInterval) } } } @@ -2725,21 +2662,21 @@ func (c *chainClientV2) SyncBroadcastMsg(msgs ...sdk.Msg) (*txtypes.BroadcastTxR // AsyncBroadcastMsg sends Tx to chain and doesn't wait until Tx is included in block. This method // cannot be used for rapid Tx sending, it is expected that you wait for transaction status with // external tools. If you want sdk to wait for it, use SyncBroadcastMsg. -func (c *chainClientV2) AsyncBroadcastMsg(msgs ...sdk.Msg) (*txtypes.BroadcastTxResponse, error) { - _, res, err := c.BroadcastMsg(txtypes.BroadcastMode_BROADCAST_MODE_ASYNC, msgs...) +func (c *chainClientV2) AsyncBroadcastMsg(ctx context.Context, msgs ...sdk.Msg) (*txtypes.BroadcastTxResponse, error) { + _, res, err := c.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_ASYNC, msgs...) return res, err } // BroadcastMsg submits a group of messages in one transaction to the chain // The function uses the broadcast mode specified with the broadcastMode parameter -func (c *chainClientV2) BroadcastMsg(broadcastMode txtypes.BroadcastMode, msgs ...sdk.Msg) (*txtypes.BroadcastTxRequest, *txtypes.BroadcastTxResponse, error) { +func (c *chainClientV2) BroadcastMsg(ctx context.Context, broadcastMode txtypes.BroadcastMode, msgs ...sdk.Msg) (*txtypes.BroadcastTxRequest, *txtypes.BroadcastTxResponse, error) { c.syncMux.Lock() defer c.syncMux.Unlock() sequence := c.getAccSeq() c.txFactory = c.txFactory.WithSequence(sequence) c.txFactory = c.txFactory.WithAccountNumber(c.accNum) - req, res, err := c.broadcastTx(c.ctx, c.txFactory, broadcastMode, msgs...) + req, res, err := c.broadcastTx(ctx, c.txFactory, broadcastMode, msgs...) if err != nil { if c.opts.ShouldFixSequenceMismatch && strings.Contains(err.Error(), "account sequence mismatch") { c.syncNonce() @@ -2747,7 +2684,7 @@ func (c *chainClientV2) BroadcastMsg(broadcastMode txtypes.BroadcastMode, msgs . c.txFactory = c.txFactory.WithSequence(sequence) c.txFactory = c.txFactory.WithAccountNumber(c.accNum) c.logger.Debugln("retrying broadcastTx with nonce", sequence) - req, res, err = c.broadcastTx(c.ctx, c.txFactory, broadcastMode, msgs...) + req, res, err = c.broadcastTx(ctx, c.txFactory, broadcastMode, msgs...) } if err != nil { resJSON, _ := json.MarshalIndent(res, "", "\t") @@ -2882,9 +2819,9 @@ func (c *chainClientV2) ComputeOrderHashes(spotOrders []exchangev2types.SpotOrde return orderHashes, nil } -func (c *chainClientV2) CurrentChainGasPrice() int64 { +func (c *chainClientV2) CurrentChainGasPrice(ctx context.Context) int64 { gasPrice := int64(client.DefaultGasPrice) - eipBaseFee, err := c.FetchEipBaseFee(context.Background()) + eipBaseFee, err := c.FetchEipBaseFee(ctx) if err != nil { c.logger.Error("an error occurred when querying the gas price from the chain, using the default gas price") diff --git a/examples/chain/13_BroadcastMsgWithoutSimulation/example.go b/examples/chain/13_BroadcastMsgWithoutSimulation/example.go index 79f676df..a9401f8a 100644 --- a/examples/chain/13_BroadcastMsgWithoutSimulation/example.go +++ b/examples/chain/13_BroadcastMsgWithoutSimulation/example.go @@ -1,9 +1,11 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" txtypes "github.com/cosmos/cosmos-sdk/types/tx" @@ -60,7 +62,10 @@ func main() { panic(err) } - gasPrice := clientInstance.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := clientInstance.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) clientInstance.SetGasPrice(gasPrice) @@ -88,7 +93,7 @@ func main() { msg.Sender = senderAddress.String() msg.Order = *order - _, response, err := clientInstance.BroadcastMsg(txtypes.BroadcastMode_BROADCAST_MODE_SYNC, msg) + _, response, err := clientInstance.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, msg) if err != nil { panic(err) @@ -97,7 +102,7 @@ func main() { str, _ := json.MarshalIndent(response, "", "\t") fmt.Print(string(str)) - gasPrice = clientInstance.CurrentChainGasPrice() + gasPrice = clientInstance.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) clientInstance.SetGasPrice(gasPrice) diff --git a/examples/chain/1_LocalOrderHash/example.go b/examples/chain/1_LocalOrderHash/example.go index 785f94e8..42216c66 100644 --- a/examples/chain/1_LocalOrderHash/example.go +++ b/examples/chain/1_LocalOrderHash/example.go @@ -1,11 +1,14 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" "github.com/google/uuid" "github.com/shopspring/decimal" @@ -56,7 +59,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -89,13 +95,15 @@ func main() { }, ) - msg := new(exchangev2types.MsgBatchCreateSpotLimitOrders) - msg.Sender = senderAddress.String() - msg.Orders = []exchangev2types.SpotOrder{*spotOrder} + msg := exchangev2types.MsgBatchCreateSpotLimitOrders{ + Sender: senderAddress.String(), + Orders: []exchangev2types.SpotOrder{*spotOrder}, + } - msg1 := new(exchangev2types.MsgBatchCreateDerivativeLimitOrders) - msg1.Sender = senderAddress.String() - msg1.Orders = []exchangev2types.DerivativeOrder{*derivativeOrder} + msg1 := exchangev2types.MsgBatchCreateDerivativeLimitOrders{ + Sender: senderAddress.String(), + Orders: []exchangev2types.DerivativeOrder{*derivativeOrder}, + } // compute local order hashes orderHashes, err := chainClient.ComputeOrderHashes(msg.Orders, msg1.Orders, defaultSubaccountID) @@ -108,29 +116,16 @@ func main() { fmt.Println("computed derivative order hashes: ", orderHashes.Derivative) // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg, msg1) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg, &msg1) if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") - - gasPrice = chainClient.CurrentChainGasPrice() - // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted - gasPrice = int64(float64(gasPrice) * 1.1) - chainClient.SetGasPrice(gasPrice) + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/2_MsgBatchCancelSpotOrders/example.go b/examples/chain/2_MsgBatchCancelSpotOrders/example.go index fd06f500..28d39f85 100644 --- a/examples/chain/2_MsgBatchCancelSpotOrders/example.go +++ b/examples/chain/2_MsgBatchCancelSpotOrders/example.go @@ -1,15 +1,18 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" + exchangev2types "github.com/InjectiveLabs/sdk-go/chain/exchange/types/v2" chainclient "github.com/InjectiveLabs/sdk-go/client/chain" "github.com/InjectiveLabs/sdk-go/client/common" - rpchttp "github.com/cometbft/cometbft/rpc/client/http" - cosmtypes "github.com/cosmos/cosmos-sdk/types" ) func main() { @@ -54,7 +57,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -75,30 +81,22 @@ func main() { Cid: cid, }) - msg := new(exchangev2types.MsgBatchCancelSpotOrders) - msg.Sender = senderAddress.String() - msg.Data = []exchangev2types.OrderData{*orderWithHash, *orderWithCid} - CosMsgs := []cosmtypes.Msg{msg} - - // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(CosMsgs...) - - if err != nil { - fmt.Println(err) + msg := exchangev2types.MsgBatchCancelSpotOrders{ + Sender: senderAddress.String(), + Data: []exchangev2types.OrderData{*orderWithHash, *orderWithCid}, } - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() + // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/3_MsgBatchCancelDerivativeOrders/example.go b/examples/chain/3_MsgBatchCancelDerivativeOrders/example.go index db4c17d3..0497ebe1 100644 --- a/examples/chain/3_MsgBatchCancelDerivativeOrders/example.go +++ b/examples/chain/3_MsgBatchCancelDerivativeOrders/example.go @@ -1,12 +1,14 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" - cosmtypes "github.com/cosmos/cosmos-sdk/types" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" exchangev2types "github.com/InjectiveLabs/sdk-go/chain/exchange/types/v2" chainclient "github.com/InjectiveLabs/sdk-go/client/chain" @@ -55,7 +57,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -76,30 +81,22 @@ func main() { Cid: cid, }) - msg := new(exchangev2types.MsgBatchCancelDerivativeOrders) - msg.Sender = senderAddress.String() - msg.Data = []exchangev2types.OrderData{*orderWithHash, *orderWithCid} - CosMsgs := []cosmtypes.Msg{msg} - - // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(CosMsgs...) - - if err != nil { - fmt.Println(err) + msg := exchangev2types.MsgBatchCancelDerivativeOrders{ + Sender: senderAddress.String(), + Data: []exchangev2types.OrderData{*orderWithHash, *orderWithCid}, } - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() + // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/4_MsgBatchCreateSpotLimitOrders/example.go b/examples/chain/4_MsgBatchCreateSpotLimitOrders/example.go index df3a633f..d66b85f3 100644 --- a/examples/chain/4_MsgBatchCreateSpotLimitOrders/example.go +++ b/examples/chain/4_MsgBatchCreateSpotLimitOrders/example.go @@ -1,11 +1,14 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" "github.com/google/uuid" "github.com/shopspring/decimal" @@ -58,7 +61,10 @@ func main() { return } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -79,47 +85,22 @@ func main() { MarketId: marketId, Cid: uuid.NewString(), }) - msg := new(exchangev2types.MsgBatchCreateSpotLimitOrders) - msg.Sender = senderAddress.String() - msg.Orders = []exchangev2types.SpotOrder{*order} - - simRes, err := chainClient.SimulateMsg(clientCtx, msg) - - if err != nil { - fmt.Println(err) - return - } - - msgBatchCreateSpotLimitOrdersResponse := exchangev2types.MsgBatchCreateSpotLimitOrdersResponse{} - err = msgBatchCreateSpotLimitOrdersResponse.Unmarshal(simRes.Result.MsgResponses[0].Value) - - if err != nil { - fmt.Println(err) - return + msg := exchangev2types.MsgBatchCreateSpotLimitOrders{ + Sender: senderAddress.String(), + Orders: []exchangev2types.SpotOrder{*order}, } - fmt.Println("simulated order hashes", msgBatchCreateSpotLimitOrdersResponse.OrderHashes) - // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - return - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/5_MsgBatchCreateDerivativeLimitOrders/example.go b/examples/chain/5_MsgBatchCreateDerivativeLimitOrders/example.go index e2535fbd..bd827906 100644 --- a/examples/chain/5_MsgBatchCreateDerivativeLimitOrders/example.go +++ b/examples/chain/5_MsgBatchCreateDerivativeLimitOrders/example.go @@ -1,11 +1,14 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" "github.com/google/uuid" "github.com/shopspring/decimal" @@ -58,7 +61,10 @@ func main() { return } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -84,47 +90,22 @@ func main() { }, ) - msg := new(exchangev2types.MsgBatchCreateDerivativeLimitOrders) - msg.Sender = senderAddress.String() - msg.Orders = []exchangev2types.DerivativeOrder{*order} - - simRes, err := chainClient.SimulateMsg(clientCtx, msg) - - if err != nil { - fmt.Println(err) - return - } - - msgBatchCreateDerivativeLimitOrdersResponse := exchangev2types.MsgBatchCreateDerivativeLimitOrdersResponse{} - err = msgBatchCreateDerivativeLimitOrdersResponse.Unmarshal(simRes.Result.MsgResponses[0].Value) - - if err != nil { - fmt.Println(err) - return + msg := exchangev2types.MsgBatchCreateDerivativeLimitOrders{ + Sender: senderAddress.String(), + Orders: []exchangev2types.DerivativeOrder{*order}, } - fmt.Println("simulated order hashes", msgBatchCreateDerivativeLimitOrdersResponse.OrderHashes) - // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - return - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/6_MsgRegisterAsDMM/example.go b/examples/chain/6_MsgRegisterAsDMM/example.go index 0b251797..a51afc2c 100644 --- a/examples/chain/6_MsgRegisterAsDMM/example.go +++ b/examples/chain/6_MsgRegisterAsDMM/example.go @@ -1,11 +1,14 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" exchangev2types "github.com/InjectiveLabs/sdk-go/chain/exchange/types/v2" chainclient "github.com/InjectiveLabs/sdk-go/client/chain" @@ -54,34 +57,29 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) - msg := &exchangev2types.MsgRewardsOptOut{ + msg := exchangev2types.MsgRewardsOptOut{ Sender: senderAddress.String(), } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/8_OfflineSigning/example.go b/examples/chain/8_OfflineSigning/example.go index a62c504b..2ff52462 100644 --- a/examples/chain/8_OfflineSigning/example.go +++ b/examples/chain/8_OfflineSigning/example.go @@ -2,9 +2,11 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" txtypes "github.com/cosmos/cosmos-sdk/types/tx" @@ -66,7 +68,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -92,7 +97,7 @@ func main() { msg.Order = *order accNum, accSeq := chainClient.GetAccNonce() - signedTx, err := chainClient.BuildSignedTx(clientCtx, accNum, accSeq, 20000, client.DefaultGasPrice, msg) + signedTx, err := chainClient.BuildSignedTx(ctx, accNum, accSeq, 20000, client.DefaultGasPrice, msg) if err != nil { panic(err) } @@ -104,7 +109,7 @@ func main() { } // Broadcast the signed tx using BroadcastSignedTx, AsyncBroadcastSignedTx, or SyncBroadcastSignedTx - response, err := chainClient.BroadcastSignedTx(signedTx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC) + response, err := chainClient.BroadcastSignedTx(ctx, signedTx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC) if err != nil { panic(err) } @@ -115,7 +120,7 @@ func main() { str, _ := json.MarshalIndent(response, "", "\t") fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/auction/1_MsgBid/example.go b/examples/chain/auction/1_MsgBid/example.go index addb3cdb..eea39676 100644 --- a/examples/chain/auction/1_MsgBid/example.go +++ b/examples/chain/auction/1_MsgBid/example.go @@ -1,6 +1,8 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" @@ -8,6 +10,7 @@ import ( "cosmossdk.io/math" rpchttp "github.com/cometbft/cometbft/rpc/client/http" sdktypes "github.com/cosmos/cosmos-sdk/types" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" auctiontypes "github.com/InjectiveLabs/sdk-go/chain/auction/types" chainclient "github.com/InjectiveLabs/sdk-go/client/chain" @@ -56,7 +59,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -66,31 +72,23 @@ func main() { Denom: "inj", Amount: math.NewInt(1000000000000000000), // 1 INJ } - msg := &auctiontypes.MsgBid{ + msg := auctiontypes.MsgBid{ Sender: senderAddress.String(), Round: round, BidAmount: bidAmount, } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/authz/1_MsgGrant/example.go b/examples/chain/authz/1_MsgGrant/example.go index 26b1f2ba..15d76e82 100644 --- a/examples/chain/authz/1_MsgGrant/example.go +++ b/examples/chain/authz/1_MsgGrant/example.go @@ -1,11 +1,14 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" chainclient "github.com/InjectiveLabs/sdk-go/client/chain" "github.com/InjectiveLabs/sdk-go/client/common" @@ -53,7 +56,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -77,24 +83,16 @@ func main() { ) // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, msg) if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/authz/2_MsgExec/example.go b/examples/chain/authz/2_MsgExec/example.go index 80570a37..90e07b8a 100644 --- a/examples/chain/authz/2_MsgExec/example.go +++ b/examples/chain/authz/2_MsgExec/example.go @@ -1,6 +1,8 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" @@ -8,6 +10,7 @@ import ( rpchttp "github.com/cometbft/cometbft/rpc/client/http" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" authztypes "github.com/cosmos/cosmos-sdk/x/authz" "github.com/shopspring/decimal" @@ -74,7 +77,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -109,30 +115,22 @@ func main() { msg0Any := &codectypes.Any{} msg0Any.TypeUrl = sdk.MsgTypeURL(&msg0) msg0Any.Value = msg0Bytes - msg := &authztypes.MsgExec{ + msg := authztypes.MsgExec{ Grantee: grantee, Msgs: []*codectypes.Any{msg0Any}, } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/authz/3_MsgRevoke/example.go b/examples/chain/authz/3_MsgRevoke/example.go index 03636e2b..a3fae58d 100644 --- a/examples/chain/authz/3_MsgRevoke/example.go +++ b/examples/chain/authz/3_MsgRevoke/example.go @@ -1,11 +1,14 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" authztypes "github.com/cosmos/cosmos-sdk/x/authz" chainclient "github.com/InjectiveLabs/sdk-go/client/chain" @@ -54,7 +57,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -62,31 +68,23 @@ func main() { grantee := "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r" msgType := "/injective.exchange.v1beta1.MsgCreateSpotLimitOrder" - msg := &authztypes.MsgRevoke{ + msg := authztypes.MsgRevoke{ Granter: senderAddress.String(), Grantee: grantee, MsgTypeUrl: msgType, } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/bank/1_MsgSend/example.go b/examples/chain/bank/1_MsgSend/example.go index 330f158a..61c35603 100644 --- a/examples/chain/bank/1_MsgSend/example.go +++ b/examples/chain/bank/1_MsgSend/example.go @@ -1,6 +1,8 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" @@ -8,6 +10,7 @@ import ( "cosmossdk.io/math" rpchttp "github.com/cometbft/cometbft/rpc/client/http" sdktypes "github.com/cosmos/cosmos-sdk/types" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" chainclient "github.com/InjectiveLabs/sdk-go/client/chain" @@ -55,13 +58,16 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) // prepare tx msg - msg := &banktypes.MsgSend{ + msg := banktypes.MsgSend{ FromAddress: senderAddress.String(), ToAddress: "inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r", Amount: []sdktypes.Coin{{ @@ -70,24 +76,16 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/bank/2_MsgMultiSend/example.go b/examples/chain/bank/2_MsgMultiSend/example.go index b30dac0c..7ff99c6f 100644 --- a/examples/chain/bank/2_MsgMultiSend/example.go +++ b/examples/chain/bank/2_MsgMultiSend/example.go @@ -1,6 +1,8 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" @@ -8,6 +10,7 @@ import ( "cosmossdk.io/math" rpchttp "github.com/cometbft/cometbft/rpc/client/http" sdktypes "github.com/cosmos/cosmos-sdk/types" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" chainclient "github.com/InjectiveLabs/sdk-go/client/chain" @@ -58,14 +61,17 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) // prepare tx msg - msg := &banktypes.MsgMultiSend{ + msg := banktypes.MsgMultiSend{ Inputs: []banktypes.Input{ { Address: senderAddress.String(), @@ -97,24 +103,16 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/distribution/1_SetWithdrawAddress/example.go b/examples/chain/distribution/1_SetWithdrawAddress/example.go index ef35d141..9d360e81 100644 --- a/examples/chain/distribution/1_SetWithdrawAddress/example.go +++ b/examples/chain/distribution/1_SetWithdrawAddress/example.go @@ -1,9 +1,11 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" "github.com/cosmos/cosmos-sdk/x/distribution/types" @@ -54,7 +56,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -67,7 +72,7 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - response, err := chainClient.AsyncBroadcastMsg(msg) + response, err := chainClient.AsyncBroadcastMsg(ctx, msg) if err != nil { panic(err) @@ -76,7 +81,7 @@ func main() { str, _ := json.MarshalIndent(response, "", "\t") fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/distribution/2_MsgWithdrawDelegatorReward/example.go b/examples/chain/distribution/2_MsgWithdrawDelegatorReward/example.go index 462298ac..cdb809d6 100644 --- a/examples/chain/distribution/2_MsgWithdrawDelegatorReward/example.go +++ b/examples/chain/distribution/2_MsgWithdrawDelegatorReward/example.go @@ -1,11 +1,14 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" chainclient "github.com/InjectiveLabs/sdk-go/client/chain" @@ -54,34 +57,30 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) - msg := new(distributiontypes.MsgWithdrawDelegatorReward) - msg.DelegatorAddress = senderAddress.String() - msg.ValidatorAddress = "injvaloper14gy4acwjm96wd20awm9ar6j54lev5p7espy9ug" - - // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) - - if err != nil { - fmt.Println(err) + msg := distributiontypes.MsgWithdrawDelegatorReward{ + DelegatorAddress: senderAddress.String(), + ValidatorAddress: "injvaloper14gy4acwjm96wd20awm9ar6j54lev5p7espy9ug", } - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() + // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/distribution/3_WithdrawValidatorCommission/example.go b/examples/chain/distribution/3_WithdrawValidatorCommission/example.go index 3f8d4fee..3f94b6a1 100644 --- a/examples/chain/distribution/3_WithdrawValidatorCommission/example.go +++ b/examples/chain/distribution/3_WithdrawValidatorCommission/example.go @@ -1,9 +1,11 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" "github.com/cosmos/cosmos-sdk/x/distribution/types" @@ -54,7 +56,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -66,7 +71,7 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - response, err := chainClient.AsyncBroadcastMsg(msg) + response, err := chainClient.AsyncBroadcastMsg(ctx, msg) if err != nil { panic(err) @@ -75,7 +80,7 @@ func main() { str, _ := json.MarshalIndent(response, "", "\t") fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/distribution/4_FundCommunityPool/example.go b/examples/chain/distribution/4_FundCommunityPool/example.go index 0dd2d8d1..83ef8209 100644 --- a/examples/chain/distribution/4_FundCommunityPool/example.go +++ b/examples/chain/distribution/4_FundCommunityPool/example.go @@ -1,9 +1,11 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "time" "cosmossdk.io/math" rpchttp "github.com/cometbft/cometbft/rpc/client/http" @@ -56,7 +58,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -69,7 +74,7 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - response, err := chainClient.AsyncBroadcastMsg(msg) + response, err := chainClient.AsyncBroadcastMsg(ctx, msg) if err != nil { panic(err) @@ -78,7 +83,7 @@ func main() { str, _ := json.MarshalIndent(response, "", "\t") fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/erc20/1_CreateTokenPair/example.go b/examples/chain/erc20/1_CreateTokenPair/example.go index de10f5c2..093d7b06 100644 --- a/examples/chain/erc20/1_CreateTokenPair/example.go +++ b/examples/chain/erc20/1_CreateTokenPair/example.go @@ -1,11 +1,14 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" erc20types "github.com/InjectiveLabs/sdk-go/chain/erc20/types" chainclient "github.com/InjectiveLabs/sdk-go/client/chain" @@ -52,7 +55,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -60,7 +66,7 @@ func main() { usdtDenom := "factory/inj10vkkttgxdeqcgeppu20x9qtyvuaxxev8qh0awq/usdt" usdtERC20 := "0xdAC17F958D2ee523a2206206994597C13D831ec7" - msg := &erc20types.MsgCreateTokenPair{ + msg := erc20types.MsgCreateTokenPair{ Sender: senderAddress.String(), TokenPair: erc20types.TokenPair{ BankDenom: usdtDenom, @@ -69,24 +75,16 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/erc20/2_DeleteTokenPair/example.go b/examples/chain/erc20/2_DeleteTokenPair/example.go index 7c6bcdb2..ad3d66cf 100644 --- a/examples/chain/erc20/2_DeleteTokenPair/example.go +++ b/examples/chain/erc20/2_DeleteTokenPair/example.go @@ -1,11 +1,14 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" erc20types "github.com/InjectiveLabs/sdk-go/chain/erc20/types" chainclient "github.com/InjectiveLabs/sdk-go/client/chain" @@ -52,37 +55,32 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) usdtDenom := "factory/inj10vkkttgxdeqcgeppu20x9qtyvuaxxev8qh0awq/usdt" - msg := &erc20types.MsgDeleteTokenPair{ + msg := erc20types.MsgDeleteTokenPair{ Sender: senderAddress.String(), BankDenom: usdtDenom, } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/exchange/10_MsgCreateDerivativeLimitOrder/example.go b/examples/chain/exchange/10_MsgCreateDerivativeLimitOrder/example.go index 714a46aa..9f2a8c35 100644 --- a/examples/chain/exchange/10_MsgCreateDerivativeLimitOrder/example.go +++ b/examples/chain/exchange/10_MsgCreateDerivativeLimitOrder/example.go @@ -1,11 +1,14 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" "github.com/google/uuid" "github.com/shopspring/decimal" @@ -56,7 +59,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -82,44 +88,22 @@ func main() { }, ) - msg := new(exchangev2types.MsgCreateDerivativeLimitOrder) - msg.Sender = senderAddress.String() - msg.Order = *order - - simRes, err := chainClient.SimulateMsg(clientCtx, msg) - - if err != nil { - panic(err) + msg := exchangev2types.MsgCreateDerivativeLimitOrder{ + Sender: senderAddress.String(), + Order: *order, } - msgCreateDerivativeLimitOrderResponse := exchangev2types.MsgCreateDerivativeLimitOrderResponse{} - err = msgCreateDerivativeLimitOrderResponse.Unmarshal(simRes.Result.MsgResponses[0].Value) - - if err != nil { - panic(err) - } - - fmt.Println("simulated order hash", msgCreateDerivativeLimitOrderResponse.OrderHash) - // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) - - if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/exchange/11_MsgCreateDerivativeMarketOrder/example.go b/examples/chain/exchange/11_MsgCreateDerivativeMarketOrder/example.go index 08f7b518..eb4e1805 100644 --- a/examples/chain/exchange/11_MsgCreateDerivativeMarketOrder/example.go +++ b/examples/chain/exchange/11_MsgCreateDerivativeMarketOrder/example.go @@ -1,11 +1,14 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" "github.com/google/uuid" "github.com/shopspring/decimal" @@ -57,7 +60,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -83,45 +89,22 @@ func main() { }, ) - msg := new(exchangev2types.MsgCreateDerivativeMarketOrder) - msg.Sender = senderAddress.String() - msg.Order = *order - - simRes, err := chainClient.SimulateMsg(clientCtx, msg) - - if err != nil { - panic(err) + msg := exchangev2types.MsgCreateDerivativeMarketOrder{ + Sender: senderAddress.String(), + Order: *order, } - msgCreateDerivativeMarketOrderResponse := exchangev2types.MsgCreateDerivativeMarketOrderResponse{} - err = msgCreateDerivativeMarketOrderResponse.Unmarshal(simRes.Result.MsgResponses[0].Value) - - if err != nil { - panic(err) - } - - fmt.Println("simulated order hash", msgCreateDerivativeMarketOrderResponse.OrderHash) - // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - return - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/exchange/12_MsgCancelDerivativeOrder/example.go b/examples/chain/exchange/12_MsgCancelDerivativeOrder/example.go index 19579f6e..015d6713 100644 --- a/examples/chain/exchange/12_MsgCancelDerivativeOrder/example.go +++ b/examples/chain/exchange/12_MsgCancelDerivativeOrder/example.go @@ -1,11 +1,14 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" exchangev2types "github.com/InjectiveLabs/sdk-go/chain/exchange/types/v2" chainclient "github.com/InjectiveLabs/sdk-go/client/chain" @@ -54,12 +57,15 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) - msg := &exchangev2types.MsgCancelDerivativeOrder{ + msg := exchangev2types.MsgCancelDerivativeOrder{ Sender: senderAddress.String(), MarketId: "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce", SubaccountId: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000", @@ -67,24 +73,16 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/exchange/13_MsgInstantBinaryOptionsMarketLaunch/example.go b/examples/chain/exchange/13_MsgInstantBinaryOptionsMarketLaunch/example.go index 7f113d2e..1641073b 100644 --- a/examples/chain/exchange/13_MsgInstantBinaryOptionsMarketLaunch/example.go +++ b/examples/chain/exchange/13_MsgInstantBinaryOptionsMarketLaunch/example.go @@ -1,9 +1,11 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "time" "cosmossdk.io/math" rpchttp "github.com/cometbft/cometbft/rpc/client/http" @@ -55,7 +57,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -81,7 +86,7 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - response, err := chainClient.AsyncBroadcastMsg(msg) + response, err := chainClient.AsyncBroadcastMsg(ctx, msg) if err != nil { panic(err) @@ -90,7 +95,7 @@ func main() { str, _ := json.MarshalIndent(response, "", "\t") fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/exchange/14_MsgSubaccountTransfer/example.go b/examples/chain/exchange/14_MsgSubaccountTransfer/example.go index 79c2c034..34b1af1e 100644 --- a/examples/chain/exchange/14_MsgSubaccountTransfer/example.go +++ b/examples/chain/exchange/14_MsgSubaccountTransfer/example.go @@ -1,6 +1,8 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" @@ -8,6 +10,7 @@ import ( "cosmossdk.io/math" rpchttp "github.com/cometbft/cometbft/rpc/client/http" sdktypes "github.com/cosmos/cosmos-sdk/types" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" exchangev2types "github.com/InjectiveLabs/sdk-go/chain/exchange/types/v2" chainclient "github.com/InjectiveLabs/sdk-go/client/chain" @@ -56,12 +59,15 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) - msg := &exchangev2types.MsgSubaccountTransfer{ + msg := exchangev2types.MsgSubaccountTransfer{ Sender: senderAddress.String(), SourceSubaccountId: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000", DestinationSubaccountId: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000001", @@ -71,24 +77,16 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/exchange/15_MsgExternalTransfer/example.go b/examples/chain/exchange/15_MsgExternalTransfer/example.go index f70efb48..b6de7e1c 100644 --- a/examples/chain/exchange/15_MsgExternalTransfer/example.go +++ b/examples/chain/exchange/15_MsgExternalTransfer/example.go @@ -1,6 +1,8 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" @@ -8,6 +10,7 @@ import ( "cosmossdk.io/math" rpchttp "github.com/cometbft/cometbft/rpc/client/http" sdktypes "github.com/cosmos/cosmos-sdk/types" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" exchangev2types "github.com/InjectiveLabs/sdk-go/chain/exchange/types/v2" chainclient "github.com/InjectiveLabs/sdk-go/client/chain" @@ -56,12 +59,15 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) - msg := &exchangev2types.MsgExternalTransfer{ + msg := exchangev2types.MsgExternalTransfer{ Sender: senderAddress.String(), SourceSubaccountId: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000", DestinationSubaccountId: "0xbdaedec95d563fb05240d6e01821008454c24c36000000000000000000000000", @@ -71,24 +77,16 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/exchange/16_MsgLiquidatePosition/example.go b/examples/chain/exchange/16_MsgLiquidatePosition/example.go index f72921d5..f4050817 100644 --- a/examples/chain/exchange/16_MsgLiquidatePosition/example.go +++ b/examples/chain/exchange/16_MsgLiquidatePosition/example.go @@ -1,9 +1,11 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" "github.com/google/uuid" @@ -56,7 +58,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -89,7 +94,7 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - response, err := chainClient.AsyncBroadcastMsg(msg) + response, err := chainClient.AsyncBroadcastMsg(ctx, msg) if err != nil { panic(err) @@ -98,7 +103,7 @@ func main() { str, _ := json.MarshalIndent(response, "", "\t") fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/exchange/17_MsgIncreasePositionMargin/example.go b/examples/chain/exchange/17_MsgIncreasePositionMargin/example.go index 909bd68e..fdaa146f 100644 --- a/examples/chain/exchange/17_MsgIncreasePositionMargin/example.go +++ b/examples/chain/exchange/17_MsgIncreasePositionMargin/example.go @@ -1,12 +1,15 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" "cosmossdk.io/math" rpchttp "github.com/cometbft/cometbft/rpc/client/http" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" exchangev2types "github.com/InjectiveLabs/sdk-go/chain/exchange/types/v2" chainclient "github.com/InjectiveLabs/sdk-go/client/chain" @@ -55,12 +58,15 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) - msg := &exchangev2types.MsgIncreasePositionMargin{ + msg := exchangev2types.MsgIncreasePositionMargin{ Sender: senderAddress.String(), MarketId: "0x4ca0f92fc28be0c9761326016b5a1a2177dd6375558365116b5bdda9abc229ce", SourceSubaccountId: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000", @@ -69,24 +75,16 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/exchange/1_MsgDeposit/example.go b/examples/chain/exchange/1_MsgDeposit/example.go index f44b7044..65883a92 100644 --- a/examples/chain/exchange/1_MsgDeposit/example.go +++ b/examples/chain/exchange/1_MsgDeposit/example.go @@ -1,6 +1,8 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" @@ -8,6 +10,7 @@ import ( "cosmossdk.io/math" rpchttp "github.com/cometbft/cometbft/rpc/client/http" sdktypes "github.com/cosmos/cosmos-sdk/types" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" exchangev2types "github.com/InjectiveLabs/sdk-go/chain/exchange/types/v2" chainclient "github.com/InjectiveLabs/sdk-go/client/chain" @@ -54,12 +57,15 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) - msg := &exchangev2types.MsgDeposit{ + msg := exchangev2types.MsgDeposit{ Sender: senderAddress.String(), SubaccountId: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000", Amount: sdktypes.Coin{ @@ -68,24 +74,16 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/exchange/21_MsgRewardsOptOut/example.go b/examples/chain/exchange/21_MsgRewardsOptOut/example.go index 0b251797..a51afc2c 100644 --- a/examples/chain/exchange/21_MsgRewardsOptOut/example.go +++ b/examples/chain/exchange/21_MsgRewardsOptOut/example.go @@ -1,11 +1,14 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" exchangev2types "github.com/InjectiveLabs/sdk-go/chain/exchange/types/v2" chainclient "github.com/InjectiveLabs/sdk-go/client/chain" @@ -54,34 +57,29 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) - msg := &exchangev2types.MsgRewardsOptOut{ + msg := exchangev2types.MsgRewardsOptOut{ Sender: senderAddress.String(), } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/exchange/23_MsgDecreasePositionMargin/example.go b/examples/chain/exchange/23_MsgDecreasePositionMargin/example.go index 43a37bd4..db233ca9 100644 --- a/examples/chain/exchange/23_MsgDecreasePositionMargin/example.go +++ b/examples/chain/exchange/23_MsgDecreasePositionMargin/example.go @@ -1,9 +1,11 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "time" "cosmossdk.io/math" rpchttp "github.com/cometbft/cometbft/rpc/client/http" @@ -55,7 +57,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -71,7 +76,7 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - response, err := chainClient.AsyncBroadcastMsg(msg) + response, err := chainClient.AsyncBroadcastMsg(ctx, msg) if err != nil { panic(err) @@ -80,7 +85,7 @@ func main() { str, _ := json.MarshalIndent(response, "", "\t") fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/exchange/24_MsgUpdateSpotMarket/example.go b/examples/chain/exchange/24_MsgUpdateSpotMarket/example.go index b15a611b..881a4a48 100644 --- a/examples/chain/exchange/24_MsgUpdateSpotMarket/example.go +++ b/examples/chain/exchange/24_MsgUpdateSpotMarket/example.go @@ -1,9 +1,11 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "time" "cosmossdk.io/math" rpchttp "github.com/cometbft/cometbft/rpc/client/http" @@ -54,7 +56,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -73,7 +78,7 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - response, err := chainClient.AsyncBroadcastMsg(msg) + response, err := chainClient.AsyncBroadcastMsg(ctx, msg) if err != nil { panic(err) @@ -82,7 +87,7 @@ func main() { str, _ := json.MarshalIndent(response, "", "\t") fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/exchange/25_MsgUpdateDerivativeMarket/example.go b/examples/chain/exchange/25_MsgUpdateDerivativeMarket/example.go index b1df72d9..e468750d 100644 --- a/examples/chain/exchange/25_MsgUpdateDerivativeMarket/example.go +++ b/examples/chain/exchange/25_MsgUpdateDerivativeMarket/example.go @@ -1,9 +1,11 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "time" "cosmossdk.io/math" rpchttp "github.com/cometbft/cometbft/rpc/client/http" @@ -54,7 +56,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -76,7 +81,7 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - response, err := chainClient.AsyncBroadcastMsg(msg) + response, err := chainClient.AsyncBroadcastMsg(ctx, msg) if err != nil { panic(err) @@ -85,7 +90,7 @@ func main() { str, _ := json.MarshalIndent(response, "", "\t") fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/exchange/26_MsgAuthorizeStakeGrants/example.go b/examples/chain/exchange/26_MsgAuthorizeStakeGrants/example.go index 49d744fa..63da5c05 100644 --- a/examples/chain/exchange/26_MsgAuthorizeStakeGrants/example.go +++ b/examples/chain/exchange/26_MsgAuthorizeStakeGrants/example.go @@ -1,9 +1,11 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "time" "cosmossdk.io/math" rpchttp "github.com/cometbft/cometbft/rpc/client/http" @@ -55,7 +57,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -71,7 +76,7 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - response, err := chainClient.AsyncBroadcastMsg(msg) + response, err := chainClient.AsyncBroadcastMsg(ctx, msg) if err != nil { panic(err) @@ -80,7 +85,7 @@ func main() { str, _ := json.MarshalIndent(response, "", "\t") fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/exchange/27_MsgActivateStakeGrant/example.go b/examples/chain/exchange/27_MsgActivateStakeGrant/example.go index 31481ce7..13db512f 100644 --- a/examples/chain/exchange/27_MsgActivateStakeGrant/example.go +++ b/examples/chain/exchange/27_MsgActivateStakeGrant/example.go @@ -1,9 +1,11 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" @@ -54,7 +56,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -65,7 +70,7 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - response, err := chainClient.AsyncBroadcastMsg(msg) + response, err := chainClient.AsyncBroadcastMsg(ctx, msg) if err != nil { panic(err) @@ -74,7 +79,7 @@ func main() { str, _ := json.MarshalIndent(response, "", "\t") fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/exchange/28_MsgCreateGTBSpotLimitOrder/example.go b/examples/chain/exchange/28_MsgCreateGTBSpotLimitOrder/example.go index 8086c98d..6ca43f40 100644 --- a/examples/chain/exchange/28_MsgCreateGTBSpotLimitOrder/example.go +++ b/examples/chain/exchange/28_MsgCreateGTBSpotLimitOrder/example.go @@ -2,11 +2,13 @@ package main import ( "context" + "encoding/json" "fmt" "os" "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" "github.com/google/uuid" "github.com/shopspring/decimal" @@ -56,13 +58,15 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) // Get latest block height - ctx := context.Background() res, err := chainClient.FetchLatestBlock(ctx) if err != nil { fmt.Println(err) @@ -89,47 +93,22 @@ func main() { }, ) - msg := new(exchangev2types.MsgCreateSpotLimitOrder) - msg.Sender = senderAddress.String() - msg.Order = *order - - simRes, err := chainClient.SimulateMsg(clientCtx, msg) - - if err != nil { - fmt.Println(err) - return - } - - msgCreateSpotLimitOrderResponse := exchangev2types.MsgCreateSpotLimitOrderResponse{} - err = msgCreateSpotLimitOrderResponse.Unmarshal(simRes.Result.MsgResponses[0].Value) - - if err != nil { - fmt.Println(err) - return + msg := exchangev2types.MsgCreateSpotLimitOrder{ + Sender: senderAddress.String(), + Order: *order, } - fmt.Println("simulated order hash: ", msgCreateSpotLimitOrderResponse.OrderHash) - // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - return - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/exchange/29_MsgCreateGTBDerivativeLimitOrder/example.go b/examples/chain/exchange/29_MsgCreateGTBDerivativeLimitOrder/example.go index e12a394e..70b8b66a 100644 --- a/examples/chain/exchange/29_MsgCreateGTBDerivativeLimitOrder/example.go +++ b/examples/chain/exchange/29_MsgCreateGTBDerivativeLimitOrder/example.go @@ -2,11 +2,13 @@ package main import ( "context" + "encoding/json" "fmt" "os" "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" "github.com/google/uuid" "github.com/shopspring/decimal" @@ -57,13 +59,15 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) // Get latest block height - ctx := context.Background() res, err := chainClient.FetchLatestBlock(ctx) if err != nil { fmt.Println(err) @@ -92,44 +96,22 @@ func main() { }, ) - msg := new(exchangev2types.MsgCreateDerivativeLimitOrder) - msg.Sender = senderAddress.String() - msg.Order = *order - - simRes, err := chainClient.SimulateMsg(clientCtx, msg) - - if err != nil { - panic(err) - } - - msgCreateDerivativeLimitOrderResponse := exchangev2types.MsgCreateDerivativeLimitOrderResponse{} - err = msgCreateDerivativeLimitOrderResponse.Unmarshal(simRes.Result.MsgResponses[0].Value) - - if err != nil { - panic(err) + msg := exchangev2types.MsgCreateDerivativeLimitOrder{ + Sender: senderAddress.String(), + Order: *order, } - fmt.Println("simulated order hash", msgCreateDerivativeLimitOrderResponse.OrderHash) - // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/exchange/2_MsgWithdraw/example.go b/examples/chain/exchange/2_MsgWithdraw/example.go index ae2035c6..2e36f528 100644 --- a/examples/chain/exchange/2_MsgWithdraw/example.go +++ b/examples/chain/exchange/2_MsgWithdraw/example.go @@ -1,6 +1,8 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" @@ -9,6 +11,7 @@ import ( "github.com/InjectiveLabs/sdk-go/client/common" rpchttp "github.com/cometbft/cometbft/rpc/client/http" sdktypes "github.com/cosmos/cosmos-sdk/types" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" exchangev2types "github.com/InjectiveLabs/sdk-go/chain/exchange/types/v2" chainclient "github.com/InjectiveLabs/sdk-go/client/chain" @@ -56,12 +59,15 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) - msg := &exchangev2types.MsgWithdraw{ + msg := exchangev2types.MsgWithdraw{ Sender: senderAddress.String(), SubaccountId: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000", Amount: sdktypes.Coin{ @@ -70,24 +76,16 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/exchange/3_MsgInstantSpotMarketLaunch/example.go b/examples/chain/exchange/3_MsgInstantSpotMarketLaunch/example.go index d0fc3585..59046b4e 100644 --- a/examples/chain/exchange/3_MsgInstantSpotMarketLaunch/example.go +++ b/examples/chain/exchange/3_MsgInstantSpotMarketLaunch/example.go @@ -1,9 +1,11 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "time" "cosmossdk.io/math" rpchttp "github.com/cometbft/cometbft/rpc/client/http" @@ -54,7 +56,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -76,7 +81,7 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - response, err := chainClient.AsyncBroadcastMsg(msg) + response, err := chainClient.AsyncBroadcastMsg(ctx, msg) if err != nil { panic(err) @@ -85,7 +90,7 @@ func main() { str, _ := json.MarshalIndent(response, "", "\t") fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/exchange/4_MsgInstantPerpetualMarketLaunch/example.go b/examples/chain/exchange/4_MsgInstantPerpetualMarketLaunch/example.go index f0958360..6e7599bb 100644 --- a/examples/chain/exchange/4_MsgInstantPerpetualMarketLaunch/example.go +++ b/examples/chain/exchange/4_MsgInstantPerpetualMarketLaunch/example.go @@ -1,9 +1,11 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "time" "cosmossdk.io/math" rpchttp "github.com/cometbft/cometbft/rpc/client/http" @@ -55,7 +57,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -81,8 +86,7 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - response, err := chainClient.AsyncBroadcastMsg(msg) - + response, err := chainClient.AsyncBroadcastMsg(ctx, msg) if err != nil { panic(err) } @@ -90,7 +94,7 @@ func main() { str, _ := json.MarshalIndent(response, "", "\t") fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/exchange/5_MsgInstantExpiryFuturesMarketLaunch/example.go b/examples/chain/exchange/5_MsgInstantExpiryFuturesMarketLaunch/example.go index ae259ac4..042e9025 100644 --- a/examples/chain/exchange/5_MsgInstantExpiryFuturesMarketLaunch/example.go +++ b/examples/chain/exchange/5_MsgInstantExpiryFuturesMarketLaunch/example.go @@ -1,9 +1,11 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "time" "cosmossdk.io/math" rpchttp "github.com/cometbft/cometbft/rpc/client/http" @@ -55,7 +57,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -82,7 +87,7 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - response, err := chainClient.AsyncBroadcastMsg(msg) + response, err := chainClient.AsyncBroadcastMsg(ctx, msg) if err != nil { panic(err) @@ -91,7 +96,7 @@ func main() { str, _ := json.MarshalIndent(response, "", "\t") fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/exchange/6_MsgCreateSpotLimitOrder/example.go b/examples/chain/exchange/6_MsgCreateSpotLimitOrder/example.go index 5a205f5b..7d31b06d 100644 --- a/examples/chain/exchange/6_MsgCreateSpotLimitOrder/example.go +++ b/examples/chain/exchange/6_MsgCreateSpotLimitOrder/example.go @@ -1,11 +1,14 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" "github.com/google/uuid" "github.com/shopspring/decimal" @@ -55,7 +58,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -79,47 +85,22 @@ func main() { }, ) - msg := new(exchangev2types.MsgCreateSpotLimitOrder) - msg.Sender = senderAddress.String() - msg.Order = *order - - simRes, err := chainClient.SimulateMsg(clientCtx, msg) - - if err != nil { - fmt.Println(err) - return - } - - msgCreateSpotLimitOrderResponse := exchangev2types.MsgCreateSpotLimitOrderResponse{} - err = msgCreateSpotLimitOrderResponse.Unmarshal(simRes.Result.MsgResponses[0].Value) - - if err != nil { - fmt.Println(err) - return + msg := exchangev2types.MsgCreateSpotLimitOrder{ + Sender: senderAddress.String(), + Order: *order, } - fmt.Println("simulated order hash: ", msgCreateSpotLimitOrderResponse.OrderHash) - // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - return - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/exchange/7_MsgCreateSpotMarketOrder/example.go b/examples/chain/exchange/7_MsgCreateSpotMarketOrder/example.go index 27512d4c..a0a872ea 100644 --- a/examples/chain/exchange/7_MsgCreateSpotMarketOrder/example.go +++ b/examples/chain/exchange/7_MsgCreateSpotMarketOrder/example.go @@ -1,11 +1,14 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" "github.com/google/uuid" "github.com/shopspring/decimal" @@ -56,7 +59,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -79,46 +85,22 @@ func main() { }, ) - msg := new(exchangev2types.MsgCreateSpotMarketOrder) - msg.Sender = senderAddress.String() - msg.Order = *order - - simRes, err := chainClient.SimulateMsg(clientCtx, msg) - if err != nil { - fmt.Println(err) - return - } - - msgCreateSpotMarketOrderResponse := exchangev2types.MsgCreateSpotMarketOrderResponse{} - err = msgCreateSpotMarketOrderResponse.Unmarshal(simRes.Result.MsgResponses[0].Value) - - if err != nil { - fmt.Println(err) - return + msg := exchangev2types.MsgCreateSpotMarketOrder{ + Sender: senderAddress.String(), + Order: *order, } - fmt.Println("simulated order hash", msgCreateSpotMarketOrderResponse.OrderHash) - // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - return - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/exchange/8_MsgCancelSpotOrder/example.go b/examples/chain/exchange/8_MsgCancelSpotOrder/example.go index 89f16788..41b7cbf3 100644 --- a/examples/chain/exchange/8_MsgCancelSpotOrder/example.go +++ b/examples/chain/exchange/8_MsgCancelSpotOrder/example.go @@ -1,11 +1,14 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" exchangev2types "github.com/InjectiveLabs/sdk-go/chain/exchange/types/v2" chainclient "github.com/InjectiveLabs/sdk-go/client/chain" @@ -54,12 +57,15 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) - msg := &exchangev2types.MsgCancelSpotOrder{ + msg := exchangev2types.MsgCancelSpotOrder{ Sender: senderAddress.String(), MarketId: "0xa508cb32923323679f29a032c70342c147c17d0145625922b0ef22e955c844c0", SubaccountId: "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000000", @@ -67,24 +73,16 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/exchange/9_MsgBatchUpdateOrders/example.go b/examples/chain/exchange/9_MsgBatchUpdateOrders/example.go index 3392cfc4..9a40b5bb 100644 --- a/examples/chain/exchange/9_MsgBatchUpdateOrders/example.go +++ b/examples/chain/exchange/9_MsgBatchUpdateOrders/example.go @@ -1,11 +1,14 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" "github.com/google/uuid" "github.com/shopspring/decimal" @@ -58,7 +61,10 @@ func main() { return } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -102,48 +108,26 @@ func main() { }, ) - msg := new(exchangev2types.MsgBatchUpdateOrders) - msg.Sender = senderAddress.String() - msg.SubaccountId = defaultSubaccountID.Hex() - msg.SpotOrdersToCreate = []*exchangev2types.SpotOrder{spot_order} - msg.DerivativeOrdersToCreate = []*exchangev2types.DerivativeOrder{derivative_order} - msg.SpotMarketIdsToCancelAll = smarketIds - msg.DerivativeMarketIdsToCancelAll = dmarketIds - - simRes, err := chainClient.SimulateMsg(clientCtx, msg) - - if err != nil { - fmt.Println(err) - return + msg := exchangev2types.MsgBatchUpdateOrders{ + Sender: senderAddress.String(), + SubaccountId: defaultSubaccountID.Hex(), + SpotOrdersToCreate: []*exchangev2types.SpotOrder{spot_order}, + DerivativeOrdersToCreate: []*exchangev2types.DerivativeOrder{derivative_order}, + SpotMarketIdsToCancelAll: smarketIds, + DerivativeMarketIdsToCancelAll: dmarketIds, } - MsgBatchUpdateOrdersResponse := exchangev2types.MsgBatchUpdateOrdersResponse{} - MsgBatchUpdateOrdersResponse.Unmarshal(simRes.Result.MsgResponses[0].Value) - - fmt.Println("simulated spot order hashes", MsgBatchUpdateOrdersResponse.SpotOrderHashes) - - fmt.Println("simulated derivative order hashes", MsgBatchUpdateOrdersResponse.DerivativeOrderHashes) - // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - return - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/ibc/transfer/1_MsgTransfer/example.go b/examples/chain/ibc/transfer/1_MsgTransfer/example.go index 09ab7030..2777447e 100644 --- a/examples/chain/ibc/transfer/1_MsgTransfer/example.go +++ b/examples/chain/ibc/transfer/1_MsgTransfer/example.go @@ -1,18 +1,20 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "time" "cosmossdk.io/math" - "github.com/InjectiveLabs/sdk-go/client/common" - - chainclient "github.com/InjectiveLabs/sdk-go/client/chain" rpchttp "github.com/cometbft/cometbft/rpc/client/http" sdktypes "github.com/cosmos/cosmos-sdk/types" ibctransfertypes "github.com/cosmos/ibc-go/v8/modules/apps/transfer/types" ibccoretypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" + + chainclient "github.com/InjectiveLabs/sdk-go/client/chain" + "github.com/InjectiveLabs/sdk-go/client/common" ) func main() { @@ -56,7 +58,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -80,7 +85,7 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - response, err := chainClient.AsyncBroadcastMsg(msg) + response, err := chainClient.AsyncBroadcastMsg(ctx, msg) if err != nil { panic(err) @@ -89,7 +94,7 @@ func main() { str, _ := json.MarshalIndent(response, "", "\t") fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/oracle/1_MsgRelayPriceFeedPrice/example.go b/examples/chain/oracle/1_MsgRelayPriceFeedPrice/example.go index 2a04b865..7d198a7f 100644 --- a/examples/chain/oracle/1_MsgRelayPriceFeedPrice/example.go +++ b/examples/chain/oracle/1_MsgRelayPriceFeedPrice/example.go @@ -1,16 +1,18 @@ package main import ( + "context" "fmt" "os" + "time" "cosmossdk.io/math" - "github.com/InjectiveLabs/sdk-go/client/common" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" txtypes "github.com/cosmos/cosmos-sdk/types/tx" oracletypes "github.com/InjectiveLabs/sdk-go/chain/oracle/types" chainclient "github.com/InjectiveLabs/sdk-go/client/chain" - rpchttp "github.com/cometbft/cometbft/rpc/client/http" + "github.com/InjectiveLabs/sdk-go/client/common" ) func main() { @@ -55,7 +57,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -72,7 +77,7 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - _, result, err := chainClient.BroadcastMsg(txtypes.BroadcastMode_BROADCAST_MODE_SYNC, msg) + _, result, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, msg) if err != nil { panic(err) @@ -80,7 +85,7 @@ func main() { fmt.Printf("Broadcast result: %s\n", result) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/peggy/1_MsgSendToEth/example.go b/examples/chain/peggy/1_MsgSendToEth/example.go index 51bd60a7..14950069 100644 --- a/examples/chain/peggy/1_MsgSendToEth/example.go +++ b/examples/chain/peggy/1_MsgSendToEth/example.go @@ -1,17 +1,20 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" "cosmossdk.io/math" "github.com/InjectiveLabs/sdk-go/client/common" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" + sdktypes "github.com/cosmos/cosmos-sdk/types" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" peggytypes "github.com/InjectiveLabs/sdk-go/chain/peggy/types" chainclient "github.com/InjectiveLabs/sdk-go/client/chain" - rpchttp "github.com/cometbft/cometbft/rpc/client/http" - sdktypes "github.com/cosmos/cosmos-sdk/types" ) func main() { @@ -56,7 +59,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -70,7 +76,7 @@ func main() { Denom: "inj", Amount: math.NewInt(2000000000000000000), // 2 INJ } - msg := &peggytypes.MsgSendToEth{ + msg := peggytypes.MsgSendToEth{ Sender: senderAddress.String(), Amount: amount, EthDest: ethDest, @@ -78,24 +84,16 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/permissions/1_MsgCreateNamespace/example.go b/examples/chain/permissions/1_MsgCreateNamespace/example.go index 7dbc45e9..46ec35bb 100644 --- a/examples/chain/permissions/1_MsgCreateNamespace/example.go +++ b/examples/chain/permissions/1_MsgCreateNamespace/example.go @@ -1,14 +1,17 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "time" + + rpchttp "github.com/cometbft/cometbft/rpc/client/http" permissionstypes "github.com/InjectiveLabs/sdk-go/chain/permissions/types" chainclient "github.com/InjectiveLabs/sdk-go/client/chain" "github.com/InjectiveLabs/sdk-go/client/common" - rpchttp "github.com/cometbft/cometbft/rpc/client/http" ) func main() { @@ -53,7 +56,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -127,7 +133,8 @@ func main() { } //AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - response, err := chainClient.SyncBroadcastMsg(msg) + pollInterval := 100 * time.Millisecond + response, err := chainClient.SyncBroadcastMsg(ctx, &pollInterval, 5, msg) if err != nil { panic(err) @@ -136,7 +143,7 @@ func main() { str, _ := json.MarshalIndent(response, "", "\t") fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/permissions/2_MsgUpdateNamespace/example.go b/examples/chain/permissions/2_MsgUpdateNamespace/example.go index 5e0ee2f6..ed477dfd 100644 --- a/examples/chain/permissions/2_MsgUpdateNamespace/example.go +++ b/examples/chain/permissions/2_MsgUpdateNamespace/example.go @@ -1,9 +1,11 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" @@ -54,7 +56,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -106,7 +111,8 @@ func main() { } //AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - response, err := chainClient.SyncBroadcastMsg(msg) + pollInterval := 100 * time.Millisecond + response, err := chainClient.SyncBroadcastMsg(ctx, &pollInterval, 5, msg) if err != nil { panic(err) @@ -115,7 +121,7 @@ func main() { str, _ := json.MarshalIndent(response, "", "\t") fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/permissions/3_MsgUpdateActorRoles/example.go b/examples/chain/permissions/3_MsgUpdateActorRoles/example.go index 3626607a..31232890 100644 --- a/examples/chain/permissions/3_MsgUpdateActorRoles/example.go +++ b/examples/chain/permissions/3_MsgUpdateActorRoles/example.go @@ -1,16 +1,18 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "time" + "github.com/InjectiveLabs/sdk-go/client/common" rpchttp "github.com/cometbft/cometbft/rpc/client/http" txtypes "github.com/cosmos/cosmos-sdk/types/tx" permissionstypes "github.com/InjectiveLabs/sdk-go/chain/permissions/types" chainclient "github.com/InjectiveLabs/sdk-go/client/chain" - "github.com/InjectiveLabs/sdk-go/client/common" ) func main() { @@ -55,7 +57,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -86,7 +91,7 @@ func main() { } //AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - _, response, err := chainClient.BroadcastMsg(txtypes.BroadcastMode_BROADCAST_MODE_SYNC, msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, msg) if err != nil { panic(err) @@ -95,7 +100,7 @@ func main() { str, _ := json.MarshalIndent(response, "", "\t") fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/permissions/4_MsgClaimVoucher/example.go b/examples/chain/permissions/4_MsgClaimVoucher/example.go index 8c48b0a9..b27aca0f 100644 --- a/examples/chain/permissions/4_MsgClaimVoucher/example.go +++ b/examples/chain/permissions/4_MsgClaimVoucher/example.go @@ -1,9 +1,11 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" txtypes "github.com/cosmos/cosmos-sdk/types/tx" @@ -55,7 +57,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -68,7 +73,7 @@ func main() { } //AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - _, response, err := chainClient.BroadcastMsg(txtypes.BroadcastMode_BROADCAST_MODE_SYNC, msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, msg) if err != nil { panic(err) @@ -77,7 +82,7 @@ func main() { str, _ := json.MarshalIndent(response, "", "\t") fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/staking/1_MsgDelegate/example.go b/examples/chain/staking/1_MsgDelegate/example.go index 2fda4383..3b76e438 100644 --- a/examples/chain/staking/1_MsgDelegate/example.go +++ b/examples/chain/staking/1_MsgDelegate/example.go @@ -1,17 +1,20 @@ package main import ( + "context" + "encoding/json" "fmt" "os" "time" "cosmossdk.io/math" - "github.com/InjectiveLabs/sdk-go/client/common" - - chainclient "github.com/InjectiveLabs/sdk-go/client/chain" rpchttp "github.com/cometbft/cometbft/rpc/client/http" sdktypes "github.com/cosmos/cosmos-sdk/types" + txtypes "github.com/cosmos/cosmos-sdk/types/tx" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + + chainclient "github.com/InjectiveLabs/sdk-go/client/chain" + "github.com/InjectiveLabs/sdk-go/client/common" ) func main() { @@ -56,37 +59,34 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) - msg := new(stakingtypes.MsgDelegate) - msg.DelegatorAddress = senderAddress.String() - msg.ValidatorAddress = "injvaloper14gy4acwjm96wd20awm9ar6j54lev5p7espy9ug" - msg.Amount = sdktypes.Coin{ - Denom: "inj", Amount: math.NewInt(1000000000000000000), // 1 INJ + msg := stakingtypes.MsgDelegate{ + DelegatorAddress: senderAddress.String(), + ValidatorAddress: "injvaloper14gy4acwjm96wd20awm9ar6j54lev5p7espy9ug", + Amount: sdktypes.Coin{ + Denom: "inj", + Amount: math.NewInt(1000000000000000000), // 1 INJ + }, } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - err = chainClient.QueueBroadcastMsg(msg) + _, response, err := chainClient.BroadcastMsg(ctx, txtypes.BroadcastMode_BROADCAST_MODE_SYNC, &msg) if err != nil { - fmt.Println(err) - } - - time.Sleep(time.Second * 5) - - gasFee, err := chainClient.GetGasFee() - - if err != nil { - fmt.Println(err) - return + panic(err) } - fmt.Println("gas fee:", gasFee, "INJ") + str, _ := json.MarshalIndent(response, "", "\t") + fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/tokenfactory/1_CreateDenom/example.go b/examples/chain/tokenfactory/1_CreateDenom/example.go index 4321cf21..2c42685d 100644 --- a/examples/chain/tokenfactory/1_CreateDenom/example.go +++ b/examples/chain/tokenfactory/1_CreateDenom/example.go @@ -1,14 +1,17 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "time" + + rpchttp "github.com/cometbft/cometbft/rpc/client/http" tokenfactorytypes "github.com/InjectiveLabs/sdk-go/chain/tokenfactory/types" chainclient "github.com/InjectiveLabs/sdk-go/client/chain" "github.com/InjectiveLabs/sdk-go/client/common" - rpchttp "github.com/cometbft/cometbft/rpc/client/http" ) func main() { @@ -52,20 +55,24 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) - message := new(tokenfactorytypes.MsgCreateDenom) - message.Sender = senderAddress.String() - message.Subdenom = "inj_test" - message.Name = "Injective Test Token" - message.Symbol = "INJTEST" - message.Decimals = 18 + message := tokenfactorytypes.MsgCreateDenom{ + Sender: senderAddress.String(), + Subdenom: "inj_test", + Name: "Injective Test Token", + Symbol: "INJTEST", + Decimals: 18, + } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - response, err := chainClient.AsyncBroadcastMsg(message) + response, err := chainClient.AsyncBroadcastMsg(ctx, &message) if err != nil { panic(err) @@ -74,7 +81,7 @@ func main() { str, _ := json.MarshalIndent(response, "", "\t") fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/tokenfactory/2_MsgMint/example.go b/examples/chain/tokenfactory/2_MsgMint/example.go index bc0c8f23..89a7659b 100644 --- a/examples/chain/tokenfactory/2_MsgMint/example.go +++ b/examples/chain/tokenfactory/2_MsgMint/example.go @@ -1,17 +1,19 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "time" "cosmossdk.io/math" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" + sdktypes "github.com/cosmos/cosmos-sdk/types" tokenfactorytypes "github.com/InjectiveLabs/sdk-go/chain/tokenfactory/types" chainclient "github.com/InjectiveLabs/sdk-go/client/chain" "github.com/InjectiveLabs/sdk-go/client/common" - rpchttp "github.com/cometbft/cometbft/rpc/client/http" - sdktypes "github.com/cosmos/cosmos-sdk/types" ) func main() { @@ -55,20 +57,24 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) - message := new(tokenfactorytypes.MsgMint) - message.Sender = senderAddress.String() - message.Amount = sdktypes.Coin{ - Denom: "factory/inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r/inj_test", - Amount: math.NewInt(1000000000), + message := tokenfactorytypes.MsgMint{ + Sender: senderAddress.String(), + Amount: sdktypes.Coin{ + Denom: "factory/inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r/inj_test", + Amount: math.NewInt(1000000000), + }, } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - response, err := chainClient.AsyncBroadcastMsg(message) + response, err := chainClient.AsyncBroadcastMsg(ctx, &message) if err != nil { panic(err) @@ -77,7 +83,7 @@ func main() { str, _ := json.MarshalIndent(response, "", "\t") fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/tokenfactory/3_MsgBurn/example.go b/examples/chain/tokenfactory/3_MsgBurn/example.go index 245b466e..c3e1d211 100644 --- a/examples/chain/tokenfactory/3_MsgBurn/example.go +++ b/examples/chain/tokenfactory/3_MsgBurn/example.go @@ -1,17 +1,19 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "time" "cosmossdk.io/math" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" + sdktypes "github.com/cosmos/cosmos-sdk/types" tokenfactorytypes "github.com/InjectiveLabs/sdk-go/chain/tokenfactory/types" chainclient "github.com/InjectiveLabs/sdk-go/client/chain" "github.com/InjectiveLabs/sdk-go/client/common" - rpchttp "github.com/cometbft/cometbft/rpc/client/http" - sdktypes "github.com/cosmos/cosmos-sdk/types" ) func main() { @@ -55,20 +57,24 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) - message := new(tokenfactorytypes.MsgBurn) - message.Sender = senderAddress.String() - message.Amount = sdktypes.Coin{ - Denom: "factory/inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r/inj_test", - Amount: math.NewInt(100), + message := tokenfactorytypes.MsgBurn{ + Sender: senderAddress.String(), + Amount: sdktypes.Coin{ + Denom: "factory/inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r/inj_test", + Amount: math.NewInt(100), + }, } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - response, err := chainClient.AsyncBroadcastMsg(message) + response, err := chainClient.AsyncBroadcastMsg(ctx, &message) if err != nil { panic(err) @@ -77,7 +83,7 @@ func main() { str, _ := json.MarshalIndent(response, "", "\t") fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/tokenfactory/4_MsgSetDenomMetadata/example.go b/examples/chain/tokenfactory/4_MsgSetDenomMetadata/example.go index 926f2b2c..49d6061e 100644 --- a/examples/chain/tokenfactory/4_MsgSetDenomMetadata/example.go +++ b/examples/chain/tokenfactory/4_MsgSetDenomMetadata/example.go @@ -1,9 +1,11 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" @@ -54,7 +56,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -86,12 +91,13 @@ func main() { Decimals: tokenDecimals, } - message := new(tokenfactorytypes.MsgSetDenomMetadata) - message.Sender = senderAddress.String() - message.Metadata = metadata + message := tokenfactorytypes.MsgSetDenomMetadata{ + Sender: senderAddress.String(), + Metadata: metadata, + } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - response, err := chainClient.AsyncBroadcastMsg(message) + response, err := chainClient.AsyncBroadcastMsg(ctx, &message) if err != nil { panic(err) @@ -100,7 +106,7 @@ func main() { str, _ := json.MarshalIndent(response, "", "\t") fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/tokenfactory/5_MsgChangeAdmin/example.go b/examples/chain/tokenfactory/5_MsgChangeAdmin/example.go index 9e2ddcb9..79510c07 100644 --- a/examples/chain/tokenfactory/5_MsgChangeAdmin/example.go +++ b/examples/chain/tokenfactory/5_MsgChangeAdmin/example.go @@ -1,9 +1,11 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" @@ -53,19 +55,23 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) - message := new(tokenfactorytypes.MsgChangeAdmin) - message.Sender = senderAddress.String() - message.Denom = "factory/inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r/inj_test" - // This is the zero address to remove admin permissions - message.NewAdmin = "inj1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqe2hm49" + message := tokenfactorytypes.MsgChangeAdmin{ + Sender: senderAddress.String(), + Denom: "factory/inj1hkhdaj2a2clmq5jq6mspsggqs32vynpk228q3r/inj_test", + // This is the zero address to remove admin permissions + NewAdmin: "inj1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqe2hm49", + } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - response, err := chainClient.AsyncBroadcastMsg(message) + response, err := chainClient.AsyncBroadcastMsg(ctx, &message) if err != nil { panic(err) @@ -74,7 +80,7 @@ func main() { str, _ := json.MarshalIndent(response, "", "\t") fmt.Print(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/examples/chain/wasmx/1_MsgExecuteContractCompat/example.go b/examples/chain/wasmx/1_MsgExecuteContractCompat/example.go index e35685fa..89338c80 100644 --- a/examples/chain/wasmx/1_MsgExecuteContractCompat/example.go +++ b/examples/chain/wasmx/1_MsgExecuteContractCompat/example.go @@ -1,9 +1,11 @@ package main import ( + "context" "encoding/json" "fmt" "os" + "time" rpchttp "github.com/cometbft/cometbft/rpc/client/http" @@ -53,7 +55,10 @@ func main() { panic(err) } - gasPrice := chainClient.CurrentChainGasPrice() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + gasPrice := chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) @@ -82,7 +87,7 @@ func main() { } // AsyncBroadcastMsg, SyncBroadcastMsg, QueueBroadcastMsg - response, err := chainClient.AsyncBroadcastMsg(&message) + response, err := chainClient.AsyncBroadcastMsg(ctx, &message) if err != nil { panic(err) @@ -91,7 +96,7 @@ func main() { str, _ := json.MarshalIndent(response, "", "\t") fmt.Println(string(str)) - gasPrice = chainClient.CurrentChainGasPrice() + gasPrice = chainClient.CurrentChainGasPrice(ctx) // adjust gas price to make it valid even if it changes between the time it is requested and the TX is broadcasted gasPrice = int64(float64(gasPrice) * 1.1) chainClient.SetGasPrice(gasPrice) diff --git a/typeddata/typed_data.go b/typeddata/typed_data.go index cb6aafbf..0278ea41 100644 --- a/typeddata/typed_data.go +++ b/typeddata/typed_data.go @@ -112,7 +112,7 @@ type TypedDataDomain struct { var typedDataReferenceTypeRegexp = regexp.MustCompile(`^[A-Z](\w*)(\[\])?$`) -// SignTextWithValidator signs the given message which can be further recovered +// SignTextValidator signs the given message which can be further recovered // with the given validator. // hash = keccak256("\x19\x00"${address}${data}). func SignTextValidator(validatorData ValidatorData) (hexutil.Bytes, string) {