diff --git a/command/bridge/deploy/deploy.go b/command/bridge/deploy/deploy.go index 630cb12f85..2fae45da48 100644 --- a/command/bridge/deploy/deploy.go +++ b/command/bridge/deploy/deploy.go @@ -19,6 +19,7 @@ import ( "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" "github.com/0xPolygon/polygon-edge/consensus/polybft/validator" "github.com/0xPolygon/polygon-edge/contracts" + "github.com/0xPolygon/polygon-edge/crypto" "github.com/0xPolygon/polygon-edge/txrelayer" "github.com/0xPolygon/polygon-edge/types" ) @@ -111,12 +112,12 @@ var ( // initializersMap maps rootchain contract names to initializer function callbacks initializersMap = map[string]func(command.OutputFormatter, txrelayer.TxRelayer, []*validator.GenesisValidator, - *polybft.RootchainConfig, ethgo.Key, int64) error{ + *polybft.RootchainConfig, crypto.Key, int64) error{ getProxyNameForImpl(checkpointManagerName): func(fmt command.OutputFormatter, relayer txrelayer.TxRelayer, genesisValidators []*validator.GenesisValidator, config *polybft.RootchainConfig, - key ethgo.Key, + key crypto.Key, chainID int64) error { if !consensusCfg.NativeTokenConfig.IsMintable { // we can not initialize checkpoint manager at this moment if native token is not mintable @@ -145,7 +146,7 @@ var ( relayer txrelayer.TxRelayer, genesisValidators []*validator.GenesisValidator, config *polybft.RootchainConfig, - key ethgo.Key, + key crypto.Key, chainID int64) error { inputParams := &contractsapi.InitializeExitHelperFn{ NewCheckpointManager: config.CheckpointManagerAddress, @@ -157,7 +158,7 @@ var ( relayer txrelayer.TxRelayer, genesisValidators []*validator.GenesisValidator, config *polybft.RootchainConfig, - key ethgo.Key, + key crypto.Key, chainID int64) error { inputParams := &contractsapi.InitializeRootERC20PredicateFn{ NewStateSender: config.StateSenderAddress, @@ -175,7 +176,7 @@ var ( relayer txrelayer.TxRelayer, genesisValidators []*validator.GenesisValidator, config *polybft.RootchainConfig, - key ethgo.Key, + key crypto.Key, chainID int64) error { initParams := &contractsapi.InitializeChildMintableERC20PredicateFn{ NewStateSender: config.StateSenderAddress, @@ -191,7 +192,7 @@ var ( relayer txrelayer.TxRelayer, genesisValidators []*validator.GenesisValidator, config *polybft.RootchainConfig, - key ethgo.Key, + key crypto.Key, chainID int64) error { initParams := &contractsapi.InitializeRootERC721PredicateFn{ NewStateSender: config.StateSenderAddress, @@ -207,7 +208,7 @@ var ( relayer txrelayer.TxRelayer, genesisValidators []*validator.GenesisValidator, config *polybft.RootchainConfig, - key ethgo.Key, + key crypto.Key, chainID int64) error { initParams := &contractsapi.InitializeChildMintableERC721PredicateFn{ NewStateSender: config.StateSenderAddress, @@ -223,7 +224,7 @@ var ( relayer txrelayer.TxRelayer, genesisValidators []*validator.GenesisValidator, config *polybft.RootchainConfig, - key ethgo.Key, + key crypto.Key, chainID int64) error { initParams := &contractsapi.InitializeRootERC1155PredicateFn{ NewStateSender: config.StateSenderAddress, @@ -239,7 +240,7 @@ var ( relayer txrelayer.TxRelayer, genesisValidators []*validator.GenesisValidator, config *polybft.RootchainConfig, - key ethgo.Key, + key crypto.Key, chainID int64) error { initParams := &contractsapi.InitializeChildMintableERC1155PredicateFn{ NewStateSender: config.StateSenderAddress, @@ -255,7 +256,7 @@ var ( relayer txrelayer.TxRelayer, genesisValidators []*validator.GenesisValidator, config *polybft.RootchainConfig, - key ethgo.Key, + key crypto.Key, chainID int64) error { gvs := make([]*contractsapi.GenesisAccount, len(genesisValidators)) for i := 0; i < len(genesisValidators); i++ { @@ -443,7 +444,7 @@ func deployContracts(outputter command.OutputFormatter, client *jsonrpc.Client, if params.isTestMode { deployerAddr := deployerKey.Address() - txn := helper.CreateTransaction(ethgo.ZeroAddress, &deployerAddr, nil, ethgo.Ether(1), true) + txn := helper.CreateTransaction(types.ZeroAddress, &deployerAddr, nil, ethgo.Ether(1), true) if _, err = txRelayer.SendTransactionLocal(txn); err != nil { return deploymentResultInfo{RootchainCfg: nil, CommandResults: nil}, err } @@ -589,7 +590,7 @@ func deployContracts(outputter command.OutputFormatter, client *jsonrpc.Client, } } - txn := helper.CreateTransaction(ethgo.ZeroAddress, nil, bytecode, nil, true) + txn := helper.CreateTransaction(types.ZeroAddress, nil, bytecode, nil, true) receipt, err := txRelayer.SendTransaction(txn, deployerKey) if err != nil { @@ -711,14 +712,14 @@ func populateExistingTokenAddr(eth *jsonrpc.Eth, tokenAddr, tokenName string, // initContract initializes arbitrary contract with given parameters deployed on a given address func initContract(cmdOutput command.OutputFormatter, txRelayer txrelayer.TxRelayer, initInputFn contractsapi.StateTransactionInput, contractAddr types.Address, - contractName string, deployerKey ethgo.Key) error { + contractName string, deployerKey crypto.Key) error { input, err := initInputFn.EncodeAbi() if err != nil { return fmt.Errorf("failed to encode initialization params for %s.initialize. error: %w", contractName, err) } - if _, err := helper.SendTransaction(txRelayer, ethgo.Address(contractAddr), + if _, err := helper.SendTransaction(txRelayer, contractAddr, input, contractName, deployerKey); err != nil { return err } diff --git a/command/bridge/deploy/deploy_test.go b/command/bridge/deploy/deploy_test.go index e7841992a7..12d2d6bce4 100644 --- a/command/bridge/deploy/deploy_test.go +++ b/command/bridge/deploy/deploy_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "github.com/umbracle/ethgo" "github.com/umbracle/ethgo/jsonrpc" "github.com/umbracle/ethgo/testutil" @@ -32,7 +33,7 @@ func TestDeployContracts_NoPanics(t *testing.T) { testKey, err := helper.DecodePrivateKey("") require.NoError(t, err) - receipt, err := server.Fund(testKey.Address()) + receipt, err := server.Fund(ethgo.Address(testKey.Address())) require.NoError(t, err) require.Equal(t, uint64(types.ReceiptSuccess), receipt.Status) diff --git a/command/bridge/deposit/erc1155/deposit_erc1155.go b/command/bridge/deposit/erc1155/deposit_erc1155.go index 6472df1fda..9a9f51281f 100644 --- a/command/bridge/deposit/erc1155/deposit_erc1155.go +++ b/command/bridge/deposit/erc1155/deposit_erc1155.go @@ -6,7 +6,6 @@ import ( "strings" "github.com/spf13/cobra" - "github.com/umbracle/ethgo" "github.com/0xPolygon/polygon-edge/command" "github.com/0xPolygon/polygon-edge/command/bridge/common" @@ -245,8 +244,8 @@ func runCommand(cmd *cobra.Command, _ []string) { } // createDepositTxn encodes parameters for deposit function on rootchain predicate contract -func createDepositTxn(sender ethgo.Address, receivers []types.Address, - amounts, tokenIDs []*big.Int) (*ethgo.Transaction, error) { +func createDepositTxn(sender types.Address, receivers []types.Address, + amounts, tokenIDs []*big.Int) (*types.Transaction, error) { depositBatchFn := &contractsapi.DepositBatchRootERC1155PredicateFn{ RootToken: types.StringToAddress(dp.TokenAddr), Receivers: receivers, @@ -259,14 +258,14 @@ func createDepositTxn(sender ethgo.Address, receivers []types.Address, return nil, fmt.Errorf("failed to encode provided parameters: %w", err) } - addr := ethgo.Address(types.StringToAddress(dp.PredicateAddr)) + addr := types.StringToAddress(dp.PredicateAddr) return helper.CreateTransaction(sender, &addr, input, nil, !dp.ChildChainMintable), nil } // createMintTxn encodes parameters for mint function on rootchain token contract -func createMintTxn(sender, receiver types.Address, amounts, tokenIDs []*big.Int) (*ethgo.Transaction, error) { +func createMintTxn(sender, receiver types.Address, amounts, tokenIDs []*big.Int) (*types.Transaction, error) { mintFn := &contractsapi.MintBatchRootERC1155Fn{ To: receiver, Amounts: amounts, @@ -278,16 +277,16 @@ func createMintTxn(sender, receiver types.Address, amounts, tokenIDs []*big.Int) return nil, fmt.Errorf("failed to encode provided parameters: %w", err) } - addr := ethgo.Address(types.StringToAddress(dp.TokenAddr)) + addr := types.StringToAddress(dp.TokenAddr) - return helper.CreateTransaction(ethgo.Address(sender), &addr, + return helper.CreateTransaction(sender, &addr, input, nil, !dp.ChildChainMintable), nil } // createApproveERC1155PredicateTxn sends approve transaction // to ERC1155 token for ERC1155 predicate so that it is able to spend given tokens func createApproveERC1155PredicateTxn(rootERC1155Predicate, - rootERC1155Token types.Address) (*ethgo.Transaction, error) { + rootERC1155Token types.Address) (*types.Transaction, error) { approveFnParams := &contractsapi.SetApprovalForAllRootERC1155Fn{ Operator: rootERC1155Predicate, Approved: true, @@ -298,8 +297,6 @@ func createApproveERC1155PredicateTxn(rootERC1155Predicate, return nil, fmt.Errorf("failed to encode parameters for RootERC1155.setApprovalForAll. error: %w", err) } - addr := ethgo.Address(rootERC1155Token) - - return helper.CreateTransaction(ethgo.ZeroAddress, &addr, + return helper.CreateTransaction(types.ZeroAddress, &rootERC1155Token, input, nil, !dp.ChildChainMintable), nil } diff --git a/command/bridge/deposit/erc20/deposit_erc20.go b/command/bridge/deposit/erc20/deposit_erc20.go index 141c77fea9..bf99b53cce 100644 --- a/command/bridge/deposit/erc20/deposit_erc20.go +++ b/command/bridge/deposit/erc20/deposit_erc20.go @@ -267,7 +267,7 @@ func runCommand(cmd *cobra.Command, _ []string) { } // createDepositTxn encodes parameters for deposit function on rootchain predicate contract -func createDepositTxn(sender, receiver types.Address, amount *big.Int) (*ethgo.Transaction, error) { +func createDepositTxn(sender, receiver types.Address, amount *big.Int) (*types.Transaction, error) { depositToFn := &contractsapi.DepositToRootERC20PredicateFn{ RootToken: types.StringToAddress(dp.TokenAddr), Receiver: receiver, @@ -279,8 +279,8 @@ func createDepositTxn(sender, receiver types.Address, amount *big.Int) (*ethgo.T return nil, fmt.Errorf("failed to encode provided parameters: %w", err) } - addr := ethgo.Address(types.StringToAddress(dp.PredicateAddr)) + addr := types.StringToAddress(dp.PredicateAddr) - return helper.CreateTransaction(ethgo.Address(sender), &addr, + return helper.CreateTransaction(sender, &addr, input, nil, !dp.ChildChainMintable), nil } diff --git a/command/bridge/deposit/erc721/deposit_erc721.go b/command/bridge/deposit/erc721/deposit_erc721.go index c56cbf0e7c..6f4fbd1f4b 100644 --- a/command/bridge/deposit/erc721/deposit_erc721.go +++ b/command/bridge/deposit/erc721/deposit_erc721.go @@ -5,6 +5,8 @@ import ( "math/big" "strings" + "github.com/spf13/cobra" + "github.com/0xPolygon/polygon-edge/command" "github.com/0xPolygon/polygon-edge/command/bridge/common" "github.com/0xPolygon/polygon-edge/command/bridge/helper" @@ -12,8 +14,6 @@ import ( helperCommon "github.com/0xPolygon/polygon-edge/helper/common" "github.com/0xPolygon/polygon-edge/txrelayer" "github.com/0xPolygon/polygon-edge/types" - "github.com/spf13/cobra" - "github.com/umbracle/ethgo" ) type depositERC721Params struct { @@ -219,8 +219,8 @@ func runCommand(cmd *cobra.Command, _ []string) { } // createDepositTxn encodes parameters for deposit function on rootchain predicate contract -func createDepositTxn(sender ethgo.Address, - receivers []types.Address, tokenIDs []*big.Int) (*ethgo.Transaction, error) { +func createDepositTxn(sender types.Address, + receivers []types.Address, tokenIDs []*big.Int) (*types.Transaction, error) { depositToRoot := &contractsapi.DepositBatchRootERC721PredicateFn{ RootToken: types.StringToAddress(dp.TokenAddr), Receivers: receivers, @@ -232,13 +232,13 @@ func createDepositTxn(sender ethgo.Address, return nil, fmt.Errorf("failed to encode provided parameters: %w", err) } - addr := ethgo.Address(types.StringToAddress(dp.PredicateAddr)) + addr := types.StringToAddress(dp.PredicateAddr) return helper.CreateTransaction(sender, &addr, input, nil, !dp.ChildChainMintable), nil } // createMintTxn encodes parameters for mint function on rootchain token contract -func createMintTxn(sender, receiver types.Address) (*ethgo.Transaction, error) { +func createMintTxn(sender, receiver types.Address) (*types.Transaction, error) { mintFn := &contractsapi.MintRootERC721Fn{ To: receiver, } @@ -248,14 +248,14 @@ func createMintTxn(sender, receiver types.Address) (*ethgo.Transaction, error) { return nil, fmt.Errorf("failed to encode provided parameters: %w", err) } - addr := ethgo.Address(types.StringToAddress(dp.TokenAddr)) + addr := types.StringToAddress(dp.TokenAddr) - return helper.CreateTransaction(ethgo.Address(sender), &addr, + return helper.CreateTransaction(sender, &addr, input, nil, !dp.ChildChainMintable), nil } // createApproveERC721PredicateTxn sends approve transaction -func createApproveERC721PredicateTxn(rootERC721Predicate, rootERC721Token types.Address) (*ethgo.Transaction, error) { +func createApproveERC721PredicateTxn(rootERC721Predicate, rootERC721Token types.Address) (*types.Transaction, error) { approveFnParams := &contractsapi.SetApprovalForAllRootERC721Fn{ Operator: rootERC721Predicate, Approved: true, @@ -266,8 +266,6 @@ func createApproveERC721PredicateTxn(rootERC721Predicate, rootERC721Token types. return nil, fmt.Errorf("failed to encode parameters for RootERC721.approve. error: %w", err) } - addr := ethgo.Address(rootERC721Token) - - return helper.CreateTransaction(ethgo.ZeroAddress, &addr, input, + return helper.CreateTransaction(types.ZeroAddress, &rootERC721Token, input, nil, !dp.ChildChainMintable), nil } diff --git a/command/bridge/exit/exit.go b/command/bridge/exit/exit.go index 38ce4d39b7..7b083693f2 100644 --- a/command/bridge/exit/exit.go +++ b/command/bridge/exit/exit.go @@ -6,7 +6,6 @@ import ( "strconv" "github.com/spf13/cobra" - "github.com/umbracle/ethgo" "github.com/umbracle/ethgo/jsonrpc" "github.com/0xPolygon/polygon-edge/command" @@ -156,7 +155,7 @@ func run(cmd *cobra.Command, _ []string) { } // createExitTxn encodes parameters for exit function on root chain ExitHelper contract -func createExitTxn(sender ethgo.Address, proof types.Proof) (*ethgo.Transaction, +func createExitTxn(sender types.Address, proof types.Proof) (*types.Transaction, *contractsapi.L2StateSyncedEvent, error) { exitInput, err := polybft.GetExitInputFromProof(proof) if err != nil { @@ -180,9 +179,9 @@ func createExitTxn(sender ethgo.Address, proof types.Proof) (*ethgo.Transaction, return nil, nil, fmt.Errorf("failed to encode provided parameters: %w", err) } - exitHelperAddr := ethgo.Address(types.StringToAddress(ep.exitHelperAddrRaw)) + exitHelperAddr := types.StringToAddress(ep.exitHelperAddrRaw) txn := helper.CreateTransaction(sender, &exitHelperAddr, input, nil, true) - txn.Gas = txrelayer.DefaultGasLimit + txn.SetGas(txrelayer.DefaultGasLimit) return txn, exitEvent, err } diff --git a/command/bridge/finalize/finalize.go b/command/bridge/finalize/finalize.go index 0a05df5faa..bf64951d91 100644 --- a/command/bridge/finalize/finalize.go +++ b/command/bridge/finalize/finalize.go @@ -15,6 +15,7 @@ import ( "github.com/0xPolygon/polygon-edge/consensus/polybft" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" "github.com/0xPolygon/polygon-edge/consensus/polybft/validator" + "github.com/0xPolygon/polygon-edge/crypto" "github.com/0xPolygon/polygon-edge/helper/hex" "github.com/0xPolygon/polygon-edge/txrelayer" "github.com/0xPolygon/polygon-edge/types" @@ -105,7 +106,7 @@ func runCommand(cmd *cobra.Command, _ []string) error { return fmt.Errorf("enlist validator failed: %w", err) } - bladeManagerAddr := ethgo.Address(params.bladeManagerAddr) + bladeManagerAddr := params.bladeManagerAddr // finalize genesis accounts on BladeManager so that no one can stake and premine no more encoded, err := finalizeGenesisABIFn.Encode([]interface{}{}) @@ -145,7 +146,7 @@ func runCommand(cmd *cobra.Command, _ []string) error { return fmt.Errorf("failed to encode genesis set input: %w", err) } - genesisSetHexOut, err := txRelayer.Call(ethgo.ZeroAddress, bladeManagerAddr, genesisSetInput) + genesisSetHexOut, err := txRelayer.Call(types.ZeroAddress, bladeManagerAddr, genesisSetInput) if err != nil { return fmt.Errorf("failed to retrieve genesis set: %w", err) } @@ -315,7 +316,7 @@ func validatorSetToABISlice(o command.OutputFormatter, func initializeCheckpointManager(outputter command.OutputFormatter, txRelayer txrelayer.TxRelayer, consensusConfig polybft.PolyBFTConfig, chainID int64, - deployerKey ethgo.Key) error { + deployerKey crypto.Key) error { validatorSet, err := validatorSetToABISlice(outputter, consensusConfig.InitialValidatorSet) if err != nil { return fmt.Errorf("failed to convert validators to map: %w", err) @@ -333,7 +334,7 @@ func initializeCheckpointManager(outputter command.OutputFormatter, return fmt.Errorf("failed to encode initialization params for CheckpointManager.initialize. error: %w", err) } - if _, err := bridgeHelper.SendTransaction(txRelayer, ethgo.Address(consensusConfig.Bridge.CheckpointManagerAddr), + if _, err := bridgeHelper.SendTransaction(txRelayer, consensusConfig.Bridge.CheckpointManagerAddr, input, "CheckpointManager", deployerKey); err != nil { return err } diff --git a/command/bridge/fund/fund.go b/command/bridge/fund/fund.go index e49406b9e6..1005853bbe 100644 --- a/command/bridge/fund/fund.go +++ b/command/bridge/fund/fund.go @@ -96,8 +96,8 @@ func runCommand(cmd *cobra.Command, _ []string) { return ctx.Err() default: - fundAddr := ethgo.Address(params.addresses[i]) - txn := helper.CreateTransaction(ethgo.ZeroAddress, &fundAddr, nil, params.amountValues[i], true) + fundAddr := params.addresses[i] + txn := helper.CreateTransaction(types.ZeroAddress, &fundAddr, nil, params.amountValues[i], true) var ( receipt *ethgo.Receipt diff --git a/command/bridge/helper/utils.go b/command/bridge/helper/utils.go index cf536b4550..0e930785ee 100644 --- a/command/bridge/helper/utils.go +++ b/command/bridge/helper/utils.go @@ -10,13 +10,13 @@ import ( dockertypes "github.com/docker/docker/api/types" "github.com/docker/docker/client" "github.com/umbracle/ethgo" - "github.com/umbracle/ethgo/wallet" polybftsecrets "github.com/0xPolygon/polygon-edge/command/secrets/init" "github.com/0xPolygon/polygon-edge/consensus/polybft" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" polybftWallet "github.com/0xPolygon/polygon-edge/consensus/polybft/wallet" "github.com/0xPolygon/polygon-edge/contracts" + "github.com/0xPolygon/polygon-edge/crypto" "github.com/0xPolygon/polygon-edge/helper/common" "github.com/0xPolygon/polygon-edge/helper/hex" "github.com/0xPolygon/polygon-edge/txrelayer" @@ -49,7 +49,7 @@ var ( ErrNoAddressesProvided = errors.New("no addresses provided") ErrInconsistentLength = errors.New("addresses and amounts must be equal length") - rootchainAccountKey *wallet.Key + rootchainAccountKey *crypto.ECDSAKey ) type MessageResult struct { @@ -66,7 +66,7 @@ func (r MessageResult) GetOutput() string { } // DecodePrivateKey decodes a private key from provided raw private key -func DecodePrivateKey(rawKey string) (ethgo.Key, error) { +func DecodePrivateKey(rawKey string) (crypto.Key, error) { privateKeyRaw := TestAccountPrivKey if rawKey != "" { privateKeyRaw = rawKey @@ -77,7 +77,7 @@ func DecodePrivateKey(rawKey string) (ethgo.Key, error) { return nil, fmt.Errorf("failed to decode private key string '%s': %w", privateKeyRaw, err) } - rootchainAccountKey, err = wallet.NewWalletFromPrivKey(dec) + rootchainAccountKey, err = crypto.NewECDSAKeyFromRawPrivECDSA(dec) if err != nil { return nil, fmt.Errorf("failed to initialize key from provided private key '%s': %w", privateKeyRaw, err) } @@ -132,7 +132,7 @@ func ReadRootchainIP() (string, error) { // GetECDSAKey returns the key based on provided parameters // If private key is provided, it will return that key // if not, it will return the key from the secrets manager -func GetECDSAKey(privateKey, accountDir, accountConfig string) (ethgo.Key, error) { +func GetECDSAKey(privateKey, accountDir, accountConfig string) (crypto.Key, error) { if privateKey != "" { key, err := DecodePrivateKey(privateKey) if err != nil { @@ -152,9 +152,9 @@ func GetECDSAKey(privateKey, accountDir, accountConfig string) (ethgo.Key, error // GetValidatorInfo queries SupernetManager smart contract on root // and retrieves validator info for given address -func GetValidatorInfo(validatorAddr ethgo.Address, supernetManagerAddr, stakeManagerAddr types.Address, +func GetValidatorInfo(validatorAddr types.Address, supernetManagerAddr, stakeManagerAddr types.Address, txRelayer txrelayer.TxRelayer) (*polybft.ValidatorInfo, error) { - caller := ethgo.Address(contracts.SystemCaller) + caller := contracts.SystemCaller getValidatorMethod := contractsapi.StakeManager.Abi.GetMethod("stakeOf") encode, err := getValidatorMethod.Encode([]interface{}{validatorAddr}) @@ -162,7 +162,7 @@ func GetValidatorInfo(validatorAddr ethgo.Address, supernetManagerAddr, stakeMan return nil, err } - response, err := txRelayer.Call(caller, ethgo.Address(supernetManagerAddr), encode) + response, err := txRelayer.Call(caller, supernetManagerAddr, encode) if err != nil { return nil, err } @@ -203,7 +203,7 @@ func GetValidatorInfo(validatorAddr ethgo.Address, supernetManagerAddr, stakeMan return nil, err } - response, err = txRelayer.Call(caller, ethgo.Address(stakeManagerAddr), encode) + response, err = txRelayer.Call(caller, stakeManagerAddr, encode) if err != nil { return nil, err } @@ -220,7 +220,7 @@ func GetValidatorInfo(validatorAddr ethgo.Address, supernetManagerAddr, stakeMan // CreateMintTxn encodes parameters for mint function on rootchain token contract func CreateMintTxn(receiver, erc20TokenAddr types.Address, - amount *big.Int, rootchainTx bool) (*ethgo.Transaction, error) { + amount *big.Int, rootchainTx bool) (*types.Transaction, error) { mintFn := &contractsapi.MintRootERC20Fn{ To: receiver, Amount: amount, @@ -231,8 +231,7 @@ func CreateMintTxn(receiver, erc20TokenAddr types.Address, return nil, fmt.Errorf("failed to encode provided parameters: %w", err) } - addr := ethgo.Address(erc20TokenAddr) - txn := CreateTransaction(ethgo.ZeroAddress, &addr, input, nil, rootchainTx) + txn := CreateTransaction(types.ZeroAddress, &erc20TokenAddr, input, nil, rootchainTx) return txn, nil } @@ -240,7 +239,7 @@ func CreateMintTxn(receiver, erc20TokenAddr types.Address, // CreateApproveERC20Txn sends approve transaction // to ERC20 token for spender so that it is able to spend given tokens func CreateApproveERC20Txn(amount *big.Int, - spender, erc20TokenAddr types.Address, rootchainTx bool) (*ethgo.Transaction, error) { + spender, erc20TokenAddr types.Address, rootchainTx bool) (*types.Transaction, error) { approveFnParams := &contractsapi.ApproveRootERC20Fn{ Spender: spender, Amount: amount, @@ -251,20 +250,18 @@ func CreateApproveERC20Txn(amount *big.Int, return nil, fmt.Errorf("failed to encode parameters for RootERC20.approve. error: %w", err) } - addr := ethgo.Address(erc20TokenAddr) - - return CreateTransaction(ethgo.ZeroAddress, &addr, input, nil, rootchainTx), nil + return CreateTransaction(types.ZeroAddress, &erc20TokenAddr, input, nil, rootchainTx), nil } // SendTransaction sends provided transaction -func SendTransaction(txRelayer txrelayer.TxRelayer, addr ethgo.Address, input []byte, contractName string, - deployerKey ethgo.Key) (*ethgo.Receipt, error) { - txn := CreateTransaction(ethgo.ZeroAddress, &addr, input, nil, true) +func SendTransaction(txRelayer txrelayer.TxRelayer, addr types.Address, input []byte, contractName string, + deployerKey crypto.Key) (*ethgo.Receipt, error) { + txn := CreateTransaction(types.ZeroAddress, &addr, input, nil, true) receipt, err := txRelayer.SendTransaction(txn, deployerKey) if err != nil { return nil, fmt.Errorf("failed to send transaction to %s contract (%s). error: %w", - contractName, txn.To.Address(), err) + contractName, txn.To(), err) } if receipt == nil || receipt.Status != uint64(types.ReceiptSuccess) { @@ -275,25 +272,21 @@ func SendTransaction(txRelayer txrelayer.TxRelayer, addr ethgo.Address, input [] } // CreateTransaction is a helper function that creates either dynamic fee or legacy transaction based on provided flag -func CreateTransaction(sender ethgo.Address, receiver *ethgo.Address, - input []byte, value *big.Int, isDynamicFeeTx bool) *ethgo.Transaction { - txn := ðgo.Transaction{ - From: sender, - To: receiver, - Input: input, - Value: value, - } - +func CreateTransaction(sender types.Address, receiver *types.Address, + input []byte, value *big.Int, isDynamicFeeTx bool) *types.Transaction { + var txData types.TxData if isDynamicFeeTx { - txn.Type = ethgo.TransactionDynamicFee + txData = types.NewDynamicFeeTx(types.WithFrom(sender), + types.WithTo(receiver), types.WithValue(value), types.WithInput(input)) } else { - txn.Type = ethgo.TransactionLegacy + txData = types.NewLegacyTx(types.WithFrom(sender), + types.WithTo(receiver), types.WithValue(value), types.WithInput(input)) } - return txn + return types.NewTx(txData) } -func DeployProxyContract(txRelayer txrelayer.TxRelayer, deployerKey ethgo.Key, proxyContractName string, +func DeployProxyContract(txRelayer txrelayer.TxRelayer, deployerKey crypto.Key, proxyContractName string, proxyAdmin, logicAddress types.Address) (*ethgo.Receipt, error) { proxyConstructorFn := contractsapi.TransparentUpgradeableProxyConstructorFn{ Logic: logicAddress, @@ -312,7 +305,7 @@ func DeployProxyContract(txRelayer txrelayer.TxRelayer, deployerKey ethgo.Key, p proxyDeployInput = append(proxyDeployInput, contractsapi.TransparentUpgradeableProxy.Bytecode...) proxyDeployInput = append(proxyDeployInput, constructorInput...) - txn := CreateTransaction(ethgo.ZeroAddress, nil, proxyDeployInput, nil, true) + txn := CreateTransaction(types.ZeroAddress, nil, proxyDeployInput, nil, true) receipt, err := txRelayer.SendTransaction(txn, deployerKey) if err != nil { diff --git a/command/bridge/premine/premine.go b/command/bridge/premine/premine.go index 4cc264dedd..82c1dd281b 100644 --- a/command/bridge/premine/premine.go +++ b/command/bridge/premine/premine.go @@ -13,7 +13,6 @@ import ( "github.com/0xPolygon/polygon-edge/txrelayer" "github.com/0xPolygon/polygon-edge/types" "github.com/spf13/cobra" - "github.com/umbracle/ethgo" ) var ( @@ -140,7 +139,7 @@ func runCommand(cmd *cobra.Command, _ []string) error { return err } - bladeManagerAddr := ethgo.Address(types.StringToAddress(params.bladeManager)) + bladeManagerAddr := types.StringToAddress(params.bladeManager) txn := bridgeHelper.CreateTransaction(ownerKey.Address(), &bladeManagerAddr, premineInput, nil, false) receipt, err = txRelayer.SendTransaction(txn, ownerKey) diff --git a/command/bridge/withdraw/erc1155/withdraw_erc1155.go b/command/bridge/withdraw/erc1155/withdraw_erc1155.go index 8789ae6d10..a2f977e113 100644 --- a/command/bridge/withdraw/erc1155/withdraw_erc1155.go +++ b/command/bridge/withdraw/erc1155/withdraw_erc1155.go @@ -7,14 +7,13 @@ import ( "strings" "github.com/spf13/cobra" - "github.com/umbracle/ethgo" - "github.com/umbracle/ethgo/wallet" "github.com/0xPolygon/polygon-edge/command" "github.com/0xPolygon/polygon-edge/command/bridge/common" "github.com/0xPolygon/polygon-edge/command/bridge/helper" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" "github.com/0xPolygon/polygon-edge/contracts" + "github.com/0xPolygon/polygon-edge/crypto" helperCommon "github.com/0xPolygon/polygon-edge/helper/common" "github.com/0xPolygon/polygon-edge/txrelayer" "github.com/0xPolygon/polygon-edge/types" @@ -85,7 +84,7 @@ func runCommand(cmd *cobra.Command, _ []string) { return } - senderAccount, err := wallet.NewWalletFromPrivKey(senderKeyRaw) + senderAccount, err := crypto.NewECDSAKeyFromRawPrivECDSA(senderKeyRaw) if err != nil { outputter.SetError(err) @@ -101,7 +100,7 @@ func runCommand(cmd *cobra.Command, _ []string) { receivers := make([]types.Address, len(wp.Receivers)) amounts := make([]*big.Int, len(wp.Receivers)) - TokenIDs := make([]*big.Int, len(wp.Receivers)) + tokenIDs := make([]*big.Int, len(wp.Receivers)) for i, receiverRaw := range wp.Receivers { receivers[i] = types.StringToAddress(receiverRaw) @@ -123,11 +122,11 @@ func runCommand(cmd *cobra.Command, _ []string) { } amounts[i] = amount - TokenIDs[i] = tokenID + tokenIDs[i] = tokenID } // withdraw tokens transaction - txn, err := createWithdrawTxn(receivers, amounts, TokenIDs) + txn, err := createWithdrawTxn(receivers, amounts, tokenIDs) if err != nil { outputter.SetError(fmt.Errorf("failed to create tx input: %w", err)) @@ -173,12 +172,12 @@ func runCommand(cmd *cobra.Command, _ []string) { } // createWithdrawTxn encodes parameters for withdraw function on child chain predicate contract -func createWithdrawTxn(receivers []types.Address, amounts, TokenIDs []*big.Int) (*ethgo.Transaction, error) { +func createWithdrawTxn(receivers []types.Address, amounts, tokenIDs []*big.Int) (*types.Transaction, error) { withdrawFn := &contractsapi.WithdrawBatchChildERC1155PredicateFn{ ChildToken: types.StringToAddress(wp.TokenAddr), Receivers: receivers, Amounts: amounts, - TokenIDs: TokenIDs, + TokenIDs: tokenIDs, } input, err := withdrawFn.EncodeAbi() @@ -186,8 +185,8 @@ func createWithdrawTxn(receivers []types.Address, amounts, TokenIDs []*big.Int) return nil, fmt.Errorf("failed to encode provided parameters: %w", err) } - addr := ethgo.Address(types.StringToAddress(wp.PredicateAddr)) + addr := types.StringToAddress(wp.PredicateAddr) - return helper.CreateTransaction(ethgo.ZeroAddress, &addr, input, + return helper.CreateTransaction(types.ZeroAddress, &addr, input, nil, wp.ChildChainMintable), nil } diff --git a/command/bridge/withdraw/erc20/withdraw_erc20.go b/command/bridge/withdraw/erc20/withdraw_erc20.go index 360b1c4fd2..1cd3742ff2 100644 --- a/command/bridge/withdraw/erc20/withdraw_erc20.go +++ b/command/bridge/withdraw/erc20/withdraw_erc20.go @@ -6,14 +6,13 @@ import ( "math/big" "github.com/spf13/cobra" - "github.com/umbracle/ethgo" - "github.com/umbracle/ethgo/wallet" "github.com/0xPolygon/polygon-edge/command" "github.com/0xPolygon/polygon-edge/command/bridge/common" "github.com/0xPolygon/polygon-edge/command/bridge/helper" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" "github.com/0xPolygon/polygon-edge/contracts" + "github.com/0xPolygon/polygon-edge/crypto" helperCommon "github.com/0xPolygon/polygon-edge/helper/common" "github.com/0xPolygon/polygon-edge/txrelayer" "github.com/0xPolygon/polygon-edge/types" @@ -76,7 +75,7 @@ func runCommand(cmd *cobra.Command, _ []string) { return } - senderAccount, err := wallet.NewWalletFromPrivKey(senderKeyRaw) + senderAccount, err := crypto.NewECDSAKeyFromRawPrivECDSA(senderKeyRaw) if err != nil { outputter.SetError(err) @@ -152,7 +151,7 @@ func runCommand(cmd *cobra.Command, _ []string) { } // createWithdrawTxn encodes parameters for withdraw function on destination predicate contract -func createWithdrawTxn(receiver types.Address, amount *big.Int) (*ethgo.Transaction, error) { +func createWithdrawTxn(receiver types.Address, amount *big.Int) (*types.Transaction, error) { withdrawToFn := &contractsapi.WithdrawToChildERC20PredicateFn{ ChildToken: types.StringToAddress(wp.TokenAddr), Receiver: receiver, @@ -164,8 +163,8 @@ func createWithdrawTxn(receiver types.Address, amount *big.Int) (*ethgo.Transact return nil, fmt.Errorf("failed to encode provided parameters: %w", err) } - addr := ethgo.Address(types.StringToAddress(wp.PredicateAddr)) + addr := types.StringToAddress(wp.PredicateAddr) - return helper.CreateTransaction(ethgo.ZeroAddress, &addr, input, + return helper.CreateTransaction(types.ZeroAddress, &addr, input, nil, wp.ChildChainMintable), nil } diff --git a/command/bridge/withdraw/erc721/withdraw_erc721.go b/command/bridge/withdraw/erc721/withdraw_erc721.go index c36381ead1..0fa596d5e1 100644 --- a/command/bridge/withdraw/erc721/withdraw_erc721.go +++ b/command/bridge/withdraw/erc721/withdraw_erc721.go @@ -11,12 +11,11 @@ import ( "github.com/0xPolygon/polygon-edge/command/bridge/helper" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" "github.com/0xPolygon/polygon-edge/contracts" + "github.com/0xPolygon/polygon-edge/crypto" helperCommon "github.com/0xPolygon/polygon-edge/helper/common" "github.com/0xPolygon/polygon-edge/txrelayer" "github.com/0xPolygon/polygon-edge/types" "github.com/spf13/cobra" - "github.com/umbracle/ethgo" - "github.com/umbracle/ethgo/wallet" ) var ( @@ -76,7 +75,7 @@ func run(cmd *cobra.Command, _ []string) { return } - senderAccount, err := wallet.NewWalletFromPrivKey(senderKeyRaw) + senderAccount, err := crypto.NewECDSAKeyFromRawPrivECDSA(senderKeyRaw) if err != nil { outputter.SetError(err) @@ -152,7 +151,7 @@ func run(cmd *cobra.Command, _ []string) { } // createWithdrawTxn encodes parameters for withdraw function on child chain predicate contract -func createWithdrawTxn(receivers []types.Address, tokenIDs []*big.Int) (*ethgo.Transaction, error) { +func createWithdrawTxn(receivers []types.Address, tokenIDs []*big.Int) (*types.Transaction, error) { withdrawToFn := &contractsapi.WithdrawBatchChildERC721PredicateFn{ ChildToken: types.StringToAddress(wp.TokenAddr), Receivers: receivers, @@ -164,8 +163,8 @@ func createWithdrawTxn(receivers []types.Address, tokenIDs []*big.Int) (*ethgo.T return nil, fmt.Errorf("failed to encode provided parameters: %w", err) } - addr := ethgo.Address(types.StringToAddress(wp.PredicateAddr)) + addr := types.StringToAddress(wp.PredicateAddr) - return helper.CreateTransaction(ethgo.ZeroAddress, &addr, input, + return helper.CreateTransaction(types.ZeroAddress, &addr, input, nil, wp.ChildChainMintable), nil } diff --git a/command/secrets/init/params_test.go b/command/secrets/init/params_test.go index a95e097dc3..a27671d73f 100644 --- a/command/secrets/init/params_test.go +++ b/command/secrets/init/params_test.go @@ -8,9 +8,9 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/umbracle/ethgo/wallet" "github.com/0xPolygon/polygon-edge/bls" + "github.com/0xPolygon/polygon-edge/crypto" "github.com/0xPolygon/polygon-edge/secrets/helper" ) @@ -94,7 +94,8 @@ func Test_getResult(t *testing.T) { // Test public key serialization privKey, err := hex.DecodeString(sir.PrivateKey) require.NoError(t, err) - k, err := wallet.NewWalletFromPrivKey(privKey) + + k, err := crypto.NewECDSAKeyFromRawPrivECDSA(privKey) require.NoError(t, err) pubKey := k.Address().String() diff --git a/command/validator/helper/helper.go b/command/validator/helper/helper.go index 6ca1e981b3..8ff2be7314 100644 --- a/command/validator/helper/helper.go +++ b/command/validator/helper/helper.go @@ -14,7 +14,6 @@ import ( "github.com/0xPolygon/polygon-edge/helper/hex" "github.com/0xPolygon/polygon-edge/txrelayer" "github.com/0xPolygon/polygon-edge/types" - "github.com/umbracle/ethgo" ) const ( @@ -59,7 +58,7 @@ func GetAccountFromDir(accountDir string) (*wallet.Account, error) { // GetValidatorInfo queries CustomSupernetManager, StakeManager and RewardPool smart contracts // to retrieve validator info for given address -func GetValidatorInfo(validatorAddr ethgo.Address, childRelayer txrelayer.TxRelayer) (*polybft.ValidatorInfo, error) { +func GetValidatorInfo(validatorAddr types.Address, childRelayer txrelayer.TxRelayer) (*polybft.ValidatorInfo, error) { getValidatorMethod := contractsapi.StakeManager.Abi.GetMethod("getValidator") encode, err := getValidatorMethod.Encode([]interface{}{validatorAddr}) @@ -67,8 +66,7 @@ func GetValidatorInfo(validatorAddr ethgo.Address, childRelayer txrelayer.TxRela return nil, err } - response, err := childRelayer.Call(ethgo.Address(contracts.SystemCaller), - ethgo.Address(contracts.StakeManagerContract), encode) + response, err := childRelayer.Call(contracts.SystemCaller, contracts.StakeManagerContract, encode) if err != nil { return nil, err } @@ -109,8 +107,7 @@ func GetValidatorInfo(validatorAddr ethgo.Address, childRelayer txrelayer.TxRela return nil, err } - response, err = childRelayer.Call(ethgo.Address(contracts.SystemCaller), - ethgo.Address(contracts.StakeManagerContract), encode) + response, err = childRelayer.Call(contracts.SystemCaller, contracts.StakeManagerContract, encode) if err != nil { return nil, err } @@ -129,7 +126,7 @@ func GetValidatorInfo(validatorAddr ethgo.Address, childRelayer txrelayer.TxRela return nil, err } - response, err = childRelayer.Call(ethgo.ZeroAddress, ethgo.Address(contracts.EpochManagerContract), encode) + response, err = childRelayer.Call(types.ZeroAddress, contracts.EpochManagerContract, encode) if err != nil { return nil, err } diff --git a/command/validator/registration/register_validator.go b/command/validator/registration/register_validator.go index 9ab1d8d878..59c6416961 100644 --- a/command/validator/registration/register_validator.go +++ b/command/validator/registration/register_validator.go @@ -183,8 +183,7 @@ func registerValidator(sender txrelayer.TxRelayer, account *wallet.Account, return nil, fmt.Errorf("register validator failed: %w", err) } - stakeManagerAddr := ethgo.Address(contracts.StakeManagerContract) - txn := bridgeHelper.CreateTransaction(ethgo.ZeroAddress, &stakeManagerAddr, input, nil, true) + txn := bridgeHelper.CreateTransaction(types.ZeroAddress, &contracts.StakeManagerContract, input, nil, true) return sender.SendTransaction(txn, account.Ecdsa) } diff --git a/command/validator/stake/stake.go b/command/validator/stake/stake.go index 208c87372a..5209d1382d 100644 --- a/command/validator/stake/stake.go +++ b/command/validator/stake/stake.go @@ -4,6 +4,8 @@ import ( "fmt" "time" + "github.com/spf13/cobra" + "github.com/0xPolygon/polygon-edge/command" bridgeHelper "github.com/0xPolygon/polygon-edge/command/bridge/helper" "github.com/0xPolygon/polygon-edge/command/helper" @@ -13,8 +15,6 @@ import ( "github.com/0xPolygon/polygon-edge/contracts" "github.com/0xPolygon/polygon-edge/txrelayer" "github.com/0xPolygon/polygon-edge/types" - "github.com/spf13/cobra" - "github.com/umbracle/ethgo" ) var ( @@ -112,9 +112,8 @@ func runCommand(cmd *cobra.Command, _ []string) error { return err } - stakeManagerAddr := ethgo.Address(contracts.StakeManagerContract) - - txn := bridgeHelper.CreateTransaction(validatorAccount.Ecdsa.Address(), &stakeManagerAddr, encoded, nil, true) + txn := bridgeHelper.CreateTransaction(validatorAccount.Ecdsa.Address(), + &contracts.StakeManagerContract, encoded, nil, true) receipt, err = txRelayer.SendTransaction(txn, validatorAccount.Ecdsa) if err != nil { diff --git a/command/validator/unstake/unstake.go b/command/validator/unstake/unstake.go index 24292b5507..21eb10abcf 100644 --- a/command/validator/unstake/unstake.go +++ b/command/validator/unstake/unstake.go @@ -13,7 +13,6 @@ import ( "github.com/0xPolygon/polygon-edge/txrelayer" "github.com/0xPolygon/polygon-edge/types" "github.com/spf13/cobra" - "github.com/umbracle/ethgo" ) var params unstakeParams @@ -87,11 +86,10 @@ func runCommand(cmd *cobra.Command, _ []string) error { return err } - txn := ðgo.Transaction{ - From: validatorAccount.Ecdsa.Address(), - Input: encoded, - To: (*ethgo.Address)(&contracts.StakeManagerContract), - } + txn := types.NewTx(types.NewLegacyTx( + types.WithFrom(validatorAccount.Ecdsa.Address()), + types.WithInput(encoded), + types.WithTo(&contracts.StakeManagerContract))) receipt, err := txRelayer.SendTransaction(txn, validatorAccount.Ecdsa) if err != nil { diff --git a/command/validator/whitelist/whitelist_validators.go b/command/validator/whitelist/whitelist_validators.go index 4db4afd212..be32fe43ce 100644 --- a/command/validator/whitelist/whitelist_validators.go +++ b/command/validator/whitelist/whitelist_validators.go @@ -13,7 +13,6 @@ import ( "github.com/0xPolygon/polygon-edge/txrelayer" "github.com/0xPolygon/polygon-edge/types" "github.com/spf13/cobra" - "github.com/umbracle/ethgo" ) var params whitelistParams @@ -97,8 +96,7 @@ func runCommand(cmd *cobra.Command, _ []string) error { return fmt.Errorf("whitelist validator failed. Could not abi encode whitelist function: %w", err) } - stakeManagerAddr := ethgo.Address(contracts.StakeManagerContract) - txn := bridgeHelper.CreateTransaction(ecdsaKey.Address(), &stakeManagerAddr, encoded, nil, true) + txn := bridgeHelper.CreateTransaction(ecdsaKey.Address(), &contracts.StakeManagerContract, encoded, nil, true) receipt, err := txRelayer.SendTransaction(txn, ecdsaKey) if err != nil { diff --git a/command/validator/withdraw-rewards/rewards.go b/command/validator/withdraw-rewards/rewards.go index ac21e0e5a8..8a6a383bee 100644 --- a/command/validator/withdraw-rewards/rewards.go +++ b/command/validator/withdraw-rewards/rewards.go @@ -5,7 +5,6 @@ import ( "time" "github.com/spf13/cobra" - "github.com/umbracle/ethgo" "github.com/0xPolygon/polygon-edge/command" bridgeHelper "github.com/0xPolygon/polygon-edge/command/bridge/helper" @@ -69,7 +68,6 @@ func runCommand(cmd *cobra.Command, _ []string) error { } validatorAddr := validatorAccount.Ecdsa.Address() - epochManagerContract := ethgo.Address(contracts.EpochManagerContract) txRelayer, err := txrelayer.NewTxRelayer(txrelayer.WithIPAddress(params.jsonRPC), txrelayer.WithReceiptTimeout(150*time.Millisecond)) @@ -82,7 +80,7 @@ func runCommand(cmd *cobra.Command, _ []string) error { return err } - response, err := txRelayer.Call(validatorAddr, epochManagerContract, encoded) + response, err := txRelayer.Call(validatorAddr, contracts.EpochManagerContract, encoded) if err != nil { return err } @@ -97,7 +95,7 @@ func runCommand(cmd *cobra.Command, _ []string) error { return err } - txn := bridgeHelper.CreateTransaction(validatorAddr, &epochManagerContract, encoded, nil, false) + txn := bridgeHelper.CreateTransaction(validatorAddr, &contracts.EpochManagerContract, encoded, nil, false) receipt, err := txRelayer.SendTransaction(txn, validatorAccount.Ecdsa) if err != nil { diff --git a/command/validator/withdraw/withdraw.go b/command/validator/withdraw/withdraw.go index 75d727d4e9..fd02eb48bf 100644 --- a/command/validator/withdraw/withdraw.go +++ b/command/validator/withdraw/withdraw.go @@ -14,7 +14,6 @@ import ( "github.com/0xPolygon/polygon-edge/txrelayer" "github.com/0xPolygon/polygon-edge/types" "github.com/spf13/cobra" - "github.com/umbracle/ethgo" ) var params withdrawParams @@ -77,8 +76,8 @@ func runCommand(cmd *cobra.Command, _ []string) error { return err } - receiver := (*ethgo.Address)(&contracts.StakeManagerContract) - txn := bridgeHelper.CreateTransaction(validatorAccount.Ecdsa.Address(), receiver, encoded, nil, false) + txn := bridgeHelper.CreateTransaction(validatorAccount.Ecdsa.Address(), + &contracts.StakeManagerContract, encoded, nil, false) receipt, err := txRelayer.SendTransaction(txn, validatorAccount.Ecdsa) if err != nil { diff --git a/consensus/polybft/block_builder_test.go b/consensus/polybft/block_builder_test.go index 041ddfb30a..3d0f984daa 100644 --- a/consensus/polybft/block_builder_test.go +++ b/consensus/polybft/block_builder_test.go @@ -1,12 +1,12 @@ package polybft import ( - "crypto/ecdsa" "math/big" "testing" "time" "github.com/0xPolygon/polygon-edge/chain" + "github.com/0xPolygon/polygon-edge/consensus/polybft/wallet" "github.com/0xPolygon/polygon-edge/crypto" "github.com/0xPolygon/polygon-edge/helper/common" "github.com/0xPolygon/polygon-edge/state" @@ -29,21 +29,13 @@ func TestBlockBuilder_BuildBlockTxOneFailedTxAndOneTakesTooMuchGas(t *testing.T) chainID = 100 ) - type account struct { - privKey *ecdsa.PrivateKey - address types.Address - } - - accounts := [6]*account{} + accounts := make([]*wallet.Account, 0, 6) - for i := range accounts { - ecdsaKey, err := crypto.GenerateECDSAKey() + for i := 0; i < cap(accounts); i++ { + acc, err := wallet.GenerateAccount() require.NoError(t, err) - accounts[i] = &account{ - privKey: ecdsaKey, - address: crypto.PubKeyToAddress(&ecdsaKey.PublicKey), - } + accounts = append(accounts, acc) } forks := &chain.Forks{} @@ -71,7 +63,7 @@ func TestBlockBuilder_BuildBlockTxOneFailedTxAndOneTakesTooMuchGas(t *testing.T) for i, acc := range accounts { // the third tx will fail because of insufficient balance if i != 2 { - balanceMap[acc.address] = &chain.GenesisAccount{Balance: ethgo.Ether(1)} + balanceMap[acc.Address()] = &chain.GenesisAccount{Balance: ethgo.Ether(1)} } } @@ -93,15 +85,19 @@ func TestBlockBuilder_BuildBlockTxOneFailedTxAndOneTakesTooMuchGas(t *testing.T) gas = blockGasLimit - 1 } + recipient := acc.Address() + tx := types.NewTx(types.NewLegacyTx( types.WithGasPrice(big.NewInt(gasPrice)), types.WithValue(big.NewInt(amount)), types.WithGas(gas), types.WithNonce(0), - types.WithTo(&acc.address), + types.WithTo(&recipient), )) - tx, err = signer.SignTx(tx, acc.privKey) + tx, err = signer.SignTxWithCallback(tx, func(hash types.Hash) (sig []byte, err error) { + return acc.Ecdsa.Sign(hash.Bytes()) + }) require.NoError(t, err) // all tx until the fifth will be retrieved from the pool diff --git a/consensus/polybft/blockchain_wrapper.go b/consensus/polybft/blockchain_wrapper.go index 902f2bca19..dd23b9b437 100644 --- a/consensus/polybft/blockchain_wrapper.go +++ b/consensus/polybft/blockchain_wrapper.go @@ -228,6 +228,6 @@ func (s *stateProvider) Call(addr ethgo.Address, input []byte, opts *contract.Ca // Txn is part of the contract.Provider interface to make Ethereum transactions. We disable this function // since the system state does not make any transaction -func (s *stateProvider) Txn(ethgo.Address, ethgo.Key, []byte) (contract.Txn, error) { +func (s *stateProvider) Txn(_ ethgo.Address, _ ethgo.Key, _ []byte) (contract.Txn, error) { return nil, errSendTxnUnsupported } diff --git a/consensus/polybft/checkpoint_manager.go b/consensus/polybft/checkpoint_manager.go index 86ee6c98c5..2fdeaf3533 100644 --- a/consensus/polybft/checkpoint_manager.go +++ b/consensus/polybft/checkpoint_manager.go @@ -10,6 +10,7 @@ import ( "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" "github.com/0xPolygon/polygon-edge/consensus/polybft/validator" "github.com/0xPolygon/polygon-edge/contracts" + "github.com/0xPolygon/polygon-edge/crypto" "github.com/0xPolygon/polygon-edge/helper/hex" "github.com/0xPolygon/polygon-edge/txrelayer" "github.com/0xPolygon/polygon-edge/types" @@ -58,7 +59,7 @@ var _ CheckpointManager = (*checkpointManager)(nil) // checkpointManager encapsulates logic for checkpoint data submission type checkpointManager struct { // key is the identity of the node submitting a checkpoint - key ethgo.Key + key crypto.Key // blockchain is abstraction for blockchain blockchain blockchainBackend // consensusBackend is abstraction for polybft consensus specific functions @@ -76,7 +77,7 @@ type checkpointManager struct { } // newCheckpointManager creates a new instance of checkpointManager -func newCheckpointManager(key ethgo.Key, +func newCheckpointManager(key crypto.Key, checkpointManagerSC types.Address, txRelayer txrelayer.TxRelayer, blockchain blockchainBackend, backend polybftBackend, logger hclog.Logger, state *State) *checkpointManager { @@ -98,7 +99,7 @@ func getCurrentCheckpointBlock(relayer txrelayer.TxRelayer, checkpointManagerAdd return 0, fmt.Errorf("failed to encode currentCheckpointBlockNumber function parameters: %w", err) } - currentCheckpointBlockRaw, err := relayer.Call(ethgo.ZeroAddress, ethgo.Address(checkpointManagerAddr), + currentCheckpointBlockRaw, err := relayer.Call(types.ZeroAddress, checkpointManagerAddr, checkpointBlockNumInput) if err != nil { return 0, fmt.Errorf("failed to invoke currentCheckpointBlockNumber function on the rootchain: %w", err) @@ -198,8 +199,6 @@ func (c *checkpointManager) submitCheckpoint(latestHeader *types.Header, isEndOf func (c *checkpointManager) encodeAndSendCheckpoint(header *types.Header, extra *Extra, isEndOfEpoch bool) error { c.logger.Debug("send checkpoint txn...", "block number", header.Number) - checkpointManager := ethgo.Address(c.checkpointManagerAddr) - nextEpochValidators := validator.AccountSet{} if isEndOfEpoch { @@ -216,11 +215,10 @@ func (c *checkpointManager) encodeAndSendCheckpoint(header *types.Header, extra return fmt.Errorf("failed to encode checkpoint data to ABI for block %d: %w", header.Number, err) } - txn := ðgo.Transaction{ - To: &checkpointManager, - Input: input, - Type: ethgo.TransactionDynamicFee, - } + txn := types.NewTx(types.NewDynamicFeeTx( + types.WithTo(&c.checkpointManagerAddr), + types.WithInput(input), + )) receipt, err := c.rootChainRelayer.SendTransaction(txn, c.key) if err != nil { @@ -331,9 +329,7 @@ func (c *checkpointManager) GenerateExitProof(exitID uint64) (types.Proof, error return types.Proof{}, fmt.Errorf("failed to encode get checkpoint block input: %w", err) } - getCheckpointBlockResp, err := c.rootChainRelayer.Call( - ethgo.ZeroAddress, - ethgo.Address(c.checkpointManagerAddr), + getCheckpointBlockResp, err := c.rootChainRelayer.Call(types.ZeroAddress, c.checkpointManagerAddr, input) if err != nil { return types.Proof{}, fmt.Errorf("failed to retrieve checkpoint block for exit ID %d: %w", exitID, err) diff --git a/consensus/polybft/checkpoint_manager_test.go b/consensus/polybft/checkpoint_manager_test.go index 1e0430ac73..c3a2a03da8 100644 --- a/consensus/polybft/checkpoint_manager_test.go +++ b/consensus/polybft/checkpoint_manager_test.go @@ -11,6 +11,7 @@ import ( "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" + "github.com/0xPolygon/polygon-edge/crypto" merkle "github.com/Ethernal-Tech/merkle-tree" hclog "github.com/hashicorp/go-hclog" "github.com/stretchr/testify/mock" @@ -36,7 +37,7 @@ func TestCheckpointManager_SubmitCheckpoint(t *testing.T) { t.Run("submit checkpoint happy path", func(t *testing.T) { t.Parallel() - var aliases = []string{"A", "B", "C", "D", "E"} + aliases := []string{"A", "B", "C", "D", "E"} validators := validator.NewTestValidatorsWithAliases(t, aliases) validatorsMetadata := validators.GetPublicIdentities() @@ -383,7 +384,7 @@ func TestCheckpointManager_GenerateExitProof(t *testing.T) { require.NoError(t, err) dummyTxRelayer := newDummyTxRelayer(t) - dummyTxRelayer.On("Call", ethgo.ZeroAddress, ethgo.ZeroAddress, input). + dummyTxRelayer.On("Call", types.ZeroAddress, types.ZeroAddress, input). Return(hex.EncodeToString(foundCheckpointReturn), error(nil)) // create checkpoint manager and insert exit events @@ -450,7 +451,7 @@ func TestCheckpointManager_GenerateExitProof(t *testing.T) { inputTwo, err := getCheckpointBlockFn.EncodeAbi() require.NoError(t, err) - dummyTxRelayer.On("Call", ethgo.ZeroAddress, ethgo.ZeroAddress, inputTwo). + dummyTxRelayer.On("Call", types.ZeroAddress, types.ZeroAddress, inputTwo). Return(hex.EncodeToString(notFoundCheckpointReturn), error(nil)) _, err = checkpointMgr.GenerateExitProof(futureBlockToGetExit) @@ -473,14 +474,14 @@ func newDummyTxRelayer(t *testing.T) *dummyTxRelayer { return &dummyTxRelayer{test: t} } -func (d *dummyTxRelayer) Call(from ethgo.Address, to ethgo.Address, input []byte) (string, error) { +func (d *dummyTxRelayer) Call(from types.Address, to types.Address, input []byte) (string, error) { args := d.Called(from, to, input) return args.String(0), args.Error(1) } -func (d *dummyTxRelayer) SendTransaction(transaction *ethgo.Transaction, key ethgo.Key) (*ethgo.Receipt, error) { - blockNumber := getBlockNumberCheckpointSubmitInput(d.test, transaction.Input) +func (d *dummyTxRelayer) SendTransaction(transaction *types.Transaction, key crypto.Key) (*ethgo.Receipt, error) { + blockNumber := getBlockNumberCheckpointSubmitInput(d.test, transaction.Input()) d.checkpointBlocks = append(d.checkpointBlocks, blockNumber) args := d.Called(transaction, key) @@ -488,7 +489,7 @@ func (d *dummyTxRelayer) SendTransaction(transaction *ethgo.Transaction, key eth } // SendTransactionLocal sends non-signed transaction (this is only for testing purposes) -func (d *dummyTxRelayer) SendTransactionLocal(txn *ethgo.Transaction) (*ethgo.Receipt, error) { +func (d *dummyTxRelayer) SendTransactionLocal(txn *types.Transaction) (*ethgo.Receipt, error) { args := d.Called(txn) return args.Get(0).(*ethgo.Receipt), args.Error(1) diff --git a/consensus/polybft/exit_relayer.go b/consensus/polybft/exit_relayer.go index 45d9118772..56c4519876 100644 --- a/consensus/polybft/exit_relayer.go +++ b/consensus/polybft/exit_relayer.go @@ -7,6 +7,7 @@ import ( "math/big" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" + "github.com/0xPolygon/polygon-edge/crypto" "github.com/0xPolygon/polygon-edge/txrelayer" "github.com/0xPolygon/polygon-edge/types" "github.com/hashicorp/go-hclog" @@ -43,7 +44,7 @@ var _ ExitRelayer = (*exitRelayer)(nil) type exitRelayer struct { *relayerEventsProcessor - key ethgo.Key + key crypto.Key proofRetriever ExitEventProofRetriever txRelayer txrelayer.TxRelayer logger hclog.Logger @@ -56,7 +57,7 @@ type exitRelayer struct { // newExitRelayer creates a new instance of exitRelayer func newExitRelayer( txRelayer txrelayer.TxRelayer, - key ethgo.Key, + key crypto.Key, proofRetriever ExitEventProofRetriever, blockchain blockchainBackend, exitStore *ExitStore, @@ -226,12 +227,14 @@ func (e *exitRelayer) sendTx(events []*RelayerEventMetaData) error { return err } + exitTxn := types.NewTx(types.NewLegacyTx( + types.WithFrom(e.key.Address()), + types.WithTo(&e.config.eventExecutionAddr), + types.WithInput(input), + )) + // send batchExecute exit events - _, err = e.txRelayer.SendTransaction(ðgo.Transaction{ - From: e.key.Address(), - To: (*ethgo.Address)(&e.config.eventExecutionAddr), - Input: input, - }, e.key) + _, err = e.txRelayer.SendTransaction(exitTxn, e.key) return err } diff --git a/consensus/polybft/stake_manager_test.go b/consensus/polybft/stake_manager_test.go index 283ead1fc1..c6b5cf4993 100644 --- a/consensus/polybft/stake_manager_test.go +++ b/consensus/polybft/stake_manager_test.go @@ -6,6 +6,7 @@ import ( "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" "github.com/0xPolygon/polygon-edge/consensus/polybft/validator" + "github.com/0xPolygon/polygon-edge/crypto" "github.com/0xPolygon/polygon-edge/helper/hex" "github.com/0xPolygon/polygon-edge/txrelayer" "github.com/0xPolygon/polygon-edge/types" @@ -500,7 +501,7 @@ func newDummyStakeTxRelayer(t *testing.T, callback func() *validator.ValidatorMe } } -func (d *dummyStakeTxRelayer) Call(from ethgo.Address, to ethgo.Address, input []byte) (string, error) { +func (d *dummyStakeTxRelayer) Call(from types.Address, to types.Address, input []byte) (string, error) { args := d.Called(from, to, input) if d.callback != nil { @@ -520,14 +521,14 @@ func (d *dummyStakeTxRelayer) Call(from ethgo.Address, to ethgo.Address, input [ return args.String(0), args.Error(1) } -func (d *dummyStakeTxRelayer) SendTransaction(transaction *ethgo.Transaction, key ethgo.Key) (*ethgo.Receipt, error) { +func (d *dummyStakeTxRelayer) SendTransaction(transaction *types.Transaction, key crypto.Key) (*ethgo.Receipt, error) { args := d.Called(transaction, key) return args.Get(0).(*ethgo.Receipt), args.Error(1) } // SendTransactionLocal sends non-signed transaction (this is only for testing purposes) -func (d *dummyStakeTxRelayer) SendTransactionLocal(txn *ethgo.Transaction) (*ethgo.Receipt, error) { +func (d *dummyStakeTxRelayer) SendTransactionLocal(txn *types.Transaction) (*ethgo.Receipt, error) { args := d.Called(txn) return args.Get(0).(*ethgo.Receipt), args.Error(1) diff --git a/consensus/polybft/state_sync_relayer.go b/consensus/polybft/state_sync_relayer.go index 8007790759..c29fad79b3 100644 --- a/consensus/polybft/state_sync_relayer.go +++ b/consensus/polybft/state_sync_relayer.go @@ -9,6 +9,7 @@ import ( "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" "github.com/0xPolygon/polygon-edge/contracts" + "github.com/0xPolygon/polygon-edge/crypto" "github.com/0xPolygon/polygon-edge/txrelayer" "github.com/0xPolygon/polygon-edge/types" "github.com/hashicorp/go-hclog" @@ -59,7 +60,7 @@ type stateSyncRelayerImpl struct { *relayerEventsProcessor txRelayer txrelayer.TxRelayer - key ethgo.Key + key crypto.Key proofRetriever StateSyncProofRetriever logger hclog.Logger @@ -72,7 +73,7 @@ func newStateSyncRelayer( state *StateSyncStore, store StateSyncProofRetriever, blockchain blockchainBackend, - key ethgo.Key, + key crypto.Key, config *relayerConfig, logger hclog.Logger, ) *stateSyncRelayerImpl { @@ -159,13 +160,15 @@ func (ssr stateSyncRelayerImpl) sendTx(events []*RelayerEventMetaData) error { return err } + txn := types.NewTx(types.NewLegacyTx( + types.WithFrom(ssr.key.Address()), + types.WithTo(&ssr.config.eventExecutionAddr), + types.WithGas(types.StateTransactionGasLimit), + types.WithInput(input), + )) + // send batchExecute state sync - _, err = ssr.txRelayer.SendTransaction(ðgo.Transaction{ - From: ssr.key.Address(), - To: (*ethgo.Address)(&ssr.config.eventExecutionAddr), - Gas: types.StateTransactionGasLimit, - Input: input, - }, ssr.key) + _, err = ssr.txRelayer.SendTransaction(txn, ssr.key) return err } diff --git a/consensus/polybft/system_state.go b/consensus/polybft/system_state.go index 86bfd684e9..96685aa772 100644 --- a/consensus/polybft/system_state.go +++ b/consensus/polybft/system_state.go @@ -13,7 +13,7 @@ import ( // ValidatorInfo is data transfer object which holds validator information, // provided by smart contract type ValidatorInfo struct { - Address ethgo.Address `json:"address"` + Address types.Address `json:"address"` Stake *big.Int `json:"stake"` WithdrawableRewards *big.Int `json:"withdrawableRewards"` IsActive bool `json:"isActive"` diff --git a/consensus/polybft/system_state_test.go b/consensus/polybft/system_state_test.go index ea001fe48b..3f5f038bb2 100644 --- a/consensus/polybft/system_state_test.go +++ b/consensus/polybft/system_state_test.go @@ -17,6 +17,7 @@ import ( "github.com/umbracle/ethgo/abi" "github.com/umbracle/ethgo/contract" "github.com/umbracle/ethgo/testutil" + "github.com/umbracle/ethgo/wallet" ) func TestSystemState_GetNextCommittedIndex(t *testing.T) { @@ -116,13 +117,14 @@ func TestSystemState_GetEpoch(t *testing.T) { func TestStateProvider_Txn_NotSupported(t *testing.T) { t.Parallel() - transition := newTestTransition(t, nil) - provider := &stateProvider{ - transition: transition, + transition: newTestTransition(t, nil), } - _, err := provider.Txn(ethgo.ZeroAddress, createTestKey(t), []byte{0x1}) + key, err := wallet.GenerateKey() + require.NoError(t, err) + + _, err = provider.Txn(ethgo.ZeroAddress, key, []byte{0x1}) require.ErrorIs(t, err, errSendTxnUnsupported) } diff --git a/consensus/polybft/wallet/account.go b/consensus/polybft/wallet/account.go index 7fb7477005..a467dc4d64 100644 --- a/consensus/polybft/wallet/account.go +++ b/consensus/polybft/wallet/account.go @@ -5,22 +5,21 @@ import ( "encoding/hex" "fmt" - "github.com/umbracle/ethgo/wallet" - "github.com/0xPolygon/polygon-edge/bls" + "github.com/0xPolygon/polygon-edge/crypto" "github.com/0xPolygon/polygon-edge/secrets" "github.com/0xPolygon/polygon-edge/types" ) // Account is an account for key signatures type Account struct { - Ecdsa *wallet.Key + Ecdsa *crypto.ECDSAKey Bls *bls.PrivateKey } // GenerateAccount generates a new random account func GenerateAccount() (*Account, error) { - key, err := wallet.GenerateKey() + key, err := crypto.GenerateECDSAKey() if err != nil { return nil, fmt.Errorf("cannot generate key. error: %w", err) } @@ -52,7 +51,7 @@ func NewAccountFromSecret(secretsManager secrets.SecretsManager) (*Account, erro } // GetEcdsaFromSecret retrieves validator(ECDSA) key by using provided secretsManager -func GetEcdsaFromSecret(secretsManager secrets.SecretsManager) (*wallet.Key, error) { +func GetEcdsaFromSecret(secretsManager secrets.SecretsManager) (*crypto.ECDSAKey, error) { encodedKey, err := secretsManager.GetSecret(secrets.ValidatorKey) if err != nil { return nil, fmt.Errorf("failed to retrieve ecdsa key: %w", err) @@ -63,7 +62,7 @@ func GetEcdsaFromSecret(secretsManager secrets.SecretsManager) (*wallet.Key, err return nil, fmt.Errorf("failed to retrieve ecdsa key: %w", err) } - key, err := wallet.NewWalletFromPrivKey(ecdsaRaw) + key, err := crypto.NewECDSAKeyFromRawPrivECDSA(ecdsaRaw) if err != nil { return nil, fmt.Errorf("failed to retrieve ecdsa key: %w", err) } @@ -116,7 +115,7 @@ func (a *Account) GetEcdsaPrivateKey() (*ecdsa.PrivateKey, error) { return nil, err } - return wallet.ParsePrivateKey(ecdsaRaw) + return crypto.ParseECDSAPrivateKey(ecdsaRaw) } func (a Account) Address() types.Address { diff --git a/consensus/polybft/wallet/key.go b/consensus/polybft/wallet/key.go index 1919de1845..7be0085ead 100644 --- a/consensus/polybft/wallet/key.go +++ b/consensus/polybft/wallet/key.go @@ -4,7 +4,6 @@ import ( "fmt" "github.com/0xPolygon/go-ibft/messages/proto" - "github.com/umbracle/ethgo" protobuf "google.golang.org/protobuf/proto" "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" @@ -28,7 +27,7 @@ func (k *Key) String() string { } // Address returns ECDSA address -func (k *Key) Address() ethgo.Address { +func (k *Key) Address() types.Address { return k.raw.Ecdsa.Address() } @@ -73,13 +72,13 @@ func RecoverAddressFromSignature(sig, rawContent []byte) (types.Address, error) return crypto.PubKeyToAddress(pub), nil } -// ECDSASigner implements ethgo.Key interface and it is used for signing using provided ECDSA key +// ECDSASigner implements crypto.Key interface and it is used for signing using provided ECDSA key type ECDSASigner struct { *Key } -func NewEcdsaSigner(ecdsaKey *Key) *ECDSASigner { - return &ECDSASigner{Key: ecdsaKey} +func NewEcdsaSigner(key *Key) *ECDSASigner { + return &ECDSASigner{Key: key} } func (k *ECDSASigner) Sign(b []byte) ([]byte, error) { diff --git a/crypto/crypto.go b/crypto/crypto.go index 061ca03c06..748989243d 100644 --- a/crypto/crypto.go +++ b/crypto/crypto.go @@ -128,8 +128,8 @@ func MarshalECDSAPrivateKey(priv *ecdsa.PrivateKey) ([]byte, error) { return btcPriv.Serialize(), nil } -// GenerateECDSAKey generates a new key based on the secp256k1 elliptic curve. -func GenerateECDSAKey() (*ecdsa.PrivateKey, error) { +// GenerateECDSAPrivateKey generates a new key based on the secp256k1 elliptic curve. +func GenerateECDSAPrivateKey() (*ecdsa.PrivateKey, error) { return ecdsa.GenerateKey(btcec.S256(), rand.Reader) } @@ -264,7 +264,7 @@ func GetAddressFromKey(key goCrypto.PrivateKey) (types.Address, error) { // generateECDSAKeyAndMarshal generates a new ECDSA private key and serializes it to a byte array func generateECDSAKeyAndMarshal() ([]byte, error) { - key, err := GenerateECDSAKey() + key, err := GenerateECDSAPrivateKey() if err != nil { return nil, err } diff --git a/crypto/crypto_test.go b/crypto/crypto_test.go index 613101338f..1b0ef5ef05 100644 --- a/crypto/crypto_test.go +++ b/crypto/crypto_test.go @@ -17,7 +17,7 @@ import ( func TestKeyEncoding(t *testing.T) { for i := 0; i < 10; i++ { - priv, _ := GenerateECDSAKey() + priv, _ := GenerateECDSAPrivateKey() // marshall private key buf, err := MarshalECDSAPrivateKey(priv) @@ -461,7 +461,7 @@ func TestRecoverPublicKey(t *testing.T) { hash := types.BytesToHash([]byte{0, 1, 2}) - privateKey, err := GenerateECDSAKey() + privateKey, err := GenerateECDSAPrivateKey() require.NoError(t, err) signature, err := Sign(privateKey, hash.Bytes()) diff --git a/crypto/ecdsa_key.go b/crypto/ecdsa_key.go new file mode 100644 index 0000000000..3cf502e3f5 --- /dev/null +++ b/crypto/ecdsa_key.go @@ -0,0 +1,76 @@ +package crypto + +import ( + "crypto/ecdsa" + + "github.com/0xPolygon/polygon-edge/types" +) + +type Key interface { + Address() types.Address + Sign(hash []byte) ([]byte, error) +} + +var _ Key = (*ECDSAKey)(nil) + +type ECDSAKey struct { + priv *ecdsa.PrivateKey + pub *ecdsa.PublicKey + addr types.Address +} + +// NewECDSAKey returns new instance of ECDSAKey +func NewECDSAKey(priv *ecdsa.PrivateKey) *ECDSAKey { + return &ECDSAKey{ + priv: priv, + pub: &priv.PublicKey, + addr: PubKeyToAddress(&priv.PublicKey), + } +} + +// GenerateECDSAKey generates an ECDSA private key and wraps it into ECDSA key +// (that is a wrapper for ECDSA private key and holds private key, public key and address) +func GenerateECDSAKey() (*ECDSAKey, error) { + privKey, err := GenerateECDSAPrivateKey() + if err != nil { + return nil, err + } + + return NewECDSAKey(privKey), nil +} + +// NewECDSAKeyFromRawPrivECDSA parses provided +func NewECDSAKeyFromRawPrivECDSA(rawPrivKey []byte) (*ECDSAKey, error) { + priv, err := ParseECDSAPrivateKey(rawPrivKey) + if err != nil { + return nil, err + } + + return NewECDSAKey(priv), nil +} + +// Sign uses the private key and signs the provided hash which produces a signature as a result +func (k *ECDSAKey) Sign(hash []byte) ([]byte, error) { + return Sign(k.priv, hash) +} + +// Address is a getter function for Ethereum address derived from the public key +func (k *ECDSAKey) Address() types.Address { + return k.addr +} + +// MarshallPrivateKey returns 256-bit big-endian binary-encoded representation of the private key +// padded to a length of 32 bytes. +func (k *ECDSAKey) MarshallPrivateKey() ([]byte, error) { + btcPrivKey, err := convertToBtcPrivKey(k.priv) + if err != nil { + return nil, err + } + + return btcPrivKey.Serialize(), nil +} + +// String returns hex encoded ECDSA address +func (k *ECDSAKey) String() string { + return k.addr.String() +} diff --git a/crypto/txsigner.go b/crypto/txsigner.go index 2d43bab9ee..2ef809320d 100644 --- a/crypto/txsigner.go +++ b/crypto/txsigner.go @@ -29,8 +29,12 @@ type TxSigner interface { // Sender returns the sender of the transaction Sender(*types.Transaction) (types.Address, error) - // SingTx takes the original transaction as input and returns its signed version + // SignTx takes the original transaction as input and returns its signed version SignTx(*types.Transaction, *ecdsa.PrivateKey) (*types.Transaction, error) + + // SignTxWithCallback signs a transaction by using a custom callback + SignTxWithCallback(tx *types.Transaction, + signFn func(hash types.Hash) (sig []byte, err error)) (*types.Transaction, error) } // NewSigner creates a new signer based on currently supported forks diff --git a/crypto/txsigner_berlin.go b/crypto/txsigner_berlin.go index 21f9777e2e..85c8a957df 100644 --- a/crypto/txsigner_berlin.go +++ b/crypto/txsigner_berlin.go @@ -113,7 +113,7 @@ func (signer *BerlinSigner) Sender(tx *types.Transaction) (types.Address, error) return recoverAddress(signer.Hash(tx), r, s, v, true) } -// SingTx takes the original transaction as input and returns its signed version +// SignTx takes the original transaction as input and returns its signed version func (signer *BerlinSigner) SignTx(tx *types.Transaction, privateKey *ecdsa.PrivateKey) (*types.Transaction, error) { if tx.Type() == types.DynamicFeeTxType { return nil, types.ErrTxTypeNotSupported @@ -124,7 +124,6 @@ func (signer *BerlinSigner) SignTx(tx *types.Transaction, privateKey *ecdsa.Priv } tx = tx.Copy() - h := signer.Hash(tx) sig, err := Sign(privateKey, h[:]) @@ -152,3 +151,22 @@ func (signer *BerlinSigner) SignTx(tx *types.Transaction, privateKey *ecdsa.Priv func (signer *BerlinSigner) calculateV(parity byte) []byte { return big.NewInt(int64(parity)).Bytes() } + +func (signer *BerlinSigner) SignTxWithCallBack(tx *types.Transaction, + signFn func(hash types.Hash) (sig []byte, err error)) (*types.Transaction, error) { + if tx.Type() != types.AccessListTxType { + return signer.EIP155Signer.SignTxWithCallback(tx, signFn) + } + + tx = tx.Copy() + h := signer.Hash(tx) + + signature, err := signFn(h) + if err != nil { + return nil, err + } + + tx.SplitToRawSignatureValues(signature, signer.calculateV(signature[64])) + + return tx, nil +} diff --git a/crypto/txsigner_eip155.go b/crypto/txsigner_eip155.go index 275dee04c9..114107ac94 100644 --- a/crypto/txsigner_eip155.go +++ b/crypto/txsigner_eip155.go @@ -118,14 +118,13 @@ func (signer *EIP155Signer) Sender(tx *types.Transaction) (types.Address, error) return recoverAddress(signer.Hash(tx), r, s, bigV, true) } -// SingTx takes the original transaction as input and returns its signed version +// SignTx takes the original transaction as input and returns its signed version func (signer *EIP155Signer) SignTx(tx *types.Transaction, privateKey *ecdsa.PrivateKey) (*types.Transaction, error) { if tx.Type() != types.LegacyTxType && tx.Type() != types.StateTxType { return nil, types.ErrTxTypeNotSupported } tx = tx.Copy() - hash := signer.Hash(tx) signature, err := Sign(privateKey, hash[:]) @@ -133,16 +132,31 @@ func (signer *EIP155Signer) SignTx(tx *types.Transaction, privateKey *ecdsa.Priv return nil, err } - r := new(big.Int).SetBytes(signature[:32]) - s := new(big.Int).SetBytes(signature[32:64]) + tx.SplitToRawSignatureValues(signature, signer.calculateV(signature[64])) + _, _, s := tx.RawSignatureValues() if s.Cmp(secp256k1NHalf) > 0 { return nil, errors.New("SignTx method: S must be inclusively lower than secp256k1n/2") } - v := new(big.Int).SetBytes(signer.calculateV(signature[64])) + return tx, nil +} + +func (e *EIP155Signer) SignTxWithCallback(tx *types.Transaction, + signFn func(hash types.Hash) (sig []byte, err error)) (*types.Transaction, error) { + if tx.Type() != types.LegacyTxType && tx.Type() != types.StateTxType { + return nil, types.ErrTxTypeNotSupported + } + + tx = tx.Copy() + h := e.Hash(tx) + + signature, err := signFn(h) + if err != nil { + return nil, err + } - tx.SetSignatureValues(v, r, s) + tx.SplitToRawSignatureValues(signature, e.calculateV(signature[64])) return tx, nil } diff --git a/crypto/txsigner_eip155_test.go b/crypto/txsigner_eip155_test.go index 6489b6d110..ce6acfb9c0 100644 --- a/crypto/txsigner_eip155_test.go +++ b/crypto/txsigner_eip155_test.go @@ -65,7 +65,7 @@ func TestEIP155Signer_Sender(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() - key, keyGenError := GenerateECDSAKey() + key, keyGenError := GenerateECDSAPrivateKey() if keyGenError != nil { t.Fatalf("Unable to generate key") } @@ -100,7 +100,7 @@ func TestEIP155Signer_ChainIDMismatch(t *testing.T) { toAddress := types.StringToAddress("1") for _, chainIDTop := range chainIDS { - key, keyGenError := GenerateECDSAKey() + key, keyGenError := GenerateECDSAPrivateKey() if keyGenError != nil { t.Fatalf("Unable to generate key") } diff --git a/crypto/txsigner_frontier.go b/crypto/txsigner_frontier.go index 26158576d2..c7631d75da 100644 --- a/crypto/txsigner_frontier.go +++ b/crypto/txsigner_frontier.go @@ -89,20 +89,19 @@ func (signer *FrontierSigner) sender(tx *types.Transaction, isHomestead bool) (t return recoverAddress(signer.Hash(tx), r, s, parity, isHomestead) } -// SingTx takes the original transaction as input and returns its signed version +// SignTx takes the original transaction as input and returns its signed version func (signer *FrontierSigner) SignTx(tx *types.Transaction, privateKey *ecdsa.PrivateKey) (*types.Transaction, error) { - return signer.signTx(tx, privateKey, nil) + return signer.signTxInternal(tx, privateKey) } -// SingTx takes the original transaction as input and returns its signed version -func (signer *FrontierSigner) signTx(tx *types.Transaction, privateKey *ecdsa.PrivateKey, - validateFn func(v, r, s *big.Int) error) (*types.Transaction, error) { +// signTxInternal takes the original transaction as input and returns its signed version +func (signer *FrontierSigner) signTxInternal(tx *types.Transaction, + privateKey *ecdsa.PrivateKey) (*types.Transaction, error) { if tx.Type() != types.LegacyTxType && tx.Type() != types.StateTxType { return nil, types.ErrTxTypeNotSupported } tx = tx.Copy() - hash := signer.Hash(tx) signature, err := Sign(privateKey, hash[:]) @@ -110,17 +109,27 @@ func (signer *FrontierSigner) signTx(tx *types.Transaction, privateKey *ecdsa.Pr return nil, err } - r := new(big.Int).SetBytes(signature[:32]) - s := new(big.Int).SetBytes(signature[32:64]) - v := new(big.Int).SetBytes(signer.calculateV(signature[64])) + tx.SplitToRawSignatureValues(signature, signer.calculateV(signature[64])) + + return tx, nil +} + +func (f *FrontierSigner) SignTxWithCallback( + tx *types.Transaction, + signFn func(hash types.Hash) (sig []byte, err error)) (*types.Transaction, error) { + if tx.Type() != types.LegacyTxType && tx.Type() != types.StateTxType { + return nil, types.ErrTxTypeNotSupported + } + + tx = tx.Copy() + h := f.Hash(tx) - if validateFn != nil { - if err := validateFn(v, r, s); err != nil { - return nil, err - } + signature, err := signFn(h) + if err != nil { + return nil, err } - tx.SetSignatureValues(v, r, s) + tx.SplitToRawSignatureValues(signature, f.calculateV(signature[64])) return tx, nil } diff --git a/crypto/txsigner_frontier_test.go b/crypto/txsigner_frontier_test.go index 80dba4c6af..36cc97f4fa 100644 --- a/crypto/txsigner_frontier_test.go +++ b/crypto/txsigner_frontier_test.go @@ -12,7 +12,7 @@ func TestFrontierSigner(t *testing.T) { signer := &FrontierSigner{} toAddress := types.StringToAddress("1") - key, err := GenerateECDSAKey() + key, err := GenerateECDSAPrivateKey() assert.NoError(t, err) txn := types.NewTx(types.NewLegacyTx( diff --git a/crypto/txsigner_homestead.go b/crypto/txsigner_homestead.go index d4ff10a0ac..8ffea6d229 100644 --- a/crypto/txsigner_homestead.go +++ b/crypto/txsigner_homestead.go @@ -3,7 +3,6 @@ package crypto import ( "crypto/ecdsa" "errors" - "math/big" "github.com/0xPolygon/polygon-edge/types" ) @@ -40,16 +39,20 @@ func (signer *HomesteadSigner) Sender(tx *types.Transaction) (types.Address, err return signer.sender(tx, true) } -// SingTx takes the original transaction as input and returns its signed version +// SignTx takes the original transaction as input and returns its signed version func (signer *HomesteadSigner) SignTx(tx *types.Transaction, privateKey *ecdsa.PrivateKey) (*types.Transaction, error) { - return signer.signTx(tx, privateKey, func(v, r, s *big.Int) error { - // Homestead hard-fork introduced the rule that the S value - // must be inclusively lower than the half of the secp256k1 curve order - // Specification: https://eips.ethereum.org/EIPS/eip-2#specification (2) - if s.Cmp(secp256k1NHalf) > 0 { - return errors.New("SignTx method: S must be inclusively lower than secp256k1n/2") - } - - return nil - }) + tx, err := signer.signTxInternal(tx, privateKey) + if err != nil { + return nil, err + } + + _, _, s := tx.RawSignatureValues() + // Homestead hard-fork introduced the rule that the S value + // must be inclusively lower than the half of the secp256k1 curve order + // Specification: https://eips.ethereum.org/EIPS/eip-2#specification (2) + if s.Cmp(secp256k1NHalf) > 0 { + return nil, errors.New("SignTx method: S must be inclusively lower than secp256k1n/2") + } + + return tx, nil } diff --git a/crypto/txsigner_london.go b/crypto/txsigner_london.go index 0c2d140a19..9b844787a4 100644 --- a/crypto/txsigner_london.go +++ b/crypto/txsigner_london.go @@ -115,14 +115,13 @@ func (signer *LondonSigner) Sender(tx *types.Transaction) (types.Address, error) return recoverAddress(signer.Hash(tx), r, s, v, true) } -// SingTx takes the original transaction as input and returns its signed version +// SignTx takes the original transaction as input and returns its signed version func (signer *LondonSigner) SignTx(tx *types.Transaction, privateKey *ecdsa.PrivateKey) (*types.Transaction, error) { if tx.Type() != types.DynamicFeeTxType { return signer.BerlinSigner.SignTx(tx, privateKey) } tx = tx.Copy() - h := signer.Hash(tx) sig, err := Sign(privateKey, h[:]) @@ -143,3 +142,22 @@ func (signer *LondonSigner) SignTx(tx *types.Transaction, privateKey *ecdsa.Priv return tx, nil } + +func (signer *LondonSigner) SignTxWithCallback(tx *types.Transaction, + signFn func(hash types.Hash) (sig []byte, err error)) (*types.Transaction, error) { + if tx.Type() != types.DynamicFeeTxType { + return signer.BerlinSigner.SignTxWithCallback(tx, signFn) + } + + tx = tx.Copy() + h := signer.Hash(tx) + + signature, err := signFn(h) + if err != nil { + return nil, err + } + + tx.SplitToRawSignatureValues(signature, signer.calculateV(signature[64])) + + return tx, nil +} diff --git a/crypto/txsigner_london_test.go b/crypto/txsigner_london_test.go index 48067deb1e..455a752421 100644 --- a/crypto/txsigner_london_test.go +++ b/crypto/txsigner_london_test.go @@ -67,7 +67,7 @@ func TestLondonSignerSender(t *testing.T) { t.Run(tc.name, func(t *testing.T) { t.Parallel() - key, err := GenerateECDSAKey() + key, err := GenerateECDSAPrivateKey() require.NoError(t, err, "unable to generate private key") var txn *types.Transaction diff --git a/e2e-polybft/e2e/acls_test.go b/e2e-polybft/e2e/acls_test.go index 4d3b9d0490..154a0717f6 100644 --- a/e2e-polybft/e2e/acls_test.go +++ b/e2e-polybft/e2e/acls_test.go @@ -5,12 +5,12 @@ import ( "testing" "github.com/0xPolygon/polygon-edge/contracts" + "github.com/0xPolygon/polygon-edge/crypto" "github.com/0xPolygon/polygon-edge/e2e-polybft/framework" "github.com/0xPolygon/polygon-edge/helper/hex" "github.com/0xPolygon/polygon-edge/state/runtime/addresslist" "github.com/0xPolygon/polygon-edge/types" "github.com/stretchr/testify/require" - "github.com/umbracle/ethgo/wallet" ) // Contract used as bytecode @@ -34,11 +34,11 @@ func TestE2E_AllowList_ContractDeployment(t *testing.T) { // create two accounts, one for an admin sender and a second // one for a non-enabled account that will switch on-off between // both enabled and non-enabled roles. - admin, _ := wallet.GenerateKey() - target, _ := wallet.GenerateKey() + admin, _ := crypto.GenerateECDSAKey() + target, _ := crypto.GenerateECDSAKey() - adminAddr := types.Address(admin.Address()) - targetAddr := types.Address(target.Address()) + adminAddr := admin.Address() + targetAddr := target.Address() otherAddr := types.Address{0x1} @@ -132,17 +132,14 @@ func TestE2E_BlockList_ContractDeployment(t *testing.T) { // create two accounts, one for an admin sender and a second // one for a non-enabled account that will switch on-off between // both enabled and non-enabled roles. - admin, _ := wallet.GenerateKey() - target, _ := wallet.GenerateKey() - - adminAddr := types.Address(admin.Address()) - targetAddr := types.Address(target.Address()) + admin, _ := crypto.GenerateECDSAKey() + target, _ := crypto.GenerateECDSAKey() otherAddr := types.Address{0x1} cluster := framework.NewTestCluster(t, 5, - framework.WithPremine(adminAddr, targetAddr), - framework.WithContractDeployerBlockListAdmin(adminAddr), + framework.WithPremine(admin.Address(), target.Address()), + framework.WithContractDeployerBlockListAdmin(admin.Address()), framework.WithContractDeployerBlockListEnabled(otherAddr), ) defer cluster.Stop() @@ -155,8 +152,8 @@ func TestE2E_BlockList_ContractDeployment(t *testing.T) { { // Step 0. Check the role of accounts - expectRole(t, cluster, contracts.BlockListContractsAddr, adminAddr, addresslist.AdminRole) - expectRole(t, cluster, contracts.BlockListContractsAddr, targetAddr, addresslist.NoRole) + expectRole(t, cluster, contracts.BlockListContractsAddr, admin.Address(), addresslist.AdminRole) + expectRole(t, cluster, contracts.BlockListContractsAddr, target.Address(), addresslist.NoRole) expectRole(t, cluster, contracts.BlockListContractsAddr, otherAddr, addresslist.EnabledRole) } @@ -184,11 +181,11 @@ func TestE2E_BlockList_ContractDeployment(t *testing.T) { { // Step 4. 'adminAddr' sends a transaction to enable 'targetAddr'. - input, _ := addresslist.SetEnabledFunc.Encode([]interface{}{targetAddr}) + input, _ := addresslist.SetEnabledFunc.Encode([]interface{}{target.Address()}) adminSetTxn := cluster.MethodTxn(t, admin, contracts.BlockListContractsAddr, input) require.NoError(t, adminSetTxn.Wait()) - expectRole(t, cluster, contracts.BlockListContractsAddr, targetAddr, addresslist.EnabledRole) + expectRole(t, cluster, contracts.BlockListContractsAddr, target.Address(), addresslist.EnabledRole) } { @@ -215,18 +212,14 @@ func TestE2E_AllowList_Transactions(t *testing.T) { // create two accounts, one for an admin sender and a second // one for a non-enabled account that will switch on-off between // both enabled and non-enabled roles. - admin, _ := wallet.GenerateKey() - target, _ := wallet.GenerateKey() - other, _ := wallet.GenerateKey() - - adminAddr := types.Address(admin.Address()) - targetAddr := types.Address(target.Address()) - otherAddr := types.Address(other.Address()) + admin, _ := crypto.GenerateECDSAKey() + target, _ := crypto.GenerateECDSAKey() + other, _ := crypto.GenerateECDSAKey() cluster := framework.NewTestCluster(t, 5, - framework.WithPremine(adminAddr, targetAddr, otherAddr), - framework.WithTransactionsAllowListAdmin(adminAddr), - framework.WithTransactionsAllowListEnabled(otherAddr), + framework.WithPremine(admin.Address(), target.Address(), other.Address()), + framework.WithTransactionsAllowListAdmin(admin.Address()), + framework.WithTransactionsAllowListEnabled(other.Address()), ) defer cluster.Stop() @@ -237,9 +230,9 @@ func TestE2E_AllowList_Transactions(t *testing.T) { { // Step 0. Check the role of both accounts - expectRole(t, cluster, contracts.AllowListTransactionsAddr, adminAddr, addresslist.AdminRole) - expectRole(t, cluster, contracts.AllowListTransactionsAddr, targetAddr, addresslist.NoRole) - expectRole(t, cluster, contracts.AllowListTransactionsAddr, otherAddr, addresslist.EnabledRole) + expectRole(t, cluster, contracts.AllowListTransactionsAddr, admin.Address(), addresslist.AdminRole) + expectRole(t, cluster, contracts.AllowListTransactionsAddr, target.Address(), addresslist.NoRole) + expectRole(t, cluster, contracts.AllowListTransactionsAddr, other.Address(), addresslist.EnabledRole) } { @@ -268,11 +261,11 @@ func TestE2E_AllowList_Transactions(t *testing.T) { { // Step 3. 'adminAddr' sends a transaction to enable 'targetAddr'. - input, _ := addresslist.SetEnabledFunc.Encode([]interface{}{targetAddr}) + input, _ := addresslist.SetEnabledFunc.Encode([]interface{}{target.Address()}) adminSetTxn := cluster.MethodTxn(t, admin, contracts.AllowListTransactionsAddr, input) require.NoError(t, adminSetTxn.Wait()) - expectRole(t, cluster, contracts.AllowListTransactionsAddr, targetAddr, addresslist.EnabledRole) + expectRole(t, cluster, contracts.AllowListTransactionsAddr, target.Address(), addresslist.EnabledRole) } { @@ -295,12 +288,12 @@ func TestE2E_AllowList_Transactions(t *testing.T) { { // Step 6. 'adminAddr' sends a transaction to disable himself. - input, _ := addresslist.SetNoneFunc.Encode([]interface{}{adminAddr}) + input, _ := addresslist.SetNoneFunc.Encode([]interface{}{admin.Address()}) noneSetTxn := cluster.MethodTxn(t, admin, contracts.AllowListTransactionsAddr, input) require.NoError(t, noneSetTxn.Wait()) require.True(t, noneSetTxn.Failed()) - expectRole(t, cluster, contracts.AllowListTransactionsAddr, adminAddr, addresslist.AdminRole) + expectRole(t, cluster, contracts.AllowListTransactionsAddr, admin.Address(), addresslist.AdminRole) } } @@ -308,18 +301,14 @@ func TestE2E_BlockList_Transactions(t *testing.T) { // create two accounts, one for an admin sender and a second // one for a non-enabled account that will switch on-off between // both enabled and non-enabled roles. - admin, _ := wallet.GenerateKey() - target, _ := wallet.GenerateKey() - other, _ := wallet.GenerateKey() - - adminAddr := types.Address(admin.Address()) - targetAddr := types.Address(target.Address()) - otherAddr := types.Address(other.Address()) + admin, _ := crypto.GenerateECDSAKey() + target, _ := crypto.GenerateECDSAKey() + other, _ := crypto.GenerateECDSAKey() cluster := framework.NewTestCluster(t, 5, - framework.WithPremine(adminAddr, targetAddr, otherAddr), - framework.WithTransactionsBlockListAdmin(adminAddr), - framework.WithTransactionsBlockListEnabled(otherAddr), + framework.WithPremine(admin.Address(), target.Address(), other.Address()), + framework.WithTransactionsBlockListAdmin(admin.Address()), + framework.WithTransactionsBlockListEnabled(other.Address()), ) defer cluster.Stop() @@ -327,9 +316,9 @@ func TestE2E_BlockList_Transactions(t *testing.T) { { // Step 0. Check the role of both accounts - expectRole(t, cluster, contracts.BlockListTransactionsAddr, adminAddr, addresslist.AdminRole) - expectRole(t, cluster, contracts.BlockListTransactionsAddr, targetAddr, addresslist.NoRole) - expectRole(t, cluster, contracts.BlockListTransactionsAddr, otherAddr, addresslist.EnabledRole) + expectRole(t, cluster, contracts.BlockListTransactionsAddr, admin.Address(), addresslist.AdminRole) + expectRole(t, cluster, contracts.BlockListTransactionsAddr, target.Address(), addresslist.NoRole) + expectRole(t, cluster, contracts.BlockListTransactionsAddr, other.Address(), addresslist.EnabledRole) } { @@ -359,11 +348,11 @@ func TestE2E_BlockList_Transactions(t *testing.T) { { // Step 4. 'adminAddr' sends a transaction to enable 'targetAddr'. - input, _ := addresslist.SetEnabledFunc.Encode([]interface{}{targetAddr}) + input, _ := addresslist.SetEnabledFunc.Encode([]interface{}{target.Address()}) adminSetTxn := cluster.MethodTxn(t, admin, contracts.BlockListTransactionsAddr, input) require.NoError(t, adminSetTxn.Wait()) - expectRole(t, cluster, contracts.BlockListTransactionsAddr, targetAddr, addresslist.EnabledRole) + expectRole(t, cluster, contracts.BlockListTransactionsAddr, target.Address(), addresslist.EnabledRole) } { @@ -378,9 +367,9 @@ func TestE2E_AddressLists_Bridge(t *testing.T) { // create two accounts, one for an admin sender and a second // one for a non-enabled account that will switch on-off between // both enabled and non-enabled roles. - admin, _ := wallet.GenerateKey() - target, _ := wallet.GenerateKey() - other, _ := wallet.GenerateKey() + admin, _ := crypto.GenerateECDSAKey() + target, _ := crypto.GenerateECDSAKey() + other, _ := crypto.GenerateECDSAKey() adminAddr := types.Address(admin.Address()) targetAddr := types.Address(target.Address()) diff --git a/e2e-polybft/e2e/bridge_test.go b/e2e-polybft/e2e/bridge_test.go index 921e26605c..409a4d5a09 100644 --- a/e2e-polybft/e2e/bridge_test.go +++ b/e2e-polybft/e2e/bridge_test.go @@ -11,7 +11,6 @@ import ( "github.com/stretchr/testify/require" "github.com/umbracle/ethgo" - "github.com/umbracle/ethgo/wallet" "github.com/0xPolygon/polygon-edge/command" "github.com/0xPolygon/polygon-edge/command/bridge/common" @@ -20,6 +19,7 @@ import ( "github.com/0xPolygon/polygon-edge/consensus/polybft" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" "github.com/0xPolygon/polygon-edge/contracts" + "github.com/0xPolygon/polygon-edge/crypto" "github.com/0xPolygon/polygon-edge/e2e-polybft/framework" helperCommon "github.com/0xPolygon/polygon-edge/helper/common" "github.com/0xPolygon/polygon-edge/state/runtime/addresslist" @@ -53,7 +53,7 @@ func TestE2E_Bridge_RootchainTokensTransfers(t *testing.T) { receiverKeys := make([]string, transfersCount) for i := 0; i < transfersCount; i++ { - key, err := wallet.GenerateKey() + key, err := crypto.GenerateECDSAKey() require.NoError(t, err) rawKey, err := key.MarshallPrivateKey() @@ -100,12 +100,12 @@ func TestE2E_Bridge_RootchainTokensTransfers(t *testing.T) { deployerKey, err := bridgeHelper.DecodePrivateKey("") require.NoError(t, err) - receipt, err := rootchainTxRelayer.SendTransaction( - ðgo.Transaction{ - To: nil, - Input: contractsapi.RootERC20.Bytecode, - }, - deployerKey) + deployTx := types.NewTx(types.NewLegacyTx( + types.WithTo(nil), + types.WithInput(contractsapi.RootERC20.Bytecode), + )) + + receipt, err := rootchainTxRelayer.SendTransaction(deployTx, deployerKey) require.NoError(t, err) require.NotNil(t, receipt) require.Equal(t, uint64(types.ReceiptSuccess), receipt.Status) @@ -206,7 +206,7 @@ func TestE2E_Bridge_RootchainTokensTransfers(t *testing.T) { require.NoError(t, err) // check that we submitted the minimal commitment to smart contract - commitmentIDRaw, err := txRelayer.Call(ethgo.ZeroAddress, ethgo.Address(contracts.StateReceiverContract), lastCommittedIDInput) + commitmentIDRaw, err := txRelayer.Call(types.ZeroAddress, contracts.StateReceiverContract, lastCommittedIDInput) require.NoError(t, err) initialCommittedID, err := helperCommon.ParseUint64orHex(&commitmentIDRaw) @@ -239,8 +239,8 @@ func TestE2E_Bridge_RootchainTokensTransfers(t *testing.T) { require.NoError(t, cluster.WaitForBlock(midBlockNumber, 2*time.Minute)) // check that we submitted the minimal commitment to smart contract - commitmentIDRaw, err = txRelayer.Call(ethgo.ZeroAddress, - ethgo.Address(contracts.StateReceiverContract), lastCommittedIDInput) + commitmentIDRaw, err = txRelayer.Call(types.ZeroAddress, + contracts.StateReceiverContract, lastCommittedIDInput) require.NoError(t, err) lastCommittedID, err := helperCommon.ParseUint64orHex(&commitmentIDRaw) @@ -266,7 +266,7 @@ func TestE2E_Bridge_RootchainTokensTransfers(t *testing.T) { require.NoError(t, cluster.WaitForBlock(midBlockNumber+5*sprintSize, 3*time.Minute)) // check that we submitted the minimal commitment to smart contract - commitmentIDRaw, err = txRelayer.Call(ethgo.ZeroAddress, ethgo.Address(contracts.StateReceiverContract), lastCommittedIDInput) + commitmentIDRaw, err = txRelayer.Call(types.ZeroAddress, contracts.StateReceiverContract, lastCommittedIDInput) require.NoError(t, err) // check that the second (larger commitment) was also submitted in epoch @@ -298,7 +298,7 @@ func TestE2E_Bridge_ERC721Transfer(t *testing.T) { tokenIDs := make([]string, transfersCount) for i := 0; i < transfersCount; i++ { - key, err := wallet.GenerateKey() + key, err := crypto.GenerateECDSAKey() require.NoError(t, err) rawKey, err := key.MarshallPrivateKey() @@ -335,12 +335,15 @@ func TestE2E_Bridge_ERC721Transfer(t *testing.T) { rootchainDeployer, err := bridgeHelper.DecodePrivateKey("") require.NoError(t, err) - // deploy root ERC 721 token - receipt, err := rootchainTxRelayer.SendTransaction( - ðgo.Transaction{ + deployTx := types.NewTx(&types.LegacyTx{ + BaseTx: &types.BaseTx{ To: nil, Input: contractsapi.RootERC721.Bytecode, - }, rootchainDeployer) + }, + }) + + // deploy root ERC 721 token + receipt, err := rootchainTxRelayer.SendTransaction(deployTx, rootchainDeployer) require.NoError(t, err) rootERC721Addr := receipt.ContractAddress @@ -467,7 +470,7 @@ func TestE2E_Bridge_ERC1155Transfer(t *testing.T) { tokenIDs := make([]string, transfersCount) for i := 0; i < transfersCount; i++ { - key, err := wallet.GenerateKey() + key, err := crypto.GenerateECDSAKey() require.NoError(t, err) rawKey, err := key.MarshallPrivateKey() @@ -506,15 +509,18 @@ func TestE2E_Bridge_ERC1155Transfer(t *testing.T) { rootchainDeployer, err := bridgeHelper.DecodePrivateKey("") require.NoError(t, err) - // deploy root ERC 1155 token - receipt, err := rootchainTxRelayer.SendTransaction( - ðgo.Transaction{ + deployTx := types.NewTx(&types.LegacyTx{ + BaseTx: &types.BaseTx{ To: nil, Input: contractsapi.RootERC1155.Bytecode, - }, rootchainDeployer) + }, + }) + + // deploy root ERC 1155 token + receipt, err := rootchainTxRelayer.SendTransaction(deployTx, rootchainDeployer) require.NoError(t, err) - rootERC1155Addr := receipt.ContractAddress + rootERC1155Addr := types.Address(receipt.ContractAddress) // DEPOSIT ERC1155 TOKENS // send a few transactions to the bridge @@ -581,7 +587,7 @@ func TestE2E_Bridge_ERC1155Transfer(t *testing.T) { balanceInput, err := balanceOfFn.EncodeAbi() require.NoError(t, err) - balanceRaw, err := txRelayer.Call(ethgo.ZeroAddress, ethgo.Address(l2ChildTokenAddr), balanceInput) + balanceRaw, err := txRelayer.Call(types.ZeroAddress, l2ChildTokenAddr, balanceInput) require.NoError(t, err) balance, err := helperCommon.ParseUint256orHex(&balanceRaw) @@ -644,7 +650,7 @@ func TestE2E_Bridge_ERC1155Transfer(t *testing.T) { balanceInput, err := balanceOfFn.EncodeAbi() require.NoError(t, err) - balanceRaw, err := rootchainTxRelayer.Call(ethgo.ZeroAddress, rootERC1155Addr, balanceInput) + balanceRaw, err := rootchainTxRelayer.Call(types.ZeroAddress, rootERC1155Addr, balanceInput) require.NoError(t, err) balance, err := helperCommon.ParseUint256orHex(&balanceRaw) @@ -670,13 +676,13 @@ func TestE2E_Bridge_ChildchainTokensTransfer(t *testing.T) { funds := make([]*big.Int, transfersCount) singleToken := ethgo.Ether(1) - admin, err := wallet.GenerateKey() + admin, err := crypto.GenerateECDSAKey() require.NoError(t, err) adminAddr := types.Address(admin.Address()) for i := uint64(0); i < transfersCount; i++ { - key, err := wallet.GenerateKey() + key, err := crypto.GenerateECDSAKey() require.NoError(t, err) rawKey, err := key.MarshallPrivateKey() @@ -997,7 +1003,7 @@ func TestE2E_CheckpointSubmission(t *testing.T) { polybftCfg, err := polybft.LoadPolyBFTConfig(path.Join(cluster.Config.TmpDir, chainConfigFileName)) require.NoError(t, err) - checkpointManagerAddr := ethgo.Address(polybftCfg.Bridge.CheckpointManagerAddr) + checkpointManagerAddr := polybftCfg.Bridge.CheckpointManagerAddr testCheckpointBlockNumber := func(expectedCheckpointBlock uint64) (bool, error) { actualCheckpointBlock, err := getCheckpointBlockNumber(rootChainRelayer, checkpointManagerAddr) @@ -1049,7 +1055,7 @@ func TestE2E_Bridge_Transfers_AccessLists(t *testing.T) { depositAmounts := make([]string, transfersCount) withdrawAmounts := make([]string, transfersCount) - admin, _ := wallet.GenerateKey() + admin, _ := crypto.GenerateECDSAKey() adminAddr := types.Address(admin.Address()) cluster := framework.NewTestCluster(t, 5, @@ -1098,11 +1104,13 @@ func TestE2E_Bridge_Transfers_AccessLists(t *testing.T) { deployerKey, err := bridgeHelper.DecodePrivateKey("") require.NoError(t, err) + deployTx := types.NewTx(types.NewLegacyTx( + types.WithTo(nil), + types.WithInput(contractsapi.RootERC20.Bytecode), + )) + // deploy root erc20 token - receipt, err := rootchainTxRelayer.SendTransaction( - ðgo.Transaction{ - To: nil, Input: contractsapi.RootERC20.Bytecode, - }, deployerKey) + receipt, err := rootchainTxRelayer.SendTransaction(deployTx, deployerKey) require.NoError(t, err) require.NotNil(t, receipt) require.Equal(t, uint64(types.ReceiptSuccess), receipt.Status) @@ -1252,13 +1260,13 @@ func TestE2E_Bridge_NonMintableERC20Token_WithPremine(t *testing.T) { bigZero = big.NewInt(0) ) - nonValidatorKey, err := wallet.GenerateKey() + nonValidatorKey, err := crypto.GenerateECDSAKey() require.NoError(t, err) nonValidatorKeyRaw, err := nonValidatorKey.MarshallPrivateKey() require.NoError(t, err) - rewardWalletKey, err := wallet.GenerateKey() + rewardWalletKey, err := crypto.GenerateECDSAKey() require.NoError(t, err) rewardWalletKeyRaw, err := rewardWalletKey.MarshallPrivateKey() @@ -1383,7 +1391,7 @@ func TestE2E_Bridge_NonMintableERC20Token_WithPremine(t *testing.T) { require.NoError(t, err) nonValidatorBalanceAfterWithdraw, err := childEthEndpoint.GetBalance( - nonValidatorKey.Address(), ethgo.Latest) + ethgo.Address(nonValidatorKey.Address()), ethgo.Latest) require.NoError(t, err) currentBlock, err := childEthEndpoint.GetBlockByNumber(ethgo.Latest, false) @@ -1469,7 +1477,7 @@ func TestE2E_Bridge_L1OriginatedNativeToken_ERC20StakingToken(t *testing.T) { stakeTokenAddr = types.StringToAddress("0x2040") ) - minter, err := wallet.GenerateKey() + minter, err := crypto.GenerateECDSAKey() require.NoError(t, err) cluster := framework.NewTestCluster(t, 5, @@ -1512,14 +1520,14 @@ func TestE2E_Bridge_L1OriginatedNativeToken_ERC20StakingToken(t *testing.T) { mintInput, err := mintFn.EncodeAbi() require.NoError(t, err) - nonNativeErc20 := ethgo.Address(polybftCfg.StakeTokenAddr) + nonNativeErc20 := polybftCfg.StakeTokenAddr + + mintTx := types.NewTx(types.NewDynamicFeeTx( + types.WithTo(&nonNativeErc20), + types.WithInput(mintInput), + )) - receipt, err := relayer.SendTransaction( - ðgo.Transaction{ - To: &nonNativeErc20, - Input: mintInput, - Type: ethgo.TransactionDynamicFee, - }, minter) + receipt, err := relayer.SendTransaction(mintTx, minter) require.NoError(t, err) require.Equal(t, uint64(types.ReceiptSuccess), receipt.Status) diff --git a/e2e-polybft/e2e/burn_contract_test.go b/e2e-polybft/e2e/burn_contract_test.go index 615bd7b7a6..057eb8e718 100644 --- a/e2e-polybft/e2e/burn_contract_test.go +++ b/e2e-polybft/e2e/burn_contract_test.go @@ -4,16 +4,16 @@ import ( "testing" "github.com/0xPolygon/polygon-edge/consensus/polybft" + "github.com/0xPolygon/polygon-edge/crypto" "github.com/0xPolygon/polygon-edge/e2e-polybft/framework" "github.com/0xPolygon/polygon-edge/types" "github.com/stretchr/testify/require" "github.com/umbracle/ethgo" - "github.com/umbracle/ethgo/wallet" ) func TestE2E_BurnContract_Deployed(t *testing.T) { - contractKey, _ := wallet.GenerateKey() - destinationKey, _ := wallet.GenerateKey() + contractKey, _ := crypto.GenerateECDSAKey() + destinationKey, _ := crypto.GenerateECDSAKey() contractAddr := types.Address(contractKey.Address()) destinationAddr := types.Address(destinationKey.Address()) diff --git a/e2e-polybft/e2e/consensus_test.go b/e2e-polybft/e2e/consensus_test.go index d2441a4769..e55a147e76 100644 --- a/e2e-polybft/e2e/consensus_test.go +++ b/e2e-polybft/e2e/consensus_test.go @@ -13,7 +13,6 @@ import ( "github.com/stretchr/testify/require" "github.com/umbracle/ethgo" "github.com/umbracle/ethgo/abi" - "github.com/umbracle/ethgo/wallet" "github.com/0xPolygon/polygon-edge/command" "github.com/0xPolygon/polygon-edge/command/genesis" @@ -21,6 +20,7 @@ import ( "github.com/0xPolygon/polygon-edge/consensus/polybft" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" "github.com/0xPolygon/polygon-edge/contracts" + "github.com/0xPolygon/polygon-edge/crypto" "github.com/0xPolygon/polygon-edge/e2e-polybft/framework" "github.com/0xPolygon/polygon-edge/helper/common" "github.com/0xPolygon/polygon-edge/txrelayer" @@ -179,13 +179,13 @@ func TestE2E_Consensus_RegisterValidator(t *testing.T) { addrs, err := cluster.InitSecrets(firstValidatorDataDir, 1) require.NoError(t, err) - firstValidatorAddr := ethgo.Address(addrs[0]) + firstValidatorAddr := addrs[0] // create the second account and extract the address addrs, err = cluster.InitSecrets(secondValidatorDataDir, 1) require.NoError(t, err) - secondValidatorAddr := ethgo.Address(addrs[0]) + secondValidatorAddr := addrs[0] // assert that accounts are created validatorSecrets, err := genesis.GetValidatorKeyFiles(cluster.Config.TmpDir, cluster.Config.ValidatorPrefix) @@ -212,12 +212,12 @@ func TestE2E_Consensus_RegisterValidator(t *testing.T) { []*big.Int{initialBalance, initialBalance}, polybftConfig.StakeTokenAddr)) // first validator's balance to be received - firstBalance, err := relayer.Client().Eth().GetBalance(firstValidatorAddr, ethgo.Latest) + firstBalance, err := relayer.Client().Eth().GetBalance(ethgo.Address(firstValidatorAddr), ethgo.Latest) require.NoError(t, err) t.Logf("First validator balance=%d\n", firstBalance) // second validator's balance to be received - secondBalance, err := relayer.Client().Eth().GetBalance(secondValidatorAddr, ethgo.Latest) + secondBalance, err := relayer.Client().Eth().GetBalance(ethgo.Address(secondValidatorAddr), ethgo.Latest) require.NoError(t, err) t.Logf("Second validator balance=%d\n", secondBalance) @@ -309,16 +309,16 @@ func TestE2E_Consensus_Validator_Unstake(t *testing.T) { cluster.WaitForReady(t) - initialValidatorBalance, err := srv.JSONRPC().Eth().GetBalance(validatorAcc.Ecdsa.Address(), ethgo.Latest) + validatorAddr := ethgo.Address(validatorAcc.Ecdsa.Address()) + + initialValidatorBalance, err := srv.JSONRPC().Eth().GetBalance(validatorAddr, ethgo.Latest) require.NoError(t, err) t.Logf("Balance (before unstake)=%d\n", initialValidatorBalance) - validatorAddr := validatorAcc.Ecdsa.Address() - // wait for some rewards to get accumulated require.NoError(t, cluster.WaitForBlock(polybftCfg.EpochSize*3, time.Minute)) - validatorInfo, err := validatorHelper.GetValidatorInfo(validatorAddr, relayer) + validatorInfo, err := validatorHelper.GetValidatorInfo(validatorAcc.Address(), relayer) require.NoError(t, err) require.True(t, validatorInfo.IsActive) @@ -340,21 +340,21 @@ func TestE2E_Consensus_Validator_Unstake(t *testing.T) { require.NoError(t, srv.WitdhrawStake()) // check that validator is no longer active (out of validator set) - validatorInfo, err = validatorHelper.GetValidatorInfo(validatorAddr, relayer) + validatorInfo, err = validatorHelper.GetValidatorInfo(validatorAcc.Address(), relayer) require.NoError(t, err) require.False(t, validatorInfo.IsActive) require.True(t, validatorInfo.Stake.Cmp(big.NewInt(0)) == 0) t.Logf("Stake (after unstake and withdraw)=%d\n", validatorInfo.Stake) - balanceBeforeRewardsWithdraw, err := srv.JSONRPC().Eth().GetBalance(validatorAcc.Ecdsa.Address(), ethgo.Latest) + balanceBeforeRewardsWithdraw, err := srv.JSONRPC().Eth().GetBalance(validatorAddr, ethgo.Latest) require.NoError(t, err) t.Logf("Balance (before withdraw rewards)=%d\n", balanceBeforeRewardsWithdraw) // withdraw pending rewards require.NoError(t, srv.WithdrawRewards()) - newValidatorBalance, err := srv.JSONRPC().Eth().GetBalance(validatorAcc.Ecdsa.Address(), ethgo.Latest) + newValidatorBalance, err := srv.JSONRPC().Eth().GetBalance(validatorAddr, ethgo.Latest) require.NoError(t, err) t.Logf("Balance (after withdrawal of rewards)=%s\n", newValidatorBalance) require.True(t, newValidatorBalance.Cmp(balanceBeforeRewardsWithdraw) > 0) @@ -374,10 +374,10 @@ func TestE2E_Consensus_MintableERC20NativeToken(t *testing.T) { initValidatorsBalance := ethgo.Ether(1) initMinterBalance := ethgo.Ether(100000) - minter, err := wallet.GenerateKey() + minter, err := crypto.GenerateECDSAKey() require.NoError(t, err) - receiver, err := wallet.GenerateKey() + receiver, err := crypto.GenerateECDSAKey() require.NoError(t, err) // because we are using native token as reward wallet, and it has default premine balance @@ -430,35 +430,35 @@ func TestE2E_Consensus_MintableERC20NativeToken(t *testing.T) { // send mint transactions mintAmount := ethgo.Ether(1) - nativeTokenAddr := ethgo.Address(contracts.NativeERC20TokenContract) // make sure minter account can mint tokens - receiverAddr := types.Address(receiver.Address()) - balanceBefore, err := targetJSONRPC.Eth().GetBalance(ethgo.Address(receiverAddr), ethgo.Latest) + balanceBefore, err := targetJSONRPC.Eth().GetBalance(ethgo.Address(receiver.Address()), ethgo.Latest) require.NoError(t, err) - t.Logf("Pre-mint balance: %v=%d\n", receiverAddr, balanceBefore) + t.Logf("Pre-mint balance: %v=%d\n", receiver.Address(), balanceBefore) mintFn := &contractsapi.MintRootERC20Fn{ - To: receiverAddr, + To: receiver.Address(), Amount: mintAmount, } mintInput, err := mintFn.EncodeAbi() require.NoError(t, err) - receipt, err := relayer.SendTransaction( - ðgo.Transaction{ - To: &nativeTokenAddr, - Input: mintInput, - Type: ethgo.TransactionDynamicFee, - }, minter) + tx := types.NewTx( + types.NewDynamicFeeTx( + types.WithTo(&contracts.NativeERC20TokenContract), + types.WithInput(mintInput), + ), + ) + + receipt, err := relayer.SendTransaction(tx, minter) require.NoError(t, err) require.Equal(t, uint64(types.ReceiptSuccess), receipt.Status) - balanceAfter, err := targetJSONRPC.Eth().GetBalance(ethgo.Address(receiverAddr), ethgo.Latest) + balanceAfter, err := targetJSONRPC.Eth().GetBalance(ethgo.Address(receiver.Address()), ethgo.Latest) require.NoError(t, err) - t.Logf("Post-mint balance: %v=%d\n", receiverAddr, balanceAfter) + t.Logf("Post-mint balance: %v=%d\n", receiver.Address(), balanceAfter) require.True(t, balanceAfter.Cmp(new(big.Int).Add(mintAmount, balanceBefore)) >= 0) // try sending mint transaction from non minter account and make sure it would fail @@ -469,12 +469,12 @@ func TestE2E_Consensus_MintableERC20NativeToken(t *testing.T) { mintInput, err = mintFn.EncodeAbi() require.NoError(t, err) - receipt, err = relayer.SendTransaction( - ðgo.Transaction{ - To: &nativeTokenAddr, - Input: mintInput, - Type: ethgo.TransactionDynamicFee, - }, nonMinterAcc.Ecdsa) + tx = types.NewTx(types.NewDynamicFeeTx( + types.WithTo(&contracts.NativeERC20TokenContract), + types.WithInput(mintInput), + )) + + receipt, err = relayer.SendTransaction(tx, nonMinterAcc.Ecdsa) require.Error(t, err) require.Nil(t, receipt) } @@ -515,10 +515,10 @@ func TestE2E_Consensus_CustomRewardToken(t *testing.T) { func TestE2E_Consensus_EIP1559Check(t *testing.T) { t.Skip("TODO - since we removed burn from evm, this should be fixed after the burn solution") - sender, err := wallet.GenerateKey() + sender, err := crypto.GenerateECDSAKey() require.NoError(t, err) - recipient := ethgo.Address(types.StringToAddress("1234")) + recipient := types.StringToAddress("1234") // sender must have premined some native tokens cluster := framework.NewTestCluster(t, 5, @@ -536,9 +536,9 @@ func TestE2E_Consensus_EIP1559Check(t *testing.T) { client := cluster.Servers[0].JSONRPC().Eth() - waitUntilBalancesChanged := func(_ ethgo.Address, initialBalance *big.Int) error { + waitUntilBalancesChanged := func(acct types.Address, initialBalance *big.Int) error { err := cluster.WaitUntil(30*time.Second, 1*time.Second, func() bool { - balance, err := client.GetBalance(recipient, ethgo.Latest) + balance, err := client.GetBalance(ethgo.Address(acct), ethgo.Latest) if err != nil { return true } @@ -554,32 +554,31 @@ func TestE2E_Consensus_EIP1559Check(t *testing.T) { sendAmount := ethgo.Gwei(1) - txns := []*ethgo.Transaction{ - { - Value: sendAmount, - To: &recipient, - Gas: 21000, - Nonce: uint64(0), - GasPrice: ethgo.Gwei(1).Uint64(), - }, - { - Value: sendAmount, - To: &recipient, - Gas: 21000, - Nonce: uint64(0), - Type: ethgo.TransactionDynamicFee, - MaxFeePerGas: ethgo.Gwei(1), - MaxPriorityFeePerGas: ethgo.Gwei(1), - }, + txns := []*types.Transaction{ + types.NewTx(types.NewLegacyTx( + types.WithValue(sendAmount), + types.WithTo(&recipient), + types.WithGas(21000), + types.WithNonce(uint64(0)), + types.WithGasPrice(ethgo.Gwei(1)), + )), + types.NewTx(types.NewDynamicFeeTx( + types.WithValue(sendAmount), + types.WithTo(&recipient), + types.WithGas(21000), + types.WithNonce(uint64(0)), + types.WithGasFeeCap(ethgo.Gwei(1)), + types.WithGasTipCap(ethgo.Gwei(1)), + )), } initialMinerBalance := big.NewInt(0) - var prevMiner ethgo.Address + prevMiner := ethgo.ZeroAddress for i, txn := range txns { - senderInitialBalance, _ := client.GetBalance(sender.Address(), ethgo.Latest) - receiverInitialBalance, _ := client.GetBalance(recipient, ethgo.Latest) + senderInitialBalance, _ := client.GetBalance(ethgo.Address(sender.Address()), ethgo.Latest) + receiverInitialBalance, _ := client.GetBalance(ethgo.Address(recipient), ethgo.Latest) burnContractInitialBalance, _ := client.GetBalance(ethgo.Address(types.ZeroAddress), ethgo.Latest) receipt, err := relayer.SendTransaction(txn, sender) @@ -597,8 +596,8 @@ func TestE2E_Consensus_EIP1559Check(t *testing.T) { prevMiner = block.Miner } - senderFinalBalance, _ := client.GetBalance(sender.Address(), ethgo.Latest) - receiverFinalBalance, _ := client.GetBalance(recipient, ethgo.Latest) + senderFinalBalance, _ := client.GetBalance(ethgo.Address(sender.Address()), ethgo.Latest) + receiverFinalBalance, _ := client.GetBalance(ethgo.Address(recipient), ethgo.Latest) burnContractFinalBalance, _ := client.GetBalance(ethgo.Address(types.ZeroAddress), ethgo.Latest) diffReceiverBalance := new(big.Int).Sub(receiverFinalBalance, receiverInitialBalance) @@ -645,7 +644,7 @@ func TestE2E_Consensus_ChangeVotingPowerByStakingPendingRewards(t *testing.T) { validatorSecretFiles, err := genesis.GetValidatorKeyFiles(cluster.Config.TmpDir, cluster.Config.ValidatorPrefix) require.NoError(t, err) - votingPowerChangeValidators := make([]ethgo.Address, votingPowerChanges) + votingPowerChangeValidators := make([]types.Address, votingPowerChanges) for i := 0; i < votingPowerChanges; i++ { validator, err := validatorHelper.GetAccountFromDir(path.Join(cluster.Config.TmpDir, validatorSecretFiles[i])) @@ -678,7 +677,7 @@ func TestE2E_Consensus_ChangeVotingPowerByStakingPendingRewards(t *testing.T) { bigZero := big.NewInt(0) // validatorsMap holds only changed validators - validatorsMap := make(map[ethgo.Address]*polybft.ValidatorInfo, votingPowerChanges) + validatorsMap := make(map[types.Address]*polybft.ValidatorInfo, votingPowerChanges) queryValidators(func(idx int, validator *polybft.ValidatorInfo) { t.Logf("[Validator#%d] Voting power (original)=%d, rewards=%d\n", @@ -731,13 +730,11 @@ func TestE2E_Consensus_ChangeVotingPowerByStakingPendingRewards(t *testing.T) { } for addr, validator := range validatorsMap { - a := types.Address(addr) - - if !currentExtra.Validators.Updated.ContainsAddress(a) { + if !currentExtra.Validators.Updated.ContainsAddress(addr) { continue } - if currentExtra.Validators.Updated.GetValidatorMetadata(a).VotingPower.Cmp(validator.Stake) != 0 { + if currentExtra.Validators.Updated.GetValidatorMetadata(addr).VotingPower.Cmp(validator.Stake) != 0 { continue } } @@ -755,12 +752,10 @@ func TestE2E_Consensus_ChangeVotingPowerByStakingPendingRewards(t *testing.T) { func TestE2E_Deploy_Nested_Contract(t *testing.T) { numberToPersist := big.NewInt(234586) - admin, err := wallet.GenerateKey() + admin, err := crypto.GenerateECDSAKey() require.NoError(t, err) - adminAddr := types.Address(admin.Address()) - - cluster := framework.NewTestCluster(t, 5, framework.WithBladeAdmin(adminAddr.String())) + cluster := framework.NewTestCluster(t, 5, framework.WithBladeAdmin(admin.Address().String())) defer cluster.Stop() cluster.WaitForReady(t) @@ -770,15 +765,16 @@ func TestE2E_Deploy_Nested_Contract(t *testing.T) { // deploy Wrapper contract receipt, err := txRelayer.SendTransaction( - ðgo.Transaction{ - To: nil, - Input: contractsapi.Wrapper.Bytecode, - }, + types.NewTx(&types.LegacyTx{ + BaseTx: &types.BaseTx{ + Input: contractsapi.Wrapper.Bytecode, + }, + }), admin) require.NoError(t, err) // address of Wrapper contract - wrapperAddr := receipt.ContractAddress + wrapperAddr := types.Address(receipt.ContractAddress) // getAddressFn returns address of the NumberPersister (nested) contract getAddressFn := contractsapi.Wrapper.Abi.GetMethod("getAddress") @@ -786,7 +782,7 @@ func TestE2E_Deploy_Nested_Contract(t *testing.T) { getAddrInput, err := getAddressFn.Encode([]interface{}{}) require.NoError(t, err) - response, err := txRelayer.Call(ethgo.ZeroAddress, wrapperAddr, getAddrInput) + response, err := txRelayer.Call(types.ZeroAddress, wrapperAddr, getAddrInput) require.NoError(t, err) // address of the NumberPersister (nested) contract @@ -799,11 +795,11 @@ func TestE2E_Deploy_Nested_Contract(t *testing.T) { setValueInput, err := setNumberFn.Encode([]interface{}{numberToPersist}) require.NoError(t, err) - txn := ðgo.Transaction{ - From: admin.Address(), - To: &wrapperAddr, - Input: setValueInput, - } + txn := types.NewTx(types.NewLegacyTx( + types.WithFrom(admin.Address()), + types.WithTo(&wrapperAddr), + types.WithInput(setValueInput), + )) receipt, err = txRelayer.SendTransaction(txn, admin) require.NoError(t, err) @@ -815,7 +811,7 @@ func TestE2E_Deploy_Nested_Contract(t *testing.T) { getNumberInput, err := getNumberFn.Encode([]interface{}{}) require.NoError(t, err) - response, err = txRelayer.Call(ethgo.ZeroAddress, wrapperAddr, getNumberInput) + response, err = txRelayer.Call(types.ZeroAddress, wrapperAddr, getNumberInput) require.NoError(t, err) parsedResponse, err := common.ParseUint256orHex(&response) diff --git a/e2e-polybft/e2e/governance_test.go b/e2e-polybft/e2e/governance_test.go index 3ad6175185..edcbef1653 100644 --- a/e2e-polybft/e2e/governance_test.go +++ b/e2e-polybft/e2e/governance_test.go @@ -136,7 +136,7 @@ func TestE2E_Governance_ProposeAndExecuteSimpleProposal(t *testing.T) { // check if epoch size changed on NetworkParams networkParamsResponse, err := ABICall(relayer, contractsapi.NetworkParams, - ethgo.Address(polybftCfg.GovernanceConfig.NetworkParamsAddr), ethgo.ZeroAddress, "epochSize") + polybftCfg.GovernanceConfig.NetworkParamsAddr, types.ZeroAddress, "epochSize") require.NoError(t, err) epochSizeOnNetworkParams, err := common.ParseUint256orHex(&networkParamsResponse) @@ -291,7 +291,7 @@ func TestE2E_Governance_ProposeAndExecuteSimpleProposal(t *testing.T) { // check if base fee change denom changed on NetworkParams networkParamsResponse, err := ABICall(relayer, contractsapi.NetworkParams, - ethgo.Address(polybftCfg.GovernanceConfig.NetworkParamsAddr), ethgo.ZeroAddress, "baseFeeChangeDenom") + polybftCfg.GovernanceConfig.NetworkParamsAddr, types.ZeroAddress, "baseFeeChangeDenom") require.NoError(t, err) baseFeeDenomOnNetworkParams, err := common.ParseUint256orHex(&networkParamsResponse) @@ -311,7 +311,7 @@ func getProposalState(t *testing.T, proposalID *big.Int, childGovernorAddr types input, err := stateFn.EncodeAbi() require.NoError(t, err) - response, err := txRelayer.Call(ethgo.ZeroAddress, ethgo.Address(childGovernorAddr), input) + response, err := txRelayer.Call(types.ZeroAddress, childGovernorAddr, input) require.NoError(t, err) require.NotEqual(t, "0x", response) @@ -322,7 +322,7 @@ func getProposalState(t *testing.T, proposalID *big.Int, childGovernorAddr types } func sendQueueProposalTransaction(t *testing.T, - txRelayer txrelayer.TxRelayer, senderKey ethgo.Key, + txRelayer txrelayer.TxRelayer, senderKey crypto.Key, childGovernorAddr, paramsContractAddr types.Address, input []byte, description string) { t.Helper() @@ -337,11 +337,10 @@ func sendQueueProposalTransaction(t *testing.T, input, err := queueFn.EncodeAbi() require.NoError(t, err) - childGovernor := ethgo.Address(childGovernorAddr) - txn := ðgo.Transaction{ - To: &childGovernor, - Input: input, - } + txn := types.NewTx(types.NewLegacyTx( + types.WithTo(&childGovernorAddr), + types.WithInput(input), + )) receipt, err := txRelayer.SendTransaction(txn, senderKey) require.NoError(t, err) @@ -349,7 +348,7 @@ func sendQueueProposalTransaction(t *testing.T, } func sendExecuteProposalTransaction(t *testing.T, - txRelayer txrelayer.TxRelayer, senderKey ethgo.Key, + txRelayer txrelayer.TxRelayer, senderKey crypto.Key, childGovernorAddr, paramsContractAddr types.Address, input []byte, description string) { t.Helper() @@ -364,11 +363,10 @@ func sendExecuteProposalTransaction(t *testing.T, input, err := executeFn.EncodeAbi() require.NoError(t, err) - childGovernor := ethgo.Address(childGovernorAddr) - txn := ðgo.Transaction{ - To: &childGovernor, - Input: input, - } + txn := types.NewTx(types.NewLegacyTx( + types.WithTo(&childGovernorAddr), + types.WithInput(input), + )) receipt, err := txRelayer.SendTransaction(txn, senderKey) require.NoError(t, err) @@ -377,7 +375,7 @@ func sendExecuteProposalTransaction(t *testing.T, func sendVoteTransaction(t *testing.T, proposalID *big.Int, vote VoteType, childGovernorAddr types.Address, - txRelayer txrelayer.TxRelayer, senderKey ethgo.Key) { + txRelayer txrelayer.TxRelayer, senderKey crypto.Key) { t.Helper() castVoteFn := &contractsapi.CastVoteChildGovernorFn{ @@ -388,11 +386,10 @@ func sendVoteTransaction(t *testing.T, proposalID *big.Int, vote VoteType, input, err := castVoteFn.EncodeAbi() require.NoError(t, err) - childGovernor := ethgo.Address(childGovernorAddr) - txn := ðgo.Transaction{ - To: &childGovernor, - Input: input, - } + txn := types.NewTx(types.NewLegacyTx( + types.WithTo(&childGovernorAddr), + types.WithInput(input), + )) receipt, err := txRelayer.SendTransaction(txn, senderKey) require.NoError(t, err) @@ -400,7 +397,7 @@ func sendVoteTransaction(t *testing.T, proposalID *big.Int, vote VoteType, } func sendProposalTransaction(t *testing.T, txRelayer txrelayer.TxRelayer, - senderKey ethgo.Key, + senderKey crypto.Key, childGovernorAddr, paramsContractAddr types.Address, input []byte, description string) *big.Int { t.Helper() @@ -415,11 +412,10 @@ func sendProposalTransaction(t *testing.T, txRelayer txrelayer.TxRelayer, input, err := proposeFn.EncodeAbi() require.NoError(t, err) - childGovernor := ethgo.Address(childGovernorAddr) - txn := ðgo.Transaction{ - To: &childGovernor, - Input: input, - } + txn := types.NewTx(types.NewLegacyTx( + types.WithTo(&childGovernorAddr), + types.WithInput(input), + )) receipt, err := txRelayer.SendTransaction(txn, senderKey) require.NoError(t, err) diff --git a/e2e-polybft/e2e/helpers_test.go b/e2e-polybft/e2e/helpers_test.go index 36e0add4c9..3290eeef6d 100644 --- a/e2e-polybft/e2e/helpers_test.go +++ b/e2e-polybft/e2e/helpers_test.go @@ -13,6 +13,7 @@ import ( "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" "github.com/0xPolygon/polygon-edge/contracts" + "github.com/0xPolygon/polygon-edge/crypto" "github.com/0xPolygon/polygon-edge/e2e-polybft/framework" "github.com/0xPolygon/polygon-edge/helper/common" "github.com/0xPolygon/polygon-edge/helper/hex" @@ -23,7 +24,7 @@ import ( const nativeTokenNonMintableConfig = "Blade:BLD:18:false" -func ABICall(relayer txrelayer.TxRelayer, artifact *contracts.Artifact, contractAddress ethgo.Address, senderAddr ethgo.Address, method string, params ...interface{}) (string, error) { +func ABICall(relayer txrelayer.TxRelayer, artifact *contracts.Artifact, contractAddress types.Address, senderAddr types.Address, method string, params ...interface{}) (string, error) { input, err := artifact.Abi.GetMethod(method).Encode(params) if err != nil { return "", err @@ -32,16 +33,18 @@ func ABICall(relayer txrelayer.TxRelayer, artifact *contracts.Artifact, contract return relayer.Call(senderAddr, contractAddress, input) } -func ABITransaction(relayer txrelayer.TxRelayer, key ethgo.Key, artifact *contracts.Artifact, contractAddress ethgo.Address, method string, params ...interface{}) (*ethgo.Receipt, error) { +func ABITransaction(relayer txrelayer.TxRelayer, key crypto.Key, artifact *contracts.Artifact, contractAddress types.Address, method string, params ...interface{}) (*ethgo.Receipt, error) { input, err := artifact.Abi.GetMethod(method).Encode(params) if err != nil { return nil, err } - return relayer.SendTransaction(ðgo.Transaction{ - To: &contractAddress, - Input: input, - }, key) + tx := types.NewTx(types.NewLegacyTx( + types.WithTo(&contractAddress), + types.WithInput(input), + )) + + return relayer.SendTransaction(tx, key) } // checkStateSyncResultLogs is helper function which parses given StateSyncResultEvent event's logs, @@ -67,9 +70,9 @@ func checkStateSyncResultLogs( } // getCheckpointBlockNumber gets current checkpoint block number from checkpoint manager smart contract -func getCheckpointBlockNumber(l1Relayer txrelayer.TxRelayer, checkpointManagerAddr ethgo.Address) (uint64, error) { +func getCheckpointBlockNumber(l1Relayer txrelayer.TxRelayer, checkpointManagerAddr types.Address) (uint64, error) { checkpointBlockNumRaw, err := ABICall(l1Relayer, contractsapi.CheckpointManager, - checkpointManagerAddr, ethgo.ZeroAddress, "currentCheckpointBlockNumber") + checkpointManagerAddr, types.ZeroAddress, "currentCheckpointBlockNumber") if err != nil { return 0, err } @@ -99,7 +102,7 @@ func waitForRootchainEpoch(targetEpoch uint64, timeout time.Duration, } rootchainEpochRaw, err := ABICall(rootchainTxRelayer, contractsapi.CheckpointManager, - ethgo.Address(checkpointManager), ethgo.ZeroAddress, "currentEpoch") + checkpointManager, types.ZeroAddress, "currentEpoch") if err != nil { return err } @@ -117,7 +120,7 @@ func waitForRootchainEpoch(targetEpoch uint64, timeout time.Duration, // setAccessListRole sets access list role to appropriate access list precompile func setAccessListRole(t *testing.T, cluster *framework.TestCluster, precompile, account types.Address, - role addresslist.Role, aclAdmin ethgo.Key) { + role addresslist.Role, aclAdmin *crypto.ECDSAKey) { t.Helper() var updateRoleFn *abi.Method @@ -171,7 +174,7 @@ func erc20BalanceOf(t *testing.T, account types.Address, tokenAddr types.Address balanceOfInput, err := balanceOfFn.EncodeAbi() require.NoError(t, err) - balanceRaw, err := relayer.Call(ethgo.ZeroAddress, ethgo.Address(tokenAddr), balanceOfInput) + balanceRaw, err := relayer.Call(types.ZeroAddress, tokenAddr, balanceOfInput) require.NoError(t, err) balance, err := common.ParseUint256orHex(&balanceRaw) require.NoError(t, err) @@ -187,7 +190,7 @@ func erc721OwnerOf(t *testing.T, tokenID *big.Int, tokenAddr types.Address, rela ownerOfInput, err := ownerOfFn.EncodeAbi() require.NoError(t, err) - ownerRaw, err := relayer.Call(ethgo.ZeroAddress, ethgo.Address(tokenAddr), ownerOfInput) + ownerRaw, err := relayer.Call(types.ZeroAddress, tokenAddr, ownerOfInput) require.NoError(t, err) return types.StringToAddress(ownerRaw) @@ -198,8 +201,8 @@ func queryNativeERC20Metadata(t *testing.T, funcName string, abiType *abi.Type, t.Helper() valueHex, err := ABICall(relayer, contractsapi.NativeERC20Mintable, - ethgo.Address(contracts.NativeERC20TokenContract), - ethgo.ZeroAddress, funcName) + contracts.NativeERC20TokenContract, + types.ZeroAddress, funcName) require.NoError(t, err) valueRaw, err := hex.DecodeHex(valueHex) @@ -224,7 +227,7 @@ func getChildToken(t *testing.T, predicateABI *abi.ABI, predicateAddr types.Addr input, err := rootToChildTokenFn.Encode([]interface{}{rootToken}) require.NoError(t, err) - childTokenRaw, err := relayer.Call(ethgo.ZeroAddress, ethgo.Address(predicateAddr), input) + childTokenRaw, err := relayer.Call(types.ZeroAddress, predicateAddr, input) require.NoError(t, err) return types.StringToAddress(childTokenRaw) @@ -238,7 +241,7 @@ func getLastExitEventID(t *testing.T, relayer txrelayer.TxRelayer) uint64 { input, err := exitEventsCounterFn.Encode([]interface{}{}) require.NoError(t, err) - exitEventIDRaw, err := relayer.Call(ethgo.ZeroAddress, ethgo.Address(contracts.L2StateSenderContract), input) + exitEventIDRaw, err := relayer.Call(types.ZeroAddress, contracts.L2StateSenderContract, input) require.NoError(t, err) exitEventID, err := common.ParseUint64orHex(&exitEventIDRaw) @@ -256,7 +259,7 @@ func isExitEventProcessed(t *testing.T, exitHelperAddr types.Address, input, err := processedExitsFn.Encode([]interface{}{exitEventID}) require.NoError(t, err) - isProcessedRaw, err := relayer.Call(ethgo.ZeroAddress, ethgo.Address(exitHelperAddr), input) + isProcessedRaw, err := relayer.Call(types.ZeroAddress, exitHelperAddr, input) require.NoError(t, err) isProcessedAsNumber, err := common.ParseUint64orHex(&isProcessedRaw) diff --git a/e2e-polybft/e2e/jsonrpc_test.go b/e2e-polybft/e2e/jsonrpc_test.go index 21ec223e91..5e6b684c30 100644 --- a/e2e-polybft/e2e/jsonrpc_test.go +++ b/e2e-polybft/e2e/jsonrpc_test.go @@ -8,7 +8,6 @@ import ( "github.com/stretchr/testify/require" "github.com/umbracle/ethgo" "github.com/umbracle/ethgo/jsonrpc" - "github.com/umbracle/ethgo/wallet" "github.com/0xPolygon/polygon-edge/consensus/polybft" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" @@ -26,11 +25,11 @@ var ( ) func TestE2E_JsonRPC(t *testing.T) { - acct, err := wallet.GenerateKey() + senderKey, err := crypto.GenerateECDSAKey() require.NoError(t, err) cluster := framework.NewTestCluster(t, 4, - framework.WithPremine(types.Address(acct.Address())), + framework.WithPremine(senderKey.Address()), framework.WithHTTPS("/etc/ssl/certs/localhost.pem", "/etc/ssl/private/localhost.key"), ) defer cluster.Stop() @@ -43,7 +42,7 @@ func TestE2E_JsonRPC(t *testing.T) { // Test eth_call with override in state diff t.Run("eth_call state override", func(t *testing.T) { - deployTxn := cluster.Deploy(t, acct, contractsapi.TestSimple.Bytecode) + deployTxn := cluster.Deploy(t, senderKey, contractsapi.TestSimple.Bytecode) require.NoError(t, deployTxn.Wait()) require.True(t, deployTxn.Succeed()) @@ -72,7 +71,7 @@ func TestE2E_JsonRPC(t *testing.T) { // Test eth_call with zero account balance t.Run("eth_call with zero-balance account", func(t *testing.T) { - deployTxn := cluster.Deploy(t, acct, contractsapi.TestSimple.Bytecode) + deployTxn := cluster.Deploy(t, senderKey, contractsapi.TestSimple.Bytecode) require.NoError(t, deployTxn.Wait()) require.True(t, deployTxn.Succeed()) @@ -80,11 +79,11 @@ func TestE2E_JsonRPC(t *testing.T) { input := contractsapi.TestSimple.Abi.GetMethod("getValue").ID() - acctZeroBalance, err := wallet.GenerateKey() + acctZeroBalance, err := crypto.GenerateECDSAKey() require.NoError(t, err) resp, err := client.Call(ðgo.CallMsg{ - From: acctZeroBalance.Address(), + From: ethgo.Address(acctZeroBalance.Address()), To: &target, Data: input, }, ethgo.Latest) @@ -93,7 +92,7 @@ func TestE2E_JsonRPC(t *testing.T) { }) t.Run("eth_estimateGas", func(t *testing.T) { - deployTxn := cluster.Deploy(t, acct, contractsapi.TestSimple.Bytecode) + deployTxn := cluster.Deploy(t, senderKey, contractsapi.TestSimple.Bytecode) require.NoError(t, deployTxn.Wait()) require.True(t, deployTxn.Succeed()) @@ -102,7 +101,7 @@ func TestE2E_JsonRPC(t *testing.T) { input := contractsapi.TestSimple.Abi.GetMethod("getValue").ID() estimatedGas, err := client.EstimateGas(ðgo.CallMsg{ - From: acct.Address(), + From: ethgo.Address(senderKey.Address()), To: &target, Data: input, }) @@ -111,19 +110,18 @@ func TestE2E_JsonRPC(t *testing.T) { }) t.Run("eth_estimateGas by zero-balance account", func(t *testing.T) { - deployTxn := cluster.Deploy(t, acct, contractsapi.TestSimple.Bytecode) + deployTxn := cluster.Deploy(t, senderKey, contractsapi.TestSimple.Bytecode) require.NoError(t, deployTxn.Wait()) require.True(t, deployTxn.Succeed()) target := deployTxn.Receipt().ContractAddress - input := contractsapi.TestSimple.Abi.GetMethod("getValue").ID() - acctZeroBalance, err := wallet.GenerateKey() + acctZeroBalance, err := crypto.GenerateECDSAKey() require.NoError(t, err) resp, err := client.EstimateGas(ðgo.CallMsg{ - From: acctZeroBalance.Address(), + From: ethgo.Address(acctZeroBalance.Address()), To: &target, Data: input, }) @@ -132,16 +130,16 @@ func TestE2E_JsonRPC(t *testing.T) { }) t.Run("eth_estimateGas by zero-balance account - simple value transfer", func(t *testing.T) { - acctZeroBalance, err := wallet.GenerateKey() + acctZeroBalance, err := crypto.GenerateECDSAKey() require.NoError(t, err) - fundedAccountAddress := acct.Address() + fundedAccountAddress := senderKey.Address() nonFundedAccountAddress := acctZeroBalance.Address() estimateGasFn := func(value *big.Int) { resp, err := client.EstimateGas(ðgo.CallMsg{ - From: nonFundedAccountAddress, - To: &fundedAccountAddress, + From: ethgo.Address(nonFundedAccountAddress), + To: (*ethgo.Address)(&fundedAccountAddress), Value: value, }) @@ -152,11 +150,12 @@ func TestE2E_JsonRPC(t *testing.T) { estimateGasFn(ethgo.Gwei(1)) // transfer some funds to zero balance account - valueTransferTxn := cluster.SendTxn(t, acct, ðgo.Transaction{ - From: fundedAccountAddress, - To: &nonFundedAccountAddress, - Value: ethgo.Gwei(10), - }) + valueTransferTxn := cluster.SendTxn(t, senderKey, + types.NewTx(types.NewLegacyTx( + types.WithFrom(fundedAccountAddress), + types.WithTo(&nonFundedAccountAddress), + types.WithValue(ethgo.Gwei(10)), + ))) require.NoError(t, valueTransferTxn.Wait()) require.True(t, valueTransferTxn.Succeed()) @@ -166,21 +165,23 @@ func TestE2E_JsonRPC(t *testing.T) { }) t.Run("eth_getBalance", func(t *testing.T) { - key1, err := wallet.GenerateKey() + recipientKey, err := crypto.GenerateECDSAKey() require.NoError(t, err) + recipientAddr := ethgo.Address(recipientKey.Address()) + // Test. return zero if the account does not exist - balance1, err := client.GetBalance(key1.Address(), ethgo.Latest) + balance1, err := client.GetBalance(recipientAddr, ethgo.Latest) require.NoError(t, err) require.Equal(t, balance1, big.NewInt(0)) // Test. return the balance of an account newBalance := ethgo.Ether(1) - txn := cluster.Transfer(t, acct, types.Address(key1.Address()), newBalance) + txn := cluster.Transfer(t, senderKey, recipientKey.Address(), newBalance) require.NoError(t, txn.Wait()) require.True(t, txn.Succeed()) - balance1, err = client.GetBalance(key1.Address(), ethgo.Latest) + balance1, err = client.GetBalance(recipientAddr, ethgo.Latest) require.NoError(t, err) require.Equal(t, balance1, newBalance) @@ -188,11 +189,9 @@ func TestE2E_JsonRPC(t *testing.T) { gasPrice, err := client.GasPrice() require.NoError(t, err) - toAddr := key1.Address() - estimatedGas, err := client.EstimateGas(ðgo.CallMsg{ - From: acct.Address(), - To: &toAddr, + From: ethgo.Address(senderKey.Address()), + To: &recipientAddr, Value: newBalance, }) require.NoError(t, err) @@ -200,62 +199,65 @@ func TestE2E_JsonRPC(t *testing.T) { // subtract gasPrice * estimatedGas from the balance and transfer the rest to the other account // in order to leave no funds on the account amountToSend := new(big.Int).Sub(newBalance, big.NewInt(int64(txPrice))) - targetAddr := acct.Address() - txn = cluster.SendTxn(t, key1, ðgo.Transaction{ - To: &targetAddr, - Value: amountToSend, - Gas: estimatedGas, - }) + targetAddr := senderKey.Address() + txn = cluster.SendTxn(t, recipientKey, + types.NewTx(types.NewLegacyTx( + types.WithTo(&targetAddr), + types.WithValue(amountToSend), + types.WithGas(estimatedGas), + ))) require.NoError(t, txn.Wait()) require.True(t, txn.Succeed()) - balance1, err = client.GetBalance(key1.Address(), ethgo.Latest) + balance1, err = client.GetBalance(ethgo.Address(recipientKey.Address()), ethgo.Latest) require.NoError(t, err) require.Equal(t, big.NewInt(0), balance1) }) t.Run("eth_getTransactionCount", func(t *testing.T) { - key1, err := wallet.GenerateKey() + recipientKey, err := crypto.GenerateECDSAKey() require.NoError(t, err) - nonce, err := client.GetNonce(key1.Address(), ethgo.Latest) + recipient := ethgo.Address(recipientKey.Address()) + + nonce, err := client.GetNonce(recipient, ethgo.Latest) require.Equal(t, uint64(0), nonce) require.NoError(t, err) - txn := cluster.Transfer(t, acct, types.Address(key1.Address()), big.NewInt(10000000000000000)) + txn := cluster.Transfer(t, senderKey, types.Address(recipient), big.NewInt(10000000000000000)) require.NoError(t, txn.Wait()) require.True(t, txn.Succeed()) // Test. increase the nonce with new transactions - txn = cluster.Transfer(t, key1, types.ZeroAddress, big.NewInt(0)) + txn = cluster.Transfer(t, recipientKey, types.ZeroAddress, big.NewInt(0)) require.NoError(t, txn.Wait()) require.True(t, txn.Succeed()) - nonce1, err := client.GetNonce(key1.Address(), ethgo.Latest) + nonce1, err := client.GetNonce(recipient, ethgo.Latest) require.NoError(t, err) require.Equal(t, nonce1, uint64(1)) // Test. you can query the nonce at any block number in time - nonce1, err = client.GetNonce(key1.Address(), ethgo.BlockNumber(txn.Receipt().BlockNumber-1)) + nonce1, err = client.GetNonce(recipient, ethgo.BlockNumber(txn.Receipt().BlockNumber-1)) require.NoError(t, err) require.Equal(t, nonce1, uint64(0)) block, err := client.GetBlockByNumber(ethgo.BlockNumber(txn.Receipt().BlockNumber)-1, false) require.NoError(t, err) - _, err = client.GetNonce(key1.Address(), ethgo.BlockNumber(block.Number)) + _, err = client.GetNonce(recipient, ethgo.BlockNumber(block.Number)) require.NoError(t, err) }) t.Run("eth_getStorageAt", func(t *testing.T) { - key1, err := wallet.GenerateKey() + key1, err := crypto.GenerateECDSAKey() require.NoError(t, err) - txn := cluster.Transfer(t, acct, types.Address(key1.Address()), one) + txn := cluster.Transfer(t, senderKey, key1.Address(), one) require.NoError(t, txn.Wait()) require.True(t, txn.Succeed()) - txn = cluster.Deploy(t, acct, contractsapi.TestSimple.Bytecode) + txn = cluster.Deploy(t, senderKey, contractsapi.TestSimple.Bytecode) require.NoError(t, txn.Wait()) require.True(t, txn.Succeed()) @@ -272,7 +274,10 @@ func TestE2E_JsonRPC(t *testing.T) { input, err := setValueFn.Encode([]interface{}{newVal}) require.NoError(t, err) - txn = cluster.SendTxn(t, acct, ðgo.Transaction{Input: input, To: &target}) + txn = cluster.SendTxn(t, senderKey, + types.NewTx( + types.NewLegacyTx(types.WithInput(input), types.WithTo((*types.Address)(&target))), + )) require.NoError(t, txn.Wait()) require.True(t, txn.Succeed()) @@ -286,11 +291,11 @@ func TestE2E_JsonRPC(t *testing.T) { // Note that in order to work, this private key should only be used for this test. priv, err := hex.DecodeString("2c15bd0dc992a47ca660983ae4b611f4ffb6178e14e04e2b34d153f3a74ce741") require.NoError(t, err) - key1, err := wallet.NewWalletFromPrivKey(priv) + key1, err := crypto.NewECDSAKeyFromRawPrivECDSA(priv) require.NoError(t, err) // fund the account so that it can deploy a contract - txn := cluster.Transfer(t, acct, types.Address(key1.Address()), big.NewInt(10000000000000000)) + txn := cluster.Transfer(t, senderKey, key1.Address(), ethgo.Ether(1)) require.NoError(t, txn.Wait()) require.True(t, txn.Succeed()) @@ -333,9 +338,9 @@ func TestE2E_JsonRPC(t *testing.T) { }) t.Run("eth_getBlockByHash", func(t *testing.T) { - key1, err := wallet.GenerateKey() + key1, err := crypto.GenerateECDSAKey() require.NoError(t, err) - txn := cluster.Transfer(t, acct, types.Address(key1.Address()), one) + txn := cluster.Transfer(t, senderKey, key1.Address(), one) require.NoError(t, txn.Wait()) require.True(t, txn.Succeed()) txReceipt := txn.Receipt() @@ -347,9 +352,9 @@ func TestE2E_JsonRPC(t *testing.T) { }) t.Run("eth_getBlockByNumber", func(t *testing.T) { - key1, err := wallet.GenerateKey() + key1, err := crypto.GenerateECDSAKey() require.NoError(t, err) - txn := cluster.Transfer(t, acct, types.Address(key1.Address()), one) + txn := cluster.Transfer(t, senderKey, key1.Address(), one) require.NoError(t, txn.Wait()) require.True(t, txn.Succeed()) txReceipt := txn.Receipt() @@ -361,9 +366,9 @@ func TestE2E_JsonRPC(t *testing.T) { }) t.Run("eth_getTransactionReceipt", func(t *testing.T) { - key1, err := wallet.GenerateKey() + key1, err := crypto.GenerateECDSAKey() require.NoError(t, err) - txn := cluster.Transfer(t, acct, types.Address(key1.Address()), one) + txn := cluster.Transfer(t, senderKey, key1.Address(), one) require.NoError(t, txn.Wait()) require.True(t, txn.Succeed()) @@ -385,7 +390,7 @@ func TestE2E_JsonRPC(t *testing.T) { require.Equal(t, receipt.BlockHash, block.Hash) // Test. The receipt of a deployed contract has the 'ContractAddress' field. - txn = cluster.Deploy(t, acct, contractsapi.TestSimple.Bytecode) + txn = cluster.Deploy(t, senderKey, contractsapi.TestSimple.Bytecode) require.NoError(t, txn.Wait()) require.True(t, txn.Succeed()) @@ -393,11 +398,11 @@ func TestE2E_JsonRPC(t *testing.T) { }) t.Run("eth_getTransactionByHash", func(t *testing.T) { - key1, err := wallet.GenerateKey() + key1, err := crypto.GenerateECDSAKey() require.NoError(t, err) // Test. We should be able to query the transaction by its hash - txn := cluster.Transfer(t, acct, types.Address(key1.Address()), one) + txn := cluster.Transfer(t, senderKey, key1.Address(), one) require.NoError(t, txn.Wait()) require.True(t, txn.Succeed()) @@ -409,11 +414,11 @@ func TestE2E_JsonRPC(t *testing.T) { }) t.Run("debug_traceTransaction", func(t *testing.T) { - key1, err := wallet.GenerateKey() + key1, err := crypto.GenerateECDSAKey() require.NoError(t, err) // Test. We should be able to query the transaction by its hash - txn := cluster.Transfer(t, acct, types.Address(key1.Address()), one) + txn := cluster.Transfer(t, senderKey, key1.Address(), one) require.NoError(t, txn.Wait()) require.True(t, txn.Succeed()) @@ -429,12 +434,12 @@ func TestE2E_JsonRPC(t *testing.T) { func TestE2E_JsonRPC_NewEthClient(t *testing.T) { const epochSize = uint64(5) - acct, err := wallet.GenerateKey() + preminedAcct, err := crypto.GenerateECDSAKey() require.NoError(t, err) cluster := framework.NewTestCluster(t, 4, framework.WithEpochSize(int(epochSize)), - framework.WithPremine(types.Address(acct.Address())), + framework.WithPremine(preminedAcct.Address()), framework.WithBurnContract(&polybft.BurnContractInfo{BlockNumber: 0, Address: types.ZeroAddress}), ) defer cluster.Stop() @@ -503,7 +508,7 @@ func TestE2E_JsonRPC_NewEthClient(t *testing.T) { }) t.Run("eth_getCode", func(t *testing.T) { - deployTxn := cluster.Deploy(t, acct, contractsapi.TestSimple.Bytecode) + deployTxn := cluster.Deploy(t, preminedAcct, contractsapi.TestSimple.Bytecode) require.NoError(t, deployTxn.Wait()) require.True(t, deployTxn.Succeed()) @@ -515,20 +520,20 @@ func TestE2E_JsonRPC_NewEthClient(t *testing.T) { }) t.Run("eth_getStorageAt", func(t *testing.T) { - key1, err := wallet.GenerateKey() + key1, err := crypto.GenerateECDSAKey() require.NoError(t, err) - txn := cluster.Transfer(t, acct, types.Address(key1.Address()), one) + txn := cluster.Transfer(t, preminedAcct, key1.Address(), ethgo.Ether(1)) require.NoError(t, txn.Wait()) require.True(t, txn.Succeed()) - txn = cluster.Deploy(t, acct, contractsapi.TestSimple.Bytecode) + txn = cluster.Deploy(t, key1, contractsapi.TestSimple.Bytecode) require.NoError(t, txn.Wait()) require.True(t, txn.Succeed()) - target := txn.Receipt().ContractAddress + target := types.Address(txn.Receipt().ContractAddress) - resp, err := newEthClient.GetStorageAt(types.Address(target), types.Hash{}, bladeRPC.LatestBlockNumberOrHash) + resp, err := newEthClient.GetStorageAt(target, types.Hash{}, bladeRPC.LatestBlockNumberOrHash) require.NoError(t, err) require.Equal(t, "0x0000000000000000000000000000000000000000000000000000000000000000", resp.String()) @@ -539,7 +544,7 @@ func TestE2E_JsonRPC_NewEthClient(t *testing.T) { input, err := setValueFn.Encode([]interface{}{newVal}) require.NoError(t, err) - txn = cluster.SendTxn(t, acct, ðgo.Transaction{Input: input, To: &target}) + txn = cluster.SendTxn(t, key1, types.NewTx(types.NewLegacyTx(types.WithInput(input), types.WithTo(&target)))) require.NoError(t, txn.Wait()) require.True(t, txn.Succeed()) @@ -549,14 +554,14 @@ func TestE2E_JsonRPC_NewEthClient(t *testing.T) { }) t.Run("eth_getTransactionByHash and eth_getTransactionReceipt", func(t *testing.T) { - txn := cluster.Transfer(t, acct, types.StringToAddress("0xDEADBEEF"), one) + txn := cluster.Transfer(t, preminedAcct, types.StringToAddress("0xDEADBEEF"), one) require.NoError(t, txn.Wait()) require.True(t, txn.Succeed()) ethTxn, err := newEthClient.GetTransactionByHash(types.Hash(txn.Receipt().TransactionHash)) require.NoError(t, err) - require.Equal(t, ethTxn.From(), types.Address(acct.Address())) + require.Equal(t, ethTxn.From(), preminedAcct.Address()) receipt, err := newEthClient.GetTransactionReceipt(ethTxn.Hash()) require.NoError(t, err) @@ -565,21 +570,21 @@ func TestE2E_JsonRPC_NewEthClient(t *testing.T) { }) t.Run("eth_getTransactionCount", func(t *testing.T) { - nonce, err := newEthClient.GetNonce(types.Address(acct.Address()), bladeRPC.LatestBlockNumberOrHash) + nonce, err := newEthClient.GetNonce(preminedAcct.Address(), bladeRPC.LatestBlockNumberOrHash) require.NoError(t, err) require.GreaterOrEqual(t, nonce, uint64(0)) // since we used this account in previous tests - txn := cluster.Transfer(t, acct, types.StringToAddress("0xDEADBEEF"), one) + txn := cluster.Transfer(t, preminedAcct, types.StringToAddress("0xDEADBEEF"), one) require.NoError(t, txn.Wait()) require.True(t, txn.Succeed()) - newNonce, err := newEthClient.GetNonce(types.Address(acct.Address()), bladeRPC.LatestBlockNumberOrHash) + newNonce, err := newEthClient.GetNonce(preminedAcct.Address(), bladeRPC.LatestBlockNumberOrHash) require.NoError(t, err) require.Equal(t, nonce+1, newNonce) }) t.Run("eth_getBalance", func(t *testing.T) { - balance, err := newEthClient.GetBalance(types.Address(acct.Address()), bladeRPC.LatestBlockNumberOrHash) + balance, err := newEthClient.GetBalance(preminedAcct.Address(), bladeRPC.LatestBlockNumberOrHash) require.NoError(t, err) require.True(t, balance.Cmp(big.NewInt(0)) >= 0) @@ -587,7 +592,7 @@ func TestE2E_JsonRPC_NewEthClient(t *testing.T) { tokens := ethgo.Ether(1) - txn := cluster.Transfer(t, acct, receiver, tokens) + txn := cluster.Transfer(t, preminedAcct, receiver, tokens) require.NoError(t, txn.Wait()) require.True(t, txn.Succeed()) @@ -597,7 +602,7 @@ func TestE2E_JsonRPC_NewEthClient(t *testing.T) { }) t.Run("eth_estimateGas", func(t *testing.T) { - deployTxn := cluster.Deploy(t, acct, contractsapi.TestSimple.Bytecode) + deployTxn := cluster.Deploy(t, preminedAcct, contractsapi.TestSimple.Bytecode) require.NoError(t, deployTxn.Wait()) require.True(t, deployTxn.Succeed()) @@ -606,7 +611,7 @@ func TestE2E_JsonRPC_NewEthClient(t *testing.T) { input := contractsapi.TestSimple.Abi.GetMethod("getValue").ID() estimatedGas, err := newEthClient.EstimateGas(&bladeRPC.CallMsg{ - From: types.Address(acct.Address()), + From: preminedAcct.Address(), To: &target, Data: input, }) @@ -621,7 +626,7 @@ func TestE2E_JsonRPC_NewEthClient(t *testing.T) { }) t.Run("eth_call", func(t *testing.T) { - deployTxn := cluster.Deploy(t, acct, contractsapi.TestSimple.Bytecode) + deployTxn := cluster.Deploy(t, preminedAcct, contractsapi.TestSimple.Bytecode) require.NoError(t, deployTxn.Wait()) require.True(t, deployTxn.Succeed()) @@ -629,7 +634,7 @@ func TestE2E_JsonRPC_NewEthClient(t *testing.T) { input := contractsapi.TestSimple.Abi.GetMethod("getValue").ID() - acctZeroBalance, err := wallet.GenerateKey() + acctZeroBalance, err := crypto.GenerateECDSAKey() require.NoError(t, err) resp, err := newEthClient.Call(&bladeRPC.CallMsg{ @@ -656,7 +661,7 @@ func TestE2E_JsonRPC_NewEthClient(t *testing.T) { t.Run("eth_sendRawTransaction", func(t *testing.T) { receiver := types.StringToAddress("0xDEADFFFF") - tokens := ethgo.Ether(1) + tokenAmount := ethgo.Ether(1) chainID, err := newEthClient.ChainID() require.NoError(t, err) @@ -666,21 +671,23 @@ func TestE2E_JsonRPC_NewEthClient(t *testing.T) { newAccountKey, newAccountAddr := tests.GenerateKeyAndAddr(t) - transferTxn := cluster.Transfer(t, acct, newAccountAddr, tokens) + transferTxn := cluster.Transfer(t, preminedAcct, newAccountAddr, tokenAmount) require.NoError(t, transferTxn.Wait()) require.True(t, transferTxn.Succeed()) newAccountBalance, err := newEthClient.GetBalance(newAccountAddr, bladeRPC.LatestBlockNumberOrHash) require.NoError(t, err) - require.Equal(t, tokens, newAccountBalance) - - txn := types.NewTx(types.NewLegacyTx(types.WithNonce(0), - types.WithFrom(newAccountAddr), - types.WithTo(&receiver), - types.WithValue(ethgo.Gwei(1)), - types.WithGas(21000), - types.WithGasPrice(new(big.Int).SetUint64(gasPrice)), - )) + require.Equal(t, tokenAmount, newAccountBalance) + + txn := types.NewTx( + types.NewLegacyTx( + types.WithNonce(0), + types.WithFrom(newAccountAddr), + types.WithTo(&receiver), + types.WithValue(ethgo.Gwei(1)), + types.WithGas(21000), + types.WithGasPrice(new(big.Int).SetUint64(gasPrice)), + )) signedTxn, err := crypto.NewLondonSigner(chainID.Uint64()).SignTx(txn, newAccountKey) require.NoError(t, err) diff --git a/e2e-polybft/e2e/migration_test.go b/e2e-polybft/e2e/migration_test.go index 8093ed1e7d..c86cd23a55 100644 --- a/e2e-polybft/e2e/migration_test.go +++ b/e2e-polybft/e2e/migration_test.go @@ -7,26 +7,26 @@ import ( "testing" "time" + "github.com/stretchr/testify/require" + "github.com/syndtr/goleveldb/leveldb" "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/umbracle/ethgo" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" + "github.com/0xPolygon/polygon-edge/crypto" frameworkpolybft "github.com/0xPolygon/polygon-edge/e2e-polybft/framework" "github.com/0xPolygon/polygon-edge/e2e/framework" "github.com/0xPolygon/polygon-edge/helper/common" itrie "github.com/0xPolygon/polygon-edge/state/immutable-trie" "github.com/0xPolygon/polygon-edge/txrelayer" "github.com/0xPolygon/polygon-edge/types" - "github.com/stretchr/testify/require" - "github.com/syndtr/goleveldb/leveldb" - "github.com/umbracle/ethgo" - "github.com/umbracle/ethgo/wallet" ) func TestE2E_Migration(t *testing.T) { - userKey, _ := wallet.GenerateKey() - userAddr := userKey.Address() - userKey2, _ := wallet.GenerateKey() - userAddr2 := userKey2.Address() + userKey, _ := crypto.GenerateECDSAKey() + userAddr := ethgo.Address(userKey.Address()) + userKey2, _ := crypto.GenerateECDSAKey() + userAddr2 := ethgo.Address(userKey2.Address()) initialBalance := ethgo.Ether(10) srvs := framework.NewTestServers(t, 1, func(config *framework.TestServerConfig) { @@ -61,32 +61,39 @@ func TestE2E_Migration(t *testing.T) { relayer, err := txrelayer.NewTxRelayer(txrelayer.WithClient(rpcClient)) require.NoError(t, err) - //send transaction to user2 + // send transaction to user2 sendAmount := ethgo.Gwei(10000) - receipt, err := relayer.SendTransaction( - ðgo.Transaction{ - From: userAddr, - To: &userAddr2, - Gas: 1000000, - Value: sendAmount, - GasPrice: ethgo.Gwei(2).Uint64(), - }, userKey) + tx := types.NewTx(&types.LegacyTx{ + BaseTx: &types.BaseTx{ + From: userKey.Address(), + To: userKey2.Address().Ptr(), + Gas: 1000000, + Value: sendAmount, + }, + GasPrice: ethgo.Gwei(2), + }) + + receipt, err := relayer.SendTransaction(tx, userKey) require.NoError(t, err) require.NotNil(t, receipt) - receipt, err = relayer.SendTransaction(ðgo.Transaction{ - From: userAddr, - Gas: 1000000, - GasPrice: ethgo.Gwei(2).Uint64(), - Input: contractsapi.TestWriteBlockMetadata.Bytecode, - }, userKey) + tx = types.NewTx(&types.LegacyTx{ + BaseTx: &types.BaseTx{ + From: userKey.Address(), + Gas: 1000000, + Input: contractsapi.TestWriteBlockMetadata.Bytecode, + }, + GasPrice: ethgo.Gwei(2), + }) + + receipt, err = relayer.SendTransaction(tx, userKey) require.NoError(t, err) require.NotNil(t, receipt) require.Equal(t, uint64(types.ReceiptSuccess), receipt.Status) deployedContractBalance := receipt.ContractAddress - initReceipt, err := ABITransaction(relayer, userKey, contractsapi.TestWriteBlockMetadata, receipt.ContractAddress, "init") + initReceipt, err := ABITransaction(relayer, userKey, contractsapi.TestWriteBlockMetadata, types.Address(receipt.ContractAddress), "init") if err != nil { t.Fatal(err) } diff --git a/e2e-polybft/e2e/txpool_test.go b/e2e-polybft/e2e/txpool_test.go index e842259605..a636f3b855 100644 --- a/e2e-polybft/e2e/txpool_test.go +++ b/e2e-polybft/e2e/txpool_test.go @@ -10,10 +10,10 @@ import ( "github.com/stretchr/testify/require" "github.com/umbracle/ethgo" "github.com/umbracle/ethgo/jsonrpc" - "github.com/umbracle/ethgo/wallet" "github.com/0xPolygon/polygon-edge/consensus/polybft" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" + "github.com/0xPolygon/polygon-edge/crypto" "github.com/0xPolygon/polygon-edge/e2e-polybft/framework" "github.com/0xPolygon/polygon-edge/txrelayer" "github.com/0xPolygon/polygon-edge/types" @@ -21,7 +21,7 @@ import ( func TestE2E_TxPool_Transfer(t *testing.T) { // premine an account in the genesis file - sender, err := wallet.GenerateKey() + sender, err := crypto.GenerateECDSAKey() require.NoError(t, err) cluster := framework.NewTestCluster(t, 5, @@ -40,10 +40,10 @@ func TestE2E_TxPool_Transfer(t *testing.T) { receivers := []ethgo.Address{} for i := 0; i < num; i++ { - key, err := wallet.GenerateKey() + key, err := crypto.GenerateECDSAKey() require.NoError(t, err) - receivers = append(receivers, key.Address()) + receivers = append(receivers, ethgo.Address(key.Address())) } var wg sync.WaitGroup @@ -53,24 +53,32 @@ func TestE2E_TxPool_Transfer(t *testing.T) { go func(i int, to ethgo.Address) { defer wg.Done() - txn := ðgo.Transaction{ - From: sender.Address(), - To: &to, - Gas: 30000, // enough to send a transfer - Value: big.NewInt(int64(sendAmount)), - Nonce: uint64(i), - } + var txData types.TxData // Send every second transaction as a dynamic fees one if i%2 == 0 { - txn.Type = ethgo.TransactionDynamicFee - txn.MaxFeePerGas = big.NewInt(1000000000) - txn.MaxPriorityFeePerGas = big.NewInt(100000000) + txData = types.NewDynamicFeeTx( + types.WithFrom(sender.Address()), + types.WithTo((*types.Address)(&to)), + types.WithGas(30000), // enough to send a transfer + types.WithValue(big.NewInt(int64(sendAmount))), + types.WithNonce(uint64(i)), + types.WithGasFeeCap(big.NewInt(1000000000)), + types.WithGasTipCap(big.NewInt(100000000)), + ) } else { - txn.Type = ethgo.TransactionLegacy - txn.GasPrice = ethgo.Gwei(2).Uint64() + txData = types.NewLegacyTx( + types.WithFrom(sender.Address()), + types.WithTo((*types.Address)(&to)), + types.WithGas(30000), + types.WithValue(big.NewInt(int64(sendAmount))), + types.WithNonce(uint64(i)), + types.WithGasPrice(ethgo.Gwei(2)), + ) } + txn := types.NewTx(txData) + sendTransaction(t, client, sender, txn) }(i, receivers[i]) } @@ -96,7 +104,7 @@ func TestE2E_TxPool_Transfer(t *testing.T) { // First account send some amount to second one and then second one to third account func TestE2E_TxPool_Transfer_Linear(t *testing.T) { - premine, err := wallet.GenerateKey() + premine, err := crypto.GenerateECDSAKey() require.NoError(t, err) // first account should have some matics premined @@ -123,24 +131,13 @@ func TestE2E_TxPool_Transfer_Linear(t *testing.T) { return err } - populateTxFees := func(txn *ethgo.Transaction, i int) { - if i%2 == 0 { - txn.Type = ethgo.TransactionDynamicFee - txn.MaxFeePerGas = big.NewInt(1000000000) - txn.MaxPriorityFeePerGas = big.NewInt(1000000000) - } else { - txn.Type = ethgo.TransactionLegacy - txn.GasPrice = ethgo.Gwei(1).Uint64() - } - } - num := 4 - receivers := []*wallet.Key{ + receivers := []crypto.Key{ premine, } for i := 0; i < num-1; i++ { - key, err := wallet.GenerateKey() + key, err := crypto.GenerateECDSAKey() assert.NoError(t, err) receivers = append(receivers, key) @@ -158,34 +155,47 @@ func TestE2E_TxPool_Transfer_Linear(t *testing.T) { // This means that since gasCost and sendAmount are fixed, account C must receive gasCost * 2 // (to cover two more transfers C->D and D->E) + sendAmount * 3 (one bundle for each C,D and E). recipient := receivers[i].Address() - txn := ðgo.Transaction{ - Value: big.NewInt(int64(sendAmount * (num - i))), - To: &recipient, - Gas: 21000, + + var txData types.TxData + + if i%2 == 0 { + txData = types.NewDynamicFeeTx( + types.WithValue(big.NewInt(int64(sendAmount*(num-i)))), + types.WithTo(&recipient), + types.WithGas(21000), + types.WithGasFeeCap(big.NewInt(1000000000)), + types.WithGasTipCap(big.NewInt(1000000000)), + ) + } else { + txData = types.NewLegacyTx( + types.WithValue(big.NewInt(int64(sendAmount*(num-i)))), + types.WithTo(&recipient), + types.WithGas(21000), + types.WithGasPrice(ethgo.Gwei(1)), + ) } - // Populate fees fields for the current transaction - populateTxFees(txn, i-1) + txn := types.NewTx(txData) // Add remaining fees to finish the cycle gasCostTotal := new(big.Int).Mul(txCost(txn), new(big.Int).SetInt64(int64(num-i-1))) - txn.Value = txn.Value.Add(txn.Value, gasCostTotal) + txn.SetValue(txn.Value().Add(txn.Value(), gasCostTotal)) sendTransaction(t, client, receivers[i-1], txn) - err := waitUntilBalancesChanged(receivers[i].Address()) + err := waitUntilBalancesChanged(ethgo.Address(receivers[i].Address())) require.NoError(t, err) } for i := 1; i < num; i++ { - balance, err := client.GetBalance(receivers[i].Address(), ethgo.Latest) + balance, err := client.GetBalance(ethgo.Address(receivers[i].Address()), ethgo.Latest) require.NoError(t, err) require.Equal(t, uint64(sendAmount), balance.Uint64()) } } func TestE2E_TxPool_TransactionWithHeaderInstructions(t *testing.T) { - sidechainKey, err := wallet.GenerateKey() + sidechainKey, err := crypto.GenerateECDSAKey() require.NoError(t, err) cluster := framework.NewTestCluster(t, 4, @@ -198,11 +208,15 @@ func TestE2E_TxPool_TransactionWithHeaderInstructions(t *testing.T) { relayer, err := txrelayer.NewTxRelayer(txrelayer.WithIPAddress(cluster.Servers[0].JSONRPCAddr())) require.NoError(t, err) - receipt, err := relayer.SendTransaction(ðgo.Transaction{Input: contractsapi.TestWriteBlockMetadata.Bytecode}, sidechainKey) + tx := types.NewTx(types.NewLegacyTx( + types.WithInput(contractsapi.TestWriteBlockMetadata.Bytecode), + )) + + receipt, err := relayer.SendTransaction(tx, sidechainKey) require.NoError(t, err) require.Equal(t, uint64(types.ReceiptSuccess), receipt.Status) - receipt, err = ABITransaction(relayer, sidechainKey, contractsapi.TestWriteBlockMetadata, receipt.ContractAddress, "init", []interface{}{}) + receipt, err = ABITransaction(relayer, sidechainKey, contractsapi.TestWriteBlockMetadata, types.Address(receipt.ContractAddress), "init", []interface{}{}) require.NoError(t, err) require.Equal(t, uint64(types.ReceiptSuccess), receipt.Status) @@ -221,7 +235,7 @@ func TestE2E_TxPool_BroadcastTransactions(t *testing.T) { ) // Create recipient key - key, err := wallet.GenerateKey() + key, err := crypto.GenerateECDSAKey() assert.NoError(t, err) recipient := key.Address() @@ -229,7 +243,7 @@ func TestE2E_TxPool_BroadcastTransactions(t *testing.T) { t.Logf("Recipient %s\n", recipient) // Create pre-mined balance for sender - sender, err := wallet.GenerateKey() + sender, err := crypto.GenerateECDSAKey() require.NoError(t, err) // First account should have some matics premined @@ -247,32 +261,39 @@ func TestE2E_TxPool_BroadcastTransactions(t *testing.T) { sentAmount := new(big.Int) nonce := uint64(0) - for i := 0; i < txNum; i++ { - txn := ðgo.Transaction{ - Value: sendAmount, - To: &recipient, - Gas: 21000, - Nonce: nonce, - } + var txData types.TxData + for i := 0; i < txNum; i++ { if i%2 == 0 { - txn.Type = ethgo.TransactionDynamicFee - txn.MaxFeePerGas = big.NewInt(1000000000) - txn.MaxPriorityFeePerGas = big.NewInt(100000000) + txData = types.NewDynamicFeeTx( + types.WithValue(sendAmount), + types.WithTo(&recipient), + types.WithGas(21000), + types.WithNonce(nonce), + types.WithGasFeeCap(big.NewInt(1000000000)), + types.WithGasTipCap(big.NewInt(100000000)), + ) } else { - txn.Type = ethgo.TransactionLegacy - txn.GasPrice = ethgo.Gwei(2).Uint64() + txData = types.NewLegacyTx( + types.WithValue(sendAmount), + types.WithTo(&recipient), + types.WithGas(21000), + types.WithNonce(nonce), + types.WithGasPrice(ethgo.Gwei(2)), + ) } + txn := types.NewTx(txData) + sendTransaction(t, client, sender, txn) - sentAmount = sentAmount.Add(sentAmount, txn.Value) + sentAmount = sentAmount.Add(sentAmount, txn.Value()) nonce++ } // Wait until the balance has changed on all nodes in the cluster err = cluster.WaitUntil(time.Minute, time.Second*3, func() bool { for _, srv := range cluster.Servers { - balance, err := srv.WaitForNonZeroBalance(recipient, time.Second*10) + balance, err := srv.WaitForNonZeroBalance(ethgo.Address(recipient), time.Second*10) assert.NoError(t, err) if balance != nil && balance.BitLen() > 0 { assert.Equal(t, sentAmount, balance) @@ -287,35 +308,39 @@ func TestE2E_TxPool_BroadcastTransactions(t *testing.T) { } // sendTransaction is a helper function which signs transaction with provided private key and sends it -func sendTransaction(t *testing.T, client *jsonrpc.Eth, sender *wallet.Key, txn *ethgo.Transaction) { +func sendTransaction(t *testing.T, client *jsonrpc.Eth, sender crypto.Key, txn *types.Transaction) { t.Helper() chainID, err := client.ChainID() require.NoError(t, err) - if txn.Type == ethgo.TransactionDynamicFee { - txn.ChainID = chainID + if txn.Type() == types.DynamicFeeTxType { + txn.SetChainID(chainID) } - signer := wallet.NewEIP155Signer(chainID.Uint64()) - signedTxn, err := signer.SignTx(txn, sender) + signer := crypto.NewLondonSigner(chainID.Uint64()) + + signedTxn, err := signer.SignTxWithCallback(txn, + func(hash types.Hash) (sig []byte, err error) { + return sender.Sign(hash[:]) + }) require.NoError(t, err) - txnRaw, err := signedTxn.MarshalRLPTo(nil) + txnRlp := signedTxn.MarshalRLPTo(nil) require.NoError(t, err) - _, err = client.SendRawTransaction(txnRaw) + _, err = client.SendRawTransaction(txnRlp) require.NoError(t, err) } -func txCost(t *ethgo.Transaction) *big.Int { +func txCost(t *types.Transaction) *big.Int { var factor *big.Int - if t.Type == ethgo.TransactionDynamicFee { - factor = new(big.Int).Set(t.MaxFeePerGas) + if t.Type() == types.DynamicFeeTxType { + factor = new(big.Int).Set(t.GasFeeCap()) } else { - factor = new(big.Int).SetUint64(t.GasPrice) + factor = new(big.Int).Set(t.GasPrice()) } - return new(big.Int).Mul(factor, new(big.Int).SetUint64(t.Gas)) + return new(big.Int).Mul(factor, new(big.Int).SetUint64(t.Gas())) } diff --git a/e2e-polybft/framework/test-cluster.go b/e2e-polybft/framework/test-cluster.go index ed763d2df7..c64cd08edb 100644 --- a/e2e-polybft/framework/test-cluster.go +++ b/e2e-polybft/framework/test-cluster.go @@ -21,6 +21,7 @@ import ( "github.com/0xPolygon/polygon-edge/command/genesis" "github.com/0xPolygon/polygon-edge/consensus/polybft" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" + "github.com/0xPolygon/polygon-edge/crypto" "github.com/0xPolygon/polygon-edge/helper/common" "github.com/0xPolygon/polygon-edge/txrelayer" "github.com/0xPolygon/polygon-edge/types" @@ -28,7 +29,6 @@ import ( "github.com/umbracle/ethgo" "github.com/umbracle/ethgo/abi" "github.com/umbracle/ethgo/jsonrpc" - "github.com/umbracle/ethgo/wallet" ) const ( @@ -1042,30 +1042,45 @@ func (c *TestCluster) Call(t *testing.T, to types.Address, method *abi.Method, return output } -func (c *TestCluster) Deploy(t *testing.T, sender ethgo.Key, bytecode []byte) *TestTxn { +func (c *TestCluster) Deploy(t *testing.T, sender *crypto.ECDSAKey, bytecode []byte) *TestTxn { t.Helper() - return c.SendTxn(t, sender, ðgo.Transaction{From: sender.Address(), Input: bytecode}) + tx := types.NewTx(&types.LegacyTx{ + BaseTx: &types.BaseTx{ + From: sender.Address(), + Input: bytecode, + }, + }) + + return c.SendTxn(t, sender, tx) } -func (c *TestCluster) Transfer(t *testing.T, sender ethgo.Key, target types.Address, value *big.Int) *TestTxn { +func (c *TestCluster) Transfer(t *testing.T, sender *crypto.ECDSAKey, target types.Address, value *big.Int) *TestTxn { t.Helper() - targetAddr := ethgo.Address(target) + tx := types.NewTx(types.NewLegacyTx( + types.WithFrom(sender.Address()), + types.WithValue(value), + types.WithTo(&target), + )) - return c.SendTxn(t, sender, ðgo.Transaction{From: sender.Address(), To: &targetAddr, Value: value}) + return c.SendTxn(t, sender, tx) } -func (c *TestCluster) MethodTxn(t *testing.T, sender ethgo.Key, target types.Address, input []byte) *TestTxn { +func (c *TestCluster) MethodTxn(t *testing.T, sender *crypto.ECDSAKey, target types.Address, input []byte) *TestTxn { t.Helper() - targetAddr := ethgo.Address(target) + tx := types.NewTx(types.NewLegacyTx( + types.WithFrom(sender.Address()), + types.WithInput(input), + types.WithTo(&target), + )) - return c.SendTxn(t, sender, ðgo.Transaction{From: sender.Address(), To: &targetAddr, Input: input}) + return c.SendTxn(t, sender, tx) } // SendTxn sends a transaction -func (c *TestCluster) SendTxn(t *testing.T, sender ethgo.Key, txn *ethgo.Transaction) *TestTxn { +func (c *TestCluster) SendTxn(t *testing.T, sender *crypto.ECDSAKey, txn *types.Transaction) *TestTxn { t.Helper() // since we might use get nonce to query the latest nonce and that value is only @@ -1079,44 +1094,46 @@ func (c *TestCluster) SendTxn(t *testing.T, sender ethgo.Key, txn *ethgo.Transac require.NoError(t, err) // initialize transaction values if not set - if txn.Nonce == 0 { - nonce, err := client.Eth().GetNonce(sender.Address(), ethgo.Latest) + if txn.Nonce() == 0 { + nonce, err := client.Eth().GetNonce(ethgo.Address(sender.Address()), ethgo.Latest) require.NoError(t, err) - txn.Nonce = nonce + txn.SetNonce(nonce) } - if txn.GasPrice == 0 { + if txn.GasPrice() == nil || txn.GasPrice() == big.NewInt(0) { gasPrice, err := client.Eth().GasPrice() require.NoError(t, err) - txn.GasPrice = gasPrice + txn.SetGasPrice(new(big.Int).SetUint64(gasPrice)) } - if txn.Gas == 0 { + if txn.Gas() == 0 { callMsg := txrelayer.ConvertTxnToCallMsg(txn) gasLimit, err := client.Eth().EstimateGas(callMsg) if err != nil { // gas estimation can fail in case an account is not allow-listed // (fallback it to default gas limit in that case) - txn.Gas = txrelayer.DefaultGasLimit + txn.SetGas(txrelayer.DefaultGasLimit) } else { - txn.Gas = gasLimit + txn.SetGas(gasLimit) } } chainID, err := client.Eth().ChainID() require.NoError(t, err) - signer := wallet.NewEIP155Signer(chainID.Uint64()) - signedTxn, err := signer.SignTx(txn, sender) + signer := crypto.NewLondonSigner(chainID.Uint64()) + signedTxn, err := signer.SignTxWithCallback(txn, + func(hash types.Hash) (sig []byte, err error) { + return sender.Sign(hash.Bytes()) + }) require.NoError(t, err) - txnRaw, err := signedTxn.MarshalRLPTo(nil) - require.NoError(t, err) + rlpTxn := signedTxn.MarshalRLPTo(nil) - hash, err := client.Eth().SendRawTransaction(txnRaw) + hash, err := client.Eth().SendRawTransaction(rlpTxn) require.NoError(t, err) return &TestTxn{ @@ -1129,12 +1146,12 @@ func (c *TestCluster) SendTxn(t *testing.T, sender ethgo.Key, txn *ethgo.Transac type TestTxn struct { client *jsonrpc.Eth hash ethgo.Hash - txn *ethgo.Transaction + txn *types.Transaction receipt *ethgo.Receipt } // Txn returns the raw transaction that was sent -func (t *TestTxn) Txn() *ethgo.Transaction { +func (t *TestTxn) Txn() *types.Transaction { return t.txn } @@ -1156,7 +1173,7 @@ func (t *TestTxn) Failed() bool { // Reverted returns whether the transaction failed and was reverted consuming // all the gas from the call func (t *TestTxn) Reverted() bool { - return t.receipt.Status == uint64(types.ReceiptFailed) && t.txn.Gas == t.receipt.GasUsed + return t.receipt.Status == uint64(types.ReceiptFailed) && t.txn.Gas() == t.receipt.GasUsed } // Wait waits for the transaction to be executed diff --git a/helper/tests/testing.go b/helper/tests/testing.go index f781e2ef85..442e39c7c5 100644 --- a/helper/tests/testing.go +++ b/helper/tests/testing.go @@ -31,7 +31,7 @@ var ( func GenerateKeyAndAddr(t *testing.T) (*ecdsa.PrivateKey, types.Address) { t.Helper() - key, err := crypto.GenerateECDSAKey() + key, err := crypto.GenerateECDSAPrivateKey() assert.NoError(t, err) diff --git a/txpool/txpool.go b/txpool/txpool.go index f09a6f07bb..6eb1bebb26 100644 --- a/txpool/txpool.go +++ b/txpool/txpool.go @@ -571,7 +571,6 @@ func (p *TxPool) validateTx(tx *types.Transaction) error { } // Check if the transaction is signed properly - // Extract the sender from, signerErr := p.signer.Sender(tx) if signerErr != nil { diff --git a/txpool/txpool_test.go b/txpool/txpool_test.go index 13cde912ee..0f4cfa3ed3 100644 --- a/txpool/txpool_test.go +++ b/txpool/txpool_test.go @@ -3537,7 +3537,7 @@ func TestAddTxsInOrder(t *testing.T) { addrsTxs := [accountCount]container{} for i := 0; i < accountCount; i++ { - key, err := crypto.GenerateECDSAKey() + key, err := crypto.GenerateECDSAPrivateKey() require.NoError(t, err) addrsTxs[i] = container{ @@ -3774,7 +3774,7 @@ func BenchmarkAddTxTime(b *testing.B) { b.Run("benchmark add one tx", func(b *testing.B) { signer := crypto.NewEIP155Signer(100) - key, err := crypto.GenerateECDSAKey() + key, err := crypto.GenerateECDSAPrivateKey() if err != nil { b.Fatal(err) } @@ -3802,7 +3802,7 @@ func BenchmarkAddTxTime(b *testing.B) { b.Run("benchmark fill account", func(b *testing.B) { signer := crypto.NewEIP155Signer(100) - key, err := crypto.GenerateECDSAKey() + key, err := crypto.GenerateECDSAPrivateKey() if err != nil { b.Fatal(err) } diff --git a/txrelayer/txrelayer.go b/txrelayer/txrelayer.go index 353772cd1b..405efd8246 100644 --- a/txrelayer/txrelayer.go +++ b/txrelayer/txrelayer.go @@ -9,10 +9,11 @@ import ( "sync" "time" - "github.com/0xPolygon/polygon-edge/types" "github.com/umbracle/ethgo" "github.com/umbracle/ethgo/jsonrpc" - "github.com/umbracle/ethgo/wallet" + + "github.com/0xPolygon/polygon-edge/crypto" + "github.com/0xPolygon/polygon-edge/types" ) const ( @@ -35,12 +36,12 @@ var ( type TxRelayer interface { // Call executes a message call immediately without creating a transaction on the blockchain - Call(from ethgo.Address, to ethgo.Address, input []byte) (string, error) + Call(from types.Address, to types.Address, input []byte) (string, error) // SendTransaction signs given transaction by provided key and sends it to the blockchain - SendTransaction(txn *ethgo.Transaction, key ethgo.Key) (*ethgo.Receipt, error) + SendTransaction(txn *types.Transaction, key crypto.Key) (*ethgo.Receipt, error) // SendTransactionLocal sends non-signed transaction // (this function is meant only for testing purposes and is about to be removed at some point) - SendTransactionLocal(txn *ethgo.Transaction) (*ethgo.Receipt, error) + SendTransactionLocal(txn *types.Transaction) (*ethgo.Receipt, error) // Client returns jsonrpc client Client() *jsonrpc.Client } @@ -81,10 +82,10 @@ func NewTxRelayer(opts ...TxRelayerOption) (TxRelayer, error) { } // Call executes a message call immediately without creating a transaction on the blockchain -func (t *TxRelayerImpl) Call(from ethgo.Address, to ethgo.Address, input []byte) (string, error) { +func (t *TxRelayerImpl) Call(from types.Address, to types.Address, input []byte) (string, error) { callMsg := ðgo.CallMsg{ - From: from, - To: &to, + From: ethgo.Address(from), + To: (*ethgo.Address)(&to), Data: input, } @@ -92,17 +93,23 @@ func (t *TxRelayerImpl) Call(from ethgo.Address, to ethgo.Address, input []byte) } // SendTransaction signs given transaction by provided key and sends it to the blockchain -func (t *TxRelayerImpl) SendTransaction(txn *ethgo.Transaction, key ethgo.Key) (*ethgo.Receipt, error) { +func (t *TxRelayerImpl) SendTransaction(txn *types.Transaction, key crypto.Key) (*ethgo.Receipt, error) { txnHash, err := t.sendTransactionLocked(txn, key) if err != nil { - if txn.Type != ethgo.TransactionLegacy { + if txn.Type() != types.LegacyTxType { for _, fallbackErr := range dynamicFeeTxFallbackErrs { if strings.Contains( strings.ToLower(err.Error()), strings.ToLower(fallbackErr.Error())) { // "downgrade" transaction to the legacy tx type and resend it - txn.Type = ethgo.TransactionLegacy - txn.GasPrice = 0 + copyTxn := txn.Copy() + txn.InitInnerData(types.LegacyTxType) + txn.SetNonce(copyTxn.Nonce()) + txn.SetInput(copyTxn.Input()) + txn.SetValue(copyTxn.Value()) + txn.SetTo(copyTxn.To()) + txn.SetFrom(copyTxn.From()) + txn.SetGasPrice(big.NewInt(0)) return t.SendTransaction(txn, key) } @@ -120,11 +127,11 @@ func (t *TxRelayerImpl) Client() *jsonrpc.Client { return t.client } -func (t *TxRelayerImpl) sendTransactionLocked(txn *ethgo.Transaction, key ethgo.Key) (ethgo.Hash, error) { +func (t *TxRelayerImpl) sendTransactionLocked(txn *types.Transaction, key crypto.Key) (ethgo.Hash, error) { t.lock.Lock() defer t.lock.Unlock() - nonce, err := t.client.Eth().GetNonce(key.Address(), ethgo.Pending) + nonce, err := t.client.Eth().GetNonce(ethgo.Address(key.Address()), ethgo.Pending) if err != nil { return ethgo.ZeroHash, fmt.Errorf("failed to get nonce: %w", err) } @@ -134,15 +141,15 @@ func (t *TxRelayerImpl) sendTransactionLocked(txn *ethgo.Transaction, key ethgo. return ethgo.ZeroHash, err } - txn.ChainID = chainID - txn.Nonce = nonce + txn.SetChainID(chainID) + txn.SetNonce(nonce) - if txn.From == ethgo.ZeroAddress { - txn.From = key.Address() + if txn.From() == types.ZeroAddress { + txn.SetFrom(key.Address()) } - if txn.Type == ethgo.TransactionDynamicFee { - maxPriorityFee := txn.MaxPriorityFeePerGas + if txn.Type() == types.DynamicFeeTxType { + maxPriorityFee := txn.GetGasTipCap() if maxPriorityFee == nil { // retrieve the max priority fee per gas if maxPriorityFee, err = t.Client().Eth().MaxPriorityFeePerGas(); err != nil { @@ -152,10 +159,10 @@ func (t *TxRelayerImpl) sendTransactionLocked(txn *ethgo.Transaction, key ethgo. // set retrieved max priority fee per gas increased by certain percentage compMaxPriorityFee := new(big.Int).Mul(maxPriorityFee, big.NewInt(feeIncreasePercentage)) compMaxPriorityFee = compMaxPriorityFee.Div(compMaxPriorityFee, big.NewInt(100)) - txn.MaxPriorityFeePerGas = new(big.Int).Add(maxPriorityFee, compMaxPriorityFee) + txn.SetGasTipCap(new(big.Int).Add(maxPriorityFee, compMaxPriorityFee)) } - if txn.MaxFeePerGas == nil { + if txn.GetGasFeeCap() == nil { // retrieve the latest base fee feeHist, err := t.Client().Eth().FeeHistory(1, ethgo.Latest, nil) if err != nil { @@ -168,32 +175,33 @@ func (t *TxRelayerImpl) sendTransactionLocked(txn *ethgo.Transaction, key ethgo. maxFeePerGas := new(big.Int).Add(baseFee, maxPriorityFee) compMaxFeePerGas := new(big.Int).Mul(maxFeePerGas, big.NewInt(feeIncreasePercentage)) compMaxFeePerGas = compMaxFeePerGas.Div(compMaxFeePerGas, big.NewInt(100)) - txn.MaxFeePerGas = new(big.Int).Add(maxFeePerGas, compMaxFeePerGas) + txn.SetGasFeeCap(new(big.Int).Add(maxFeePerGas, compMaxFeePerGas)) } - } else if txn.GasPrice == 0 { + } else if txn.GasPrice() == nil || txn.GasPrice().Uint64() == 0 { gasPrice, err := t.Client().Eth().GasPrice() if err != nil { return ethgo.ZeroHash, fmt.Errorf("failed to get gas price: %w", err) } - txn.GasPrice = gasPrice + (gasPrice * feeIncreasePercentage / 100) + gasPriceBigInt := new(big.Int).SetUint64(gasPrice + (gasPrice * feeIncreasePercentage / 100)) + txn.SetGasPrice(gasPriceBigInt) } - if txn.Gas == 0 { + if txn.Gas() == 0 { gasLimit, err := t.client.Eth().EstimateGas(ConvertTxnToCallMsg(txn)) if err != nil { return ethgo.ZeroHash, fmt.Errorf("failed to estimate gas: %w", err) } - txn.Gas = gasLimit + (gasLimit * gasLimitIncreasePercentage / 100) + txn.SetGas(gasLimit + (gasLimit * gasLimitIncreasePercentage / 100)) } - signer := wallet.NewEIP155Signer(chainID.Uint64()) - if txn, err = signer.SignTx(txn, key); err != nil { - return ethgo.ZeroHash, err - } - - data, err := txn.MarshalRLPTo(nil) + signer := crypto.NewLondonSigner( + chainID.Uint64()) + signedTxn, err := signer.SignTxWithCallback(txn, + func(hash types.Hash) (sig []byte, err error) { + return key.Sign(hash.Bytes()) + }) if err != nil { return ethgo.ZeroHash, err } @@ -201,24 +209,26 @@ func (t *TxRelayerImpl) sendTransactionLocked(txn *ethgo.Transaction, key ethgo. if t.writer != nil { var msg string - if txn.Type == ethgo.TransactionDynamicFee { + if txn.Type() == types.DynamicFeeTxType { msg = fmt.Sprintf("[TxRelayer.SendTransaction]\nFrom = %s\nGas = %d\n"+ "Max Fee Per Gas = %d\nMax Priority Fee Per Gas = %d\n", - txn.From, txn.Gas, txn.MaxFeePerGas, txn.MaxPriorityFeePerGas) + txn.From(), txn.Gas(), txn.GasFeeCap(), txn.GasTipCap()) } else { msg = fmt.Sprintf("[TxRelayer.SendTransaction]\nFrom = %s\nGas = %d\nGas Price = %d\n", - txn.From, txn.Gas, txn.GasPrice) + txn.From(), txn.Gas(), txn.GasPrice()) } _, _ = t.writer.Write([]byte(msg)) } - return t.client.Eth().SendRawTransaction(data) + rlpTxn := signedTxn.MarshalRLP() + + return t.client.Eth().SendRawTransaction(rlpTxn) } // SendTransactionLocal sends non-signed transaction // (this function is meant only for testing purposes and is about to be removed at some point) -func (t *TxRelayerImpl) SendTransactionLocal(txn *ethgo.Transaction) (*ethgo.Receipt, error) { +func (t *TxRelayerImpl) SendTransactionLocal(txn *types.Transaction) (*ethgo.Receipt, error) { txnHash, err := t.sendTransactionLocalLocked(txn) if err != nil { return nil, err @@ -227,7 +237,7 @@ func (t *TxRelayerImpl) SendTransactionLocal(txn *ethgo.Transaction) (*ethgo.Rec return t.waitForReceipt(txnHash) } -func (t *TxRelayerImpl) sendTransactionLocalLocked(txn *ethgo.Transaction) (ethgo.Hash, error) { +func (t *TxRelayerImpl) sendTransactionLocalLocked(txn *types.Transaction) (ethgo.Hash, error) { t.lock.Lock() defer t.lock.Unlock() @@ -240,17 +250,17 @@ func (t *TxRelayerImpl) sendTransactionLocalLocked(txn *ethgo.Transaction) (ethg return ethgo.ZeroHash, errNoAccounts } - txn.From = accounts[0] + txn.SetFrom(types.Address(accounts[0])) gasLimit, err := t.client.Eth().EstimateGas(ConvertTxnToCallMsg(txn)) if err != nil { return ethgo.ZeroHash, err } - txn.Gas = gasLimit - txn.GasPrice = defaultGasPrice + txn.SetGas(gasLimit) + txn.SetGasPrice(new(big.Int).SetUint64(defaultGasPrice)) - return t.client.Eth().SendTransaction(txn) + return t.client.Eth().SendTransaction(convertTxn(txn)) } func (t *TxRelayerImpl) waitForReceipt(hash ethgo.Hash) (*ethgo.Receipt, error) { @@ -278,15 +288,75 @@ func (t *TxRelayerImpl) waitForReceipt(hash ethgo.Hash) (*ethgo.Receipt, error) } // ConvertTxnToCallMsg converts txn instance to call message -func ConvertTxnToCallMsg(txn *ethgo.Transaction) *ethgo.CallMsg { +func ConvertTxnToCallMsg(txn *types.Transaction) *ethgo.CallMsg { + gasPrice := uint64(0) + if txn.GasPrice() != nil { + gasPrice = txn.GasPrice().Uint64() + } + return ðgo.CallMsg{ - From: txn.From, - To: txn.To, - Data: txn.Input, - GasPrice: txn.GasPrice, - Value: txn.Value, - Gas: new(big.Int).SetUint64(txn.Gas), + From: ethgo.Address(txn.From()), + To: (*ethgo.Address)(txn.To()), + Data: txn.Input(), + GasPrice: gasPrice, + Value: txn.Value(), + Gas: new(big.Int).SetUint64(txn.Gas()), + } +} + +// convertTxn converts transaction from types.Transaction to ethgo.Transaction +func convertTxn(tx *types.Transaction) *ethgo.Transaction { + getAccessList := func() ethgo.AccessList { + accessList := make(ethgo.AccessList, 0, len(tx.AccessList())) + + for _, e := range tx.AccessList() { + storageKeys := make([]ethgo.Hash, 0) + + for _, sk := range e.StorageKeys { + storageKeys = append(storageKeys, ethgo.Hash(sk)) + } + + accessList = append(accessList, + ethgo.AccessEntry{ + Address: ethgo.Address(e.Address), + Storage: storageKeys, + }) + } + + return accessList + } + + convertedTx := ðgo.Transaction{ + From: ethgo.Address(tx.From()), + To: (*ethgo.Address)(tx.To()), + Input: tx.Input(), + Value: tx.Value(), + Gas: tx.Gas(), + } + + switch tx.Type() { + case types.DynamicFeeTxType: + convertedTx.Type = ethgo.TransactionDynamicFee + convertedTx.AccessList = getAccessList() + convertedTx.MaxFeePerGas = tx.GetGasFeeCap() + convertedTx.MaxPriorityFeePerGas = tx.GetGasTipCap() + + break + + case types.AccessListTxType: + convertedTx.Type = ethgo.TransactionAccessList + convertedTx.AccessList = getAccessList() + + break + + default: + convertedTx.Type = ethgo.TransactionLegacy + convertedTx.GasPrice = tx.GetGasPrice(0).Uint64() + + break } + + return convertedTx } type TxRelayerOption func(*TxRelayerImpl) diff --git a/types/transaction.go b/types/transaction.go index 248ee979e1..73804406cb 100644 --- a/types/transaction.go +++ b/types/transaction.go @@ -183,6 +183,15 @@ func (t *Transaction) SetSignatureValues(v, r, s *big.Int) { t.Inner.setSignatureValues(v, r, s) } +// SplitToRawSignatureValues splits signature to v, r and s components and sets it to the transaction +func (t *Transaction) SplitToRawSignatureValues(signature, vRaw []byte) { + r := new(big.Int).SetBytes(signature[:HashLength]) + s := new(big.Int).SetBytes(signature[HashLength : 2*HashLength]) + v := new(big.Int).SetBytes(vRaw) + + t.SetSignatureValues(v, r, s) +} + func (t *Transaction) SetFrom(addr Address) { t.Inner.setFrom(addr) }