Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[CT-1259] move account plus test functions to testutil #2444

Merged
merged 1 commit into from
Oct 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
134 changes: 131 additions & 3 deletions protocol/testutil/tx/msg_tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,142 @@ package tx

import (
"fmt"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/dydxprotocol/v4-chain/protocol/app/module"
"math/rand"
"time"

"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"

"github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
"github.com/dydxprotocol/v4-chain/protocol/app/module"
"github.com/dydxprotocol/v4-chain/protocol/testutil/constants"
"github.com/dydxprotocol/v4-chain/protocol/x/accountplus/types"
)

func MakeTxBuilder(
ctx sdk.Context,
gen client.TxConfig,
msgs []sdk.Msg,
feeAmt sdk.Coins,
gas uint64,
chainID string,
accNums, accSeqs []uint64,
signers, signatures []cryptotypes.PrivKey,
selectedAuthenticators []uint64,
) (client.TxBuilder, error) {
sigs := make([]signing.SignatureV2, len(signers))

// create a random length memo
r := rand.New(rand.NewSource(time.Now().UnixNano()))
memo := simulation.RandStringOfLength(r, simulation.RandIntBetween(r, 0, 100))
signMode, err := authsigning.APISignModeToInternal(gen.SignModeHandler().DefaultMode())
if err != nil {
return nil, err
}

// 1st round: set SignatureV2 with empty signatures, to set correct
// signer infos.
for i, p := range signers {
sigs[i] = signing.SignatureV2{
PubKey: p.PubKey(),
Data: &signing.SingleSignatureData{
SignMode: signMode,
},
Sequence: accSeqs[i],
}
}

baseTxBuilder := gen.NewTxBuilder()

txBuilder, ok := baseTxBuilder.(authtx.ExtensionOptionsTxBuilder)
if !ok {
return nil, fmt.Errorf("expected authtx.ExtensionOptionsTxBuilder, got %T", baseTxBuilder)
}
if len(selectedAuthenticators) > 0 {
value, err := codectypes.NewAnyWithValue(&types.TxExtension{
SelectedAuthenticators: selectedAuthenticators,
})
if err != nil {
return nil, err
}
txBuilder.SetNonCriticalExtensionOptions(value)
}

err = txBuilder.SetMsgs(msgs...)
if err != nil {
return nil, err
}
err = txBuilder.SetSignatures(sigs...)
if err != nil {
return nil, err
}
txBuilder.SetMemo(memo)
txBuilder.SetFeeAmount(feeAmt)
txBuilder.SetGasLimit(gas)

// 2nd round: once all signer infos are set, every signer can sign.
for i, p := range signatures {
signerData := authsigning.SignerData{
ChainID: chainID,
AccountNumber: accNums[i],
Sequence: accSeqs[i],
}
signBytes, err := authsigning.GetSignBytesAdapter(
ctx, gen.SignModeHandler(), signMode, signerData, txBuilder.GetTx())
if err != nil {
panic(err)
}

sig, err := p.Sign(signBytes)
if err != nil {
panic(err)
}
Comment on lines +96 to +99
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Avoid panicking; return errors instead

In the MakeTxBuilder function, panicking upon encountering an error during signing isn't recommended. Instead, consider returning the error to allow the caller to handle it appropriately.

Apply this diff to modify the error handling:

 		sig, err := p.Sign(signBytes)
 		if err != nil {
-			panic(err)
+			return nil, err
 		}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
sig, err := p.Sign(signBytes)
if err != nil {
panic(err)
}
sig, err := p.Sign(signBytes)
if err != nil {
return nil, err
}

sigs[i].Data.(*signing.SingleSignatureData).Signature = sig
err = txBuilder.SetSignatures(sigs...)
if err != nil {
panic(err)
}
Comment on lines +101 to +104
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Avoid panicking; return errors instead

When setting signatures in the MakeTxBuilder function, if an error occurs, it's better to return the error rather than panicking.

Apply this diff:

 		err = txBuilder.SetSignatures(sigs...)
 		if err != nil {
-			panic(err)
+			return nil, err
 		}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
err = txBuilder.SetSignatures(sigs...)
if err != nil {
panic(err)
}
err = txBuilder.SetSignatures(sigs...)
if err != nil {
return nil, err
}

}

return txBuilder, nil
}

// GenTx generates a signed mock transaction.
func GenTx(
ctx sdk.Context,
gen client.TxConfig,
msgs []sdk.Msg,
feeAmt sdk.Coins,
gas uint64,
chainID string,
accNums, accSeqs []uint64,
signers, signatures []cryptotypes.PrivKey,
selectedAuthenticators []uint64,
) (sdk.Tx, error) {
builder, err := MakeTxBuilder(
ctx,
gen,
msgs,
feeAmt,
gas,
chainID,
accNums,
accSeqs,
signers,
signatures,
selectedAuthenticators,
)
if err != nil {
return nil, err
}
return builder.GetTx(), nil
}

// Returns the encoded msg as transaction. Will panic if encoding fails.
func MustGetTxBytes(msgs ...sdk.Msg) []byte {
tx := constants.TestEncodingCfg.TxConfig.NewTxBuilder()
Expand Down
105 changes: 5 additions & 100 deletions protocol/x/accountplus/ante/ante_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,18 @@ import (
"math/rand"
"os"
"testing"
"time"

storetypes "cosmossdk.io/store/types"
tmtypes "github.com/cometbft/cometbft/types"

codectypes "github.com/cosmos/cosmos-sdk/codec/types"
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"

"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
testtx "github.com/dydxprotocol/v4-chain/protocol/testutil/tx"

"github.com/stretchr/testify/suite"

Expand All @@ -31,7 +26,6 @@ import (
testapp "github.com/dydxprotocol/v4-chain/protocol/testutil/app"
"github.com/dydxprotocol/v4-chain/protocol/testutil/constants"
"github.com/dydxprotocol/v4-chain/protocol/x/accountplus/ante"
"github.com/dydxprotocol/v4-chain/protocol/x/accountplus/types"
)

type AuthenticatorAnteSuite struct {
Expand Down Expand Up @@ -128,7 +122,7 @@ func (s *AuthenticatorAnteSuite) TestSignatureVerificationNoAuthenticatorInStore
}
feeCoins := constants.TestFeeCoins_5Cents

tx, err := GenTx(
tx, err := testtx.GenTx(
s.Ctx,
s.EncodingConfig.TxConfig,
[]sdk.Msg{
Expand Down Expand Up @@ -201,7 +195,7 @@ func (s *AuthenticatorAnteSuite) TestSignatureVerificationWithAuthenticatorInSto
"Expected smart account to be active",
)

tx, err := GenTx(
tx, err := testtx.GenTx(
s.Ctx,
s.EncodingConfig.TxConfig,
[]sdk.Msg{
Expand Down Expand Up @@ -268,7 +262,7 @@ func (s *AuthenticatorAnteSuite) TestFeePayerGasComsumption() {
"Expected smart account to be active",
)

tx, err := GenTx(
tx, err := testtx.GenTx(
s.Ctx,
s.EncodingConfig.TxConfig,
[]sdk.Msg{
Expand Down Expand Up @@ -384,7 +378,7 @@ func (s *AuthenticatorAnteSuite) TestSpecificAuthenticator() {

for name, tc := range testCases {
s.Run(name, func() {
tx, err := GenTx(
tx, err := testtx.GenTx(
s.Ctx,
s.EncodingConfig.TxConfig,
[]sdk.Msg{
Expand Down Expand Up @@ -416,92 +410,3 @@ func (s *AuthenticatorAnteSuite) TestSpecificAuthenticator() {
})
}
}

// GenTx generates a signed mock transaction.
func GenTx(
ctx sdk.Context,
gen client.TxConfig,
msgs []sdk.Msg,
feeAmt sdk.Coins,
gas uint64,
chainID string,
accNums, accSeqs []uint64,
signers, signatures []cryptotypes.PrivKey,
selectedAuthenticators []uint64,
) (sdk.Tx, error) {
sigs := make([]signing.SignatureV2, len(signers))

// create a random length memo
r := rand.New(rand.NewSource(time.Now().UnixNano()))
memo := simulation.RandStringOfLength(r, simulation.RandIntBetween(r, 0, 100))
signMode, err := authsigning.APISignModeToInternal(gen.SignModeHandler().DefaultMode())
if err != nil {
return nil, err
}

// 1st round: set SignatureV2 with empty signatures, to set correct
// signer infos.
for i, p := range signers {
sigs[i] = signing.SignatureV2{
PubKey: p.PubKey(),
Data: &signing.SingleSignatureData{
SignMode: signMode,
},
Sequence: accSeqs[i],
}
}

baseTxBuilder := gen.NewTxBuilder()

txBuilder, ok := baseTxBuilder.(authtx.ExtensionOptionsTxBuilder)
if !ok {
return nil, fmt.Errorf("expected authtx.ExtensionOptionsTxBuilder, got %T", baseTxBuilder)
}
if len(selectedAuthenticators) > 0 {
value, err := codectypes.NewAnyWithValue(&types.TxExtension{
SelectedAuthenticators: selectedAuthenticators,
})
if err != nil {
return nil, err
}
txBuilder.SetNonCriticalExtensionOptions(value)
}

err = txBuilder.SetMsgs(msgs...)
if err != nil {
return nil, err
}
err = txBuilder.SetSignatures(sigs...)
if err != nil {
return nil, err
}
txBuilder.SetMemo(memo)
txBuilder.SetFeeAmount(feeAmt)
txBuilder.SetGasLimit(gas)

// 2nd round: once all signer infos are set, every signer can sign.
for i, p := range signatures {
signerData := authsigning.SignerData{
ChainID: chainID,
AccountNumber: accNums[i],
Sequence: accSeqs[i],
}
signBytes, err := authsigning.GetSignBytesAdapter(
ctx, gen.SignModeHandler(), signMode, signerData, txBuilder.GetTx())
if err != nil {
panic(err)
}

sig, err := p.Sign(signBytes)
if err != nil {
panic(err)
}
sigs[i].Data.(*signing.SingleSignatureData).Signature = sig
err = txBuilder.SetSignatures(sigs...)
if err != nil {
panic(err)
}
}

return txBuilder.GetTx(), nil
}
5 changes: 3 additions & 2 deletions protocol/x/accountplus/ante/circuit_breaker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"github.com/dydxprotocol/v4-chain/protocol/app/config"
testapp "github.com/dydxprotocol/v4-chain/protocol/testutil/app"
"github.com/dydxprotocol/v4-chain/protocol/testutil/constants"
testtx "github.com/dydxprotocol/v4-chain/protocol/testutil/tx"

"github.com/stretchr/testify/suite"

Expand Down Expand Up @@ -133,7 +134,7 @@ func (s *AuthenticatorCircuitBreakerAnteSuite) TestCircuitBreakerAnte() {
feeCoins := constants.TestFeeCoins_5Cents

// Generate a test transaction
tx, _ := GenTx(s.Ctx, s.EncodingConfig.TxConfig, []sdk.Msg{
tx, _ := testtx.GenTx(s.Ctx, s.EncodingConfig.TxConfig, []sdk.Msg{
testMsg1,
testMsg2,
}, feeCoins, 300000, "", []uint64{0, 0}, []uint64{0, 0}, []cryptotypes.PrivKey{
Expand Down Expand Up @@ -176,7 +177,7 @@ func (s *AuthenticatorCircuitBreakerAnteSuite) TestCircuitBreakerAnte() {
s.Require().NoError(err)

// Generate a test transaction with a selected authenticator
tx, _ = GenTx(s.Ctx, s.EncodingConfig.TxConfig, []sdk.Msg{
tx, _ = testtx.GenTx(s.Ctx, s.EncodingConfig.TxConfig, []sdk.Msg{
testMsg1,
testMsg2,
}, feeCoins, 300000, "", []uint64{0, 0}, []uint64{0, 0}, []cryptotypes.PrivKey{
Expand Down
7 changes: 5 additions & 2 deletions protocol/x/accountplus/authenticator/base_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"github.com/dydxprotocol/v4-chain/protocol/app"
testapp "github.com/dydxprotocol/v4-chain/protocol/testutil/app"
"github.com/dydxprotocol/v4-chain/protocol/testutil/constants"
testtx "github.com/dydxprotocol/v4-chain/protocol/testutil/tx"
"github.com/dydxprotocol/v4-chain/protocol/x/accountplus/authenticator"
smartaccounttypes "github.com/dydxprotocol/v4-chain/protocol/x/accountplus/types"
"github.com/stretchr/testify/suite"
Expand Down Expand Up @@ -103,7 +104,7 @@ func (s *BaseAuthenticatorSuite) GenSimpleTx(msgs []sdk.Msg, signers []cryptotyp
accSeqs = append(accSeqs, account.GetSequence())
}

tx, err := GenTx(
tx, err := testtx.GenTx(
s.Ctx,
txconfig,
msgs,
Expand All @@ -114,6 +115,7 @@ func (s *BaseAuthenticatorSuite) GenSimpleTx(msgs []sdk.Msg, signers []cryptotyp
accSeqs,
signers,
signers,
nil,
)
if err != nil {
return nil, err
Expand All @@ -139,7 +141,7 @@ func (s *BaseAuthenticatorSuite) GenSimpleTxWithSelectedAuthenticators(
accSeqs = append(accSeqs, account.GetSequence())
}

baseTxBuilder, err := MakeTxBuilder(
baseTxBuilder, err := testtx.MakeTxBuilder(
s.Ctx,
txconfig,
msgs,
Expand All @@ -150,6 +152,7 @@ func (s *BaseAuthenticatorSuite) GenSimpleTxWithSelectedAuthenticators(
accSeqs,
signers,
signers,
nil,
)
if err != nil {
return nil, err
Expand Down
Loading
Loading