diff --git a/command/bridge/deploy/deploy.go b/command/bridge/deploy/deploy.go index 2fae45da48..8ae061c18d 100644 --- a/command/bridge/deploy/deploy.go +++ b/command/bridge/deploy/deploy.go @@ -6,9 +6,9 @@ import ( "math/big" "sync" + "github.com/0xPolygon/polygon-edge/jsonrpc" "github.com/spf13/cobra" "github.com/umbracle/ethgo" - "github.com/umbracle/ethgo/jsonrpc" "golang.org/x/sync/errgroup" "github.com/0xPolygon/polygon-edge/chain" @@ -361,7 +361,7 @@ func runCommand(cmd *cobra.Command, _ []string) { return } - client, err := jsonrpc.NewClient(params.jsonRPCAddress) + client, err := jsonrpc.NewEthClient(params.jsonRPCAddress) if err != nil { outputter.SetError(fmt.Errorf("failed to initialize JSON RPC client for provided IP address: %s: %w", params.jsonRPCAddress, err)) @@ -370,7 +370,7 @@ func runCommand(cmd *cobra.Command, _ []string) { } if consensusCfg.Bridge != nil { - code, err := client.Eth().GetCode(ethgo.Address(consensusCfg.Bridge.StateSenderAddr), ethgo.Latest) + code, err := client.GetCode(consensusCfg.Bridge.StateSenderAddr, jsonrpc.LatestBlockNumberOrHash) if err != nil { outputter.SetError(fmt.Errorf("failed to check if rootchain contracts are deployed: %w", err)) @@ -387,7 +387,7 @@ func runCommand(cmd *cobra.Command, _ []string) { // set event tracker start blocks for rootchain contract(s) of interest // the block number should be queried before deploying contracts so that no events during deployment // and initialization are missed - blockNum, err := client.Eth().BlockNumber() + blockNum, err := client.BlockNumber() if err != nil { outputter.SetError(fmt.Errorf("failed to query rootchain latest block number: %w", err)) @@ -427,7 +427,7 @@ func runCommand(cmd *cobra.Command, _ []string) { } // deployContracts deploys and initializes rootchain smart contracts -func deployContracts(outputter command.OutputFormatter, client *jsonrpc.Client, chainID int64, +func deployContracts(outputter command.OutputFormatter, client *jsonrpc.EthClient, chainID int64, initialValidators []*validator.GenesisValidator, cmdCtx context.Context) (deploymentResultInfo, error) { txRelayer, err := txrelayer.NewTxRelayer(txrelayer.WithClient(client), txrelayer.WithWriter(outputter)) if err != nil { @@ -465,7 +465,7 @@ func deployContracts(outputter command.OutputFormatter, client *jsonrpc.Client, if !consensusCfg.NativeTokenConfig.IsMintable { if params.rootERC20TokenAddr != "" { // use existing root chain ERC20 token - if err := populateExistingTokenAddr(client.Eth(), + if err := populateExistingTokenAddr(client, params.rootERC20TokenAddr, rootERC20Name, rootchainConfig); err != nil { return deploymentResultInfo{RootchainCfg: nil, CommandResults: nil}, err } @@ -688,11 +688,11 @@ func deployContracts(outputter command.OutputFormatter, client *jsonrpc.Client, // populateExistingTokenAddr checks whether given token is deployed on the provided address. // If it is, then its address is set to the rootchain config, otherwise an error is returned -func populateExistingTokenAddr(eth *jsonrpc.Eth, tokenAddr, tokenName string, +func populateExistingTokenAddr(eth *jsonrpc.EthClient, tokenAddr, tokenName string, rootchainCfg *polybft.RootchainConfig) error { addr := types.StringToAddress(tokenAddr) - code, err := eth.GetCode(ethgo.Address(addr), ethgo.Latest) + code, err := eth.GetCode(addr, jsonrpc.LatestBlockNumberOrHash) if err != nil { return fmt.Errorf("failed to check is %s token deployed: %w", tokenName, err) } else if code == "0x" { diff --git a/command/bridge/deploy/deploy_test.go b/command/bridge/deploy/deploy_test.go index 12d2d6bce4..d575baae8c 100644 --- a/command/bridge/deploy/deploy_test.go +++ b/command/bridge/deploy/deploy_test.go @@ -5,9 +5,9 @@ import ( "os" "testing" + "github.com/0xPolygon/polygon-edge/jsonrpc" "github.com/stretchr/testify/require" "github.com/umbracle/ethgo" - "github.com/umbracle/ethgo/jsonrpc" "github.com/umbracle/ethgo/testutil" "github.com/0xPolygon/polygon-edge/command" @@ -27,7 +27,7 @@ func TestDeployContracts_NoPanics(t *testing.T) { } }) - client, err := jsonrpc.NewClient(server.HTTPAddr()) + client, err := jsonrpc.NewEthClient(server.HTTPAddr()) require.NoError(t, err) testKey, err := helper.DecodePrivateKey("") diff --git a/command/validator/registration/register_validator.go b/command/validator/registration/register_validator.go index 59c6416961..8c0b2973b5 100644 --- a/command/validator/registration/register_validator.go +++ b/command/validator/registration/register_validator.go @@ -90,7 +90,7 @@ func runCommand(cmd *cobra.Command, _ []string) error { return err } - rootChainID, err := txRelayer.Client().Eth().ChainID() + rootChainID, err := txRelayer.Client().ChainID() if err != nil { return err } diff --git a/consensus/polybft/checkpoint_manager_test.go b/consensus/polybft/checkpoint_manager_test.go index c3a2a03da8..2cb1411f05 100644 --- a/consensus/polybft/checkpoint_manager_test.go +++ b/consensus/polybft/checkpoint_manager_test.go @@ -7,7 +7,7 @@ import ( "strconv" "testing" - "github.com/umbracle/ethgo/jsonrpc" + "github.com/0xPolygon/polygon-edge/jsonrpc" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" "github.com/0xPolygon/polygon-edge/consensus/polybft/signer" @@ -495,7 +495,7 @@ func (d *dummyTxRelayer) SendTransactionLocal(txn *types.Transaction) (*ethgo.Re return args.Get(0).(*ethgo.Receipt), args.Error(1) } -func (d *dummyTxRelayer) Client() *jsonrpc.Client { +func (d *dummyTxRelayer) Client() *jsonrpc.EthClient { return nil } diff --git a/consensus/polybft/stake_manager_test.go b/consensus/polybft/stake_manager_test.go index c6b5cf4993..ab0fce6a4e 100644 --- a/consensus/polybft/stake_manager_test.go +++ b/consensus/polybft/stake_manager_test.go @@ -8,6 +8,7 @@ import ( "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/jsonrpc" "github.com/0xPolygon/polygon-edge/txrelayer" "github.com/0xPolygon/polygon-edge/types" "github.com/hashicorp/go-hclog" @@ -15,7 +16,6 @@ import ( "github.com/stretchr/testify/require" "github.com/umbracle/ethgo" "github.com/umbracle/ethgo/abi" - "github.com/umbracle/ethgo/jsonrpc" ) func TestStakeManager_PostBlock(t *testing.T) { @@ -534,6 +534,6 @@ func (d *dummyStakeTxRelayer) SendTransactionLocal(txn *types.Transaction) (*eth return args.Get(0).(*ethgo.Receipt), args.Error(1) } -func (d *dummyStakeTxRelayer) Client() *jsonrpc.Client { +func (d *dummyStakeTxRelayer) Client() *jsonrpc.EthClient { return nil } diff --git a/e2e-polybft/e2e/acls_test.go b/e2e-polybft/e2e/acls_test.go index 154a0717f6..d71b3fad9e 100644 --- a/e2e-polybft/e2e/acls_test.go +++ b/e2e-polybft/e2e/acls_test.go @@ -77,17 +77,18 @@ func TestE2E_AllowList_ContractDeployment(t *testing.T) { deployTxn := cluster.Deploy(t, target, bytecode) require.NoError(t, deployTxn.Wait()) require.True(t, deployTxn.Reverted()) - require.False(t, cluster.ExistsCode(t, deployTxn.Receipt().ContractAddress)) + require.False(t, cluster.ExistsCode(t, types.Address(deployTxn.Receipt().ContractAddress))) } { // Step 3. 'adminAddr' can create contracts deployTxn := cluster.Deploy(t, admin, bytecode) require.NoError(t, deployTxn.Wait()) - require.True(t, deployTxn.Succeed()) - require.True(t, cluster.ExistsCode(t, deployTxn.Receipt().ContractAddress)) proxyContract = types.Address(deployTxn.Receipt().ContractAddress) + + require.True(t, deployTxn.Succeed()) + require.True(t, cluster.ExistsCode(t, proxyContract)) } { @@ -104,7 +105,7 @@ func TestE2E_AllowList_ContractDeployment(t *testing.T) { deployTxn := cluster.Deploy(t, target, bytecode) require.NoError(t, deployTxn.Wait()) require.True(t, deployTxn.Succeed()) - require.True(t, cluster.ExistsCode(t, deployTxn.Receipt().ContractAddress)) + require.True(t, cluster.ExistsCode(t, types.Address(deployTxn.Receipt().ContractAddress))) } { @@ -168,7 +169,7 @@ func TestE2E_BlockList_ContractDeployment(t *testing.T) { deployTxn := cluster.Deploy(t, target, bytecode) require.NoError(t, deployTxn.Wait()) require.True(t, deployTxn.Succeed()) - require.True(t, cluster.ExistsCode(t, deployTxn.Receipt().ContractAddress)) + require.True(t, cluster.ExistsCode(t, types.Address(deployTxn.Receipt().ContractAddress))) } { @@ -176,7 +177,7 @@ func TestE2E_BlockList_ContractDeployment(t *testing.T) { deployTxn := cluster.Deploy(t, admin, bytecode) require.NoError(t, deployTxn.Wait()) require.True(t, deployTxn.Succeed()) - require.True(t, cluster.ExistsCode(t, deployTxn.Receipt().ContractAddress)) + require.True(t, cluster.ExistsCode(t, types.Address(deployTxn.Receipt().ContractAddress))) } { @@ -193,7 +194,7 @@ func TestE2E_BlockList_ContractDeployment(t *testing.T) { deployTxn := cluster.Deploy(t, target, bytecode) require.NoError(t, deployTxn.Wait()) require.True(t, deployTxn.Reverted()) - require.False(t, cluster.ExistsCode(t, deployTxn.Receipt().ContractAddress)) + require.False(t, cluster.ExistsCode(t, types.Address(deployTxn.Receipt().ContractAddress))) } { @@ -256,7 +257,7 @@ func TestE2E_AllowList_Transactions(t *testing.T) { deployTxn := cluster.Deploy(t, target, bytecode) require.NoError(t, deployTxn.Wait()) require.True(t, deployTxn.Reverted()) - require.False(t, cluster.ExistsCode(t, deployTxn.Receipt().ContractAddress)) + require.False(t, cluster.ExistsCode(t, types.Address(deployTxn.Receipt().ContractAddress))) } { diff --git a/e2e-polybft/e2e/bridge_test.go b/e2e-polybft/e2e/bridge_test.go index 409a4d5a09..4a30bae5ce 100644 --- a/e2e-polybft/e2e/bridge_test.go +++ b/e2e-polybft/e2e/bridge_test.go @@ -22,6 +22,7 @@ import ( "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/jsonrpc" "github.com/0xPolygon/polygon-edge/state/runtime/addresslist" "github.com/0xPolygon/polygon-edge/txrelayer" "github.com/0xPolygon/polygon-edge/types" @@ -89,12 +90,12 @@ func TestE2E_Bridge_RootchainTokensTransfers(t *testing.T) { validatorSrv := cluster.Servers[0] - childEthEndpoint := validatorSrv.JSONRPC().Eth() + childEthEndpoint := validatorSrv.JSONRPC() rootchainTxRelayer, err := txrelayer.NewTxRelayer(txrelayer.WithIPAddress(cluster.Bridge.JSONRPCAddr())) require.NoError(t, err) - txRelayer, err := txrelayer.NewTxRelayer(txrelayer.WithClient(validatorSrv.JSONRPC())) + txRelayer, err := txrelayer.NewTxRelayer(txrelayer.WithClient(childEthEndpoint)) require.NoError(t, err) deployerKey, err := bridgeHelper.DecodePrivateKey("") @@ -198,7 +199,7 @@ func TestE2E_Bridge_RootchainTokensTransfers(t *testing.T) { depositsSubset = 1 ) - txRelayer, err := txrelayer.NewTxRelayer(txrelayer.WithClient(validatorSrv.JSONRPC())) + txRelayer, err := txrelayer.NewTxRelayer(txrelayer.WithClient(childEthEndpoint)) require.NoError(t, err) lastCommittedIDMethod := contractsapi.StateReceiver.Abi.GetMethod("lastCommittedId") @@ -346,7 +347,7 @@ func TestE2E_Bridge_ERC721Transfer(t *testing.T) { receipt, err := rootchainTxRelayer.SendTransaction(deployTx, rootchainDeployer) require.NoError(t, err) - rootERC721Addr := receipt.ContractAddress + rootERC721Addr := types.Address(receipt.ContractAddress) // DEPOSIT ERC721 TOKENS // send a few transactions to the bridge @@ -354,7 +355,7 @@ func TestE2E_Bridge_ERC721Transfer(t *testing.T) { t, cluster.Bridge.Deposit( common.ERC721, - types.Address(rootERC721Addr), + rootERC721Addr, polybftCfg.Bridge.RootERC721PredicateAddr, bridgeHelper.TestAccountPrivKey, strings.Join(receivers[:], ","), @@ -369,7 +370,7 @@ func TestE2E_Bridge_ERC721Transfer(t *testing.T) { require.NoError(t, cluster.WaitForBlock(50, 4*time.Minute)) validatorSrv := cluster.Servers[0] - childEthEndpoint := validatorSrv.JSONRPC().Eth() + childEthEndpoint := validatorSrv.JSONRPC() // the transactions are processed and there should be a success events var stateSyncedResult contractsapi.StateSyncResultEvent @@ -390,14 +391,14 @@ func TestE2E_Bridge_ERC721Transfer(t *testing.T) { require.NoError(t, cluster.WaitForBlock(uint64(50+(i+1)*epochSize), 1*time.Minute)) } - txRelayer, err := txrelayer.NewTxRelayer(txrelayer.WithClient(validatorSrv.JSONRPC())) + txRelayer, err := txrelayer.NewTxRelayer(txrelayer.WithClient(childEthEndpoint)) require.NoError(t, err) // retrieve child token address (from both chains, and assert they are the same) l1ChildTokenAddr := getChildToken(t, contractsapi.RootERC721Predicate.Abi, polybftCfg.Bridge.RootERC721PredicateAddr, - types.Address(rootERC721Addr), rootchainTxRelayer) + rootERC721Addr, rootchainTxRelayer) l2ChildTokenAddr := getChildToken(t, contractsapi.ChildERC721Predicate.Abi, contracts.ChildERC721PredicateContract, - types.Address(rootERC721Addr), txRelayer) + rootERC721Addr, txRelayer) t.Log("L1 child token", l1ChildTokenAddr) t.Log("L2 child token", l2ChildTokenAddr) @@ -426,10 +427,10 @@ func TestE2E_Bridge_ERC721Transfer(t *testing.T) { require.NoError(t, err) } - currentBlock, err := childEthEndpoint.GetBlockByNumber(ethgo.Latest, false) + currentBlock, err := childEthEndpoint.GetBlockByNumber(jsonrpc.LatestBlockNumber, false) require.NoError(t, err) - currentExtra, err := polybft.GetIbftExtra(currentBlock.ExtraData) + currentExtra, err := polybft.GetIbftExtra(currentBlock.Header.ExtraData) require.NoError(t, err) t.Logf("Latest block number: %d, epoch number: %d\n", currentBlock.Number, currentExtra.Checkpoint.EpochNumber) @@ -449,7 +450,7 @@ func TestE2E_Bridge_ERC721Transfer(t *testing.T) { // assert that owners of given token ids are the accounts on the root chain ERC 721 token for i, receiver := range receiversAddrs { - owner := erc721OwnerOf(t, big.NewInt(int64(i)), types.Address(rootERC721Addr), rootchainTxRelayer) + owner := erc721OwnerOf(t, big.NewInt(int64(i)), rootERC721Addr, rootchainTxRelayer) require.Equal(t, receiver, owner) } } @@ -528,7 +529,7 @@ func TestE2E_Bridge_ERC1155Transfer(t *testing.T) { t, cluster.Bridge.Deposit( common.ERC1155, - types.Address(rootERC1155Addr), + rootERC1155Addr, polybftCfg.Bridge.RootERC1155PredicateAddr, bridgeHelper.TestAccountPrivKey, strings.Join(receivers[:], ","), @@ -543,7 +544,7 @@ func TestE2E_Bridge_ERC1155Transfer(t *testing.T) { require.NoError(t, cluster.WaitForBlock(50, 4*time.Minute)) validatorSrv := cluster.Servers[0] - childEthEndpoint := validatorSrv.JSONRPC().Eth() + childEthEndpoint := validatorSrv.JSONRPC() // the transactions are processed and there should be a success events var stateSyncedResult contractsapi.StateSyncResultEvent @@ -564,14 +565,14 @@ func TestE2E_Bridge_ERC1155Transfer(t *testing.T) { require.NoError(t, cluster.WaitForBlock(uint64(50+(i+1)*epochSize), 1*time.Minute)) } - txRelayer, err := txrelayer.NewTxRelayer(txrelayer.WithClient(validatorSrv.JSONRPC())) + txRelayer, err := txrelayer.NewTxRelayer(txrelayer.WithClient(childEthEndpoint)) require.NoError(t, err) // retrieve child token address l1ChildTokenAddr := getChildToken(t, contractsapi.RootERC1155Predicate.Abi, polybftCfg.Bridge.RootERC1155PredicateAddr, - types.Address(rootERC1155Addr), rootchainTxRelayer) + rootERC1155Addr, rootchainTxRelayer) l2ChildTokenAddr := getChildToken(t, contractsapi.ChildERC1155Predicate.Abi, contracts.ChildERC1155PredicateContract, - types.Address(rootERC1155Addr), txRelayer) + rootERC1155Addr, txRelayer) t.Log("L1 child token", l1ChildTokenAddr) t.Log("L2 child token", l2ChildTokenAddr) @@ -618,10 +619,10 @@ func TestE2E_Bridge_ERC1155Transfer(t *testing.T) { require.NoError(t, err) } - currentBlock, err := childEthEndpoint.GetBlockByNumber(ethgo.Latest, false) + currentBlock, err := childEthEndpoint.GetBlockByNumber(jsonrpc.LatestBlockNumber, false) require.NoError(t, err) - currentExtra, err := polybft.GetIbftExtra(currentBlock.ExtraData) + currentExtra, err := polybft.GetIbftExtra(currentBlock.Header.ExtraData) require.NoError(t, err) currentEpoch := currentExtra.Checkpoint.EpochNumber @@ -709,7 +710,7 @@ func TestE2E_Bridge_ChildchainTokensTransfer(t *testing.T) { require.NoError(t, err) validatorSrv := cluster.Servers[0] - childEthEndpoint := validatorSrv.JSONRPC().Eth() + childEthEndpoint := validatorSrv.JSONRPC() // fund accounts on rootchain require.NoError(t, validatorSrv.RootchainFundFor(depositors, funds)) @@ -719,7 +720,7 @@ func TestE2E_Bridge_ChildchainTokensTransfer(t *testing.T) { rootchainTxRelayer, err := txrelayer.NewTxRelayer(txrelayer.WithIPAddress(cluster.Bridge.JSONRPCAddr())) require.NoError(t, err) - childchainTxRelayer, err := txrelayer.NewTxRelayer(txrelayer.WithClient(validatorSrv.JSONRPC())) + childchainTxRelayer, err := txrelayer.NewTxRelayer(txrelayer.WithClient(childEthEndpoint)) require.NoError(t, err) t.Run("bridge native tokens", func(t *testing.T) { @@ -764,10 +765,10 @@ func TestE2E_Bridge_ChildchainTokensTransfer(t *testing.T) { require.NoError(t, err) } - latestBlock, err := childEthEndpoint.GetBlockByNumber(ethgo.Latest, false) + latestBlock, err := childEthEndpoint.GetBlockByNumber(jsonrpc.LatestBlockNumber, false) require.NoError(t, err) - extra, err := polybft.GetIbftExtra(latestBlock.ExtraData) + extra, err := polybft.GetIbftExtra(latestBlock.Header.ExtraData) require.NoError(t, err) // wait for checkpoint to get submitted before invoking exit transactions @@ -803,7 +804,7 @@ func TestE2E_Bridge_ChildchainTokensTransfer(t *testing.T) { balancesBefore := make([]*big.Int, transfersCount) for i := uint64(0); i < transfersCount; i++ { - balancesBefore[i], err = childEthEndpoint.GetBalance(ethgo.Address(depositors[i]), ethgo.Latest) + balancesBefore[i], err = childEthEndpoint.GetBalance(depositors[i], jsonrpc.LatestBlockNumberOrHash) require.NoError(t, err) } @@ -856,7 +857,7 @@ func TestE2E_Bridge_ChildchainTokensTransfer(t *testing.T) { erc721DeployTxn := cluster.Deploy(t, admin, contractsapi.RootERC721.Bytecode) require.NoError(t, erc721DeployTxn.Wait()) require.True(t, erc721DeployTxn.Succeed()) - rootERC721Token := erc721DeployTxn.Receipt().ContractAddress + rootERC721Token := types.Address(erc721DeployTxn.Receipt().ContractAddress) for _, depositor := range depositors { // mint all the depositors in advance @@ -864,7 +865,7 @@ func TestE2E_Bridge_ChildchainTokensTransfer(t *testing.T) { mintInput, err := mintFn.EncodeAbi() require.NoError(t, err) - mintTxn := cluster.MethodTxn(t, admin, types.Address(rootERC721Token), mintInput) + mintTxn := cluster.MethodTxn(t, admin, rootERC721Token, mintInput) require.NoError(t, mintTxn.Wait()) require.True(t, mintTxn.Succeed()) @@ -875,7 +876,7 @@ func TestE2E_Bridge_ChildchainTokensTransfer(t *testing.T) { // deposit should fail because depositors are in bridge block list err = cluster.Bridge.Deposit( common.ERC721, - types.Address(rootERC721Token), + rootERC721Token, contracts.RootMintableERC721PredicateContract, depositorKeys[0], depositors[0].String(), @@ -905,10 +906,10 @@ func TestE2E_Bridge_ChildchainTokensTransfer(t *testing.T) { require.NoError(t, err) } - childChainBlock, err := childEthEndpoint.GetBlockByNumber(ethgo.Latest, false) + childChainBlock, err := childEthEndpoint.GetBlockByNumber(jsonrpc.LatestBlockNumber, false) require.NoError(t, err) - childChainBlockExtra, err := polybft.GetIbftExtra(childChainBlock.ExtraData) + childChainBlockExtra, err := polybft.GetIbftExtra(childChainBlock.Header.ExtraData) require.NoError(t, err) // wait for checkpoint to be submitted @@ -1088,8 +1089,8 @@ func TestE2E_Bridge_Transfers_AccessLists(t *testing.T) { require.NoError(t, err) validatorSrv := cluster.Servers[0] - childEthEndpoint := validatorSrv.JSONRPC().Eth() - relayer, err := txrelayer.NewTxRelayer(txrelayer.WithClient(validatorSrv.JSONRPC())) + childEthEndpoint := validatorSrv.JSONRPC() + relayer, err := txrelayer.NewTxRelayer(txrelayer.WithClient(childEthEndpoint)) require.NoError(t, err) senderAccount, err := validatorHelper.GetAccountFromDir(validatorSrv.DataDir()) @@ -1209,10 +1210,10 @@ func TestE2E_Bridge_Transfers_AccessLists(t *testing.T) { false) require.ErrorContains(t, err, "failed to send withdraw transaction") - currentBlock, err := childEthEndpoint.GetBlockByNumber(ethgo.Latest, false) + currentBlock, err := childEthEndpoint.GetBlockByNumber(jsonrpc.LatestBlockNumber, false) require.NoError(t, err) - currentExtra, err := polybft.GetIbftExtra(currentBlock.ExtraData) + currentExtra, err := polybft.GetIbftExtra(currentBlock.Header.ExtraData) require.NoError(t, err) t.Logf("Latest block number: %d, epoch number: %d\n", currentBlock.Number, currentExtra.Checkpoint.EpochNumber) @@ -1306,7 +1307,7 @@ func TestE2E_Bridge_NonMintableERC20Token_WithPremine(t *testing.T) { rootchainTxRelayer, err := txrelayer.NewTxRelayer(txrelayer.WithIPAddress(cluster.Bridge.JSONRPCAddr())) require.NoError(t, err) - childEthEndpoint := cluster.Servers[0].JSONRPC().Eth() + childEthEndpoint := cluster.Servers[0].JSONRPC() defer cluster.Stop() @@ -1327,7 +1328,7 @@ func TestE2E_Bridge_NonMintableERC20Token_WithPremine(t *testing.T) { t.Log("Balance of native ERC20 token on root", balance, "Address", address) require.Equal(t, rootExpected, balance) - balance, err = childEthEndpoint.GetBalance(ethgo.Address(address), ethgo.Latest) + balance, err = childEthEndpoint.GetBalance(address, jsonrpc.LatestBlockNumberOrHash) require.NoError(t, err) t.Log("Balance of native ERC20 token on child", balance, "Address", address) @@ -1375,7 +1376,7 @@ func TestE2E_Bridge_NonMintableERC20Token_WithPremine(t *testing.T) { require.NoError(t, err) validatorBalanceAfterWithdraw, err := childEthEndpoint.GetBalance( - ethgo.Address(validatorAcc.Address()), ethgo.Latest) + validatorAcc.Address(), jsonrpc.LatestBlockNumberOrHash) require.NoError(t, err) err = cluster.Bridge.Withdraw( @@ -1391,13 +1392,13 @@ func TestE2E_Bridge_NonMintableERC20Token_WithPremine(t *testing.T) { require.NoError(t, err) nonValidatorBalanceAfterWithdraw, err := childEthEndpoint.GetBalance( - ethgo.Address(nonValidatorKey.Address()), ethgo.Latest) + nonValidatorKey.Address(), jsonrpc.LatestBlockNumberOrHash) require.NoError(t, err) - currentBlock, err := childEthEndpoint.GetBlockByNumber(ethgo.Latest, false) + currentBlock, err := childEthEndpoint.GetBlockByNumber(jsonrpc.LatestBlockNumber, false) require.NoError(t, err) - currentExtra, err := polybft.GetIbftExtra(currentBlock.ExtraData) + currentExtra, err := polybft.GetIbftExtra(currentBlock.Header.ExtraData) require.NoError(t, err) t.Logf("Latest block number: %d, epoch number: %d\n", currentBlock.Number, currentExtra.Checkpoint.EpochNumber) @@ -1440,11 +1441,11 @@ func TestE2E_Bridge_NonMintableERC20Token_WithPremine(t *testing.T) { false), ) - currentBlock, err := childEthEndpoint.GetBlockByNumber(ethgo.Latest, false) + currentBlock, err := childEthEndpoint.GetBlockByNumber(jsonrpc.LatestBlockNumber, false) require.NoError(t, err) // wait for a couple of sprints - finalBlockNum := currentBlock.Number + 5*sprintSize + finalBlockNum := currentBlock.Header.Number + 5*sprintSize // the transaction is processed and there should be a success event var stateSyncedResult contractsapi.StateSyncResultEvent diff --git a/e2e-polybft/e2e/burn_contract_test.go b/e2e-polybft/e2e/burn_contract_test.go index 057eb8e718..f7224c64fe 100644 --- a/e2e-polybft/e2e/burn_contract_test.go +++ b/e2e-polybft/e2e/burn_contract_test.go @@ -6,9 +6,9 @@ import ( "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/jsonrpc" "github.com/0xPolygon/polygon-edge/types" "github.com/stretchr/testify/require" - "github.com/umbracle/ethgo" ) func TestE2E_BurnContract_Deployed(t *testing.T) { @@ -30,10 +30,10 @@ func TestE2E_BurnContract_Deployed(t *testing.T) { defer cluster.Stop() cluster.WaitForReady(t) - client := cluster.Servers[0].JSONRPC().Eth() + client := cluster.Servers[0].JSONRPC() // Get the code for the default deployed burn contract - code, err := client.GetCode(ethgo.Address(contractAddr), ethgo.Latest) + code, err := client.GetCode(contractAddr, jsonrpc.LatestBlockNumberOrHash) require.NoError(t, err) require.NotEqual(t, code, "0x") } diff --git a/e2e-polybft/e2e/consensus_test.go b/e2e-polybft/e2e/consensus_test.go index e55a147e76..3a12d20afe 100644 --- a/e2e-polybft/e2e/consensus_test.go +++ b/e2e-polybft/e2e/consensus_test.go @@ -23,6 +23,7 @@ import ( "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/jsonrpc" "github.com/0xPolygon/polygon-edge/txrelayer" "github.com/0xPolygon/polygon-edge/types" ) @@ -60,7 +61,7 @@ func TestE2E_Consensus_Basic(t *testing.T) { t.Run("sync protocol, drop single validator node", func(t *testing.T) { // query the current block number, as it is a starting point for the test - currentBlockNum, err := cluster.Servers[0].JSONRPC().Eth().BlockNumber() + currentBlockNum, err := cluster.Servers[0].JSONRPC().BlockNumber() require.NoError(t, err) // stop one node @@ -79,7 +80,7 @@ func TestE2E_Consensus_Basic(t *testing.T) { t.Run("sync protocol, drop single non-validator node", func(t *testing.T) { // query the current block number, as it is a starting point for the test - currentBlockNum, err := cluster.Servers[0].JSONRPC().Eth().BlockNumber() + currentBlockNum, err := cluster.Servers[0].JSONRPC().BlockNumber() require.NoError(t, err) // stop one non-validator node @@ -192,10 +193,10 @@ func TestE2E_Consensus_RegisterValidator(t *testing.T) { require.NoError(t, err) require.Equal(t, validatorSetSize+2, len(validatorSecrets)) - genesisBlock, err := owner.JSONRPC().Eth().GetBlockByNumber(0, false) + genesisBlock, err := owner.JSONRPC().GetBlockByNumber(0, false) require.NoError(t, err) - _, err = polybft.GetIbftExtra(genesisBlock.ExtraData) + _, err = polybft.GetIbftExtra(genesisBlock.Header.ExtraData) require.NoError(t, err) // owner whitelists both new validators @@ -212,12 +213,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(ethgo.Address(firstValidatorAddr), ethgo.Latest) + firstBalance, err := relayer.Client().GetBalance(firstValidatorAddr, jsonrpc.LatestBlockNumberOrHash) 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(ethgo.Address(secondValidatorAddr), ethgo.Latest) + secondBalance, err := relayer.Client().GetBalance(secondValidatorAddr, jsonrpc.LatestBlockNumberOrHash) require.NoError(t, err) t.Logf("Second validator balance=%d\n", secondBalance) @@ -251,11 +252,11 @@ func TestE2E_Consensus_RegisterValidator(t *testing.T) { require.True(t, secondValidatorInfo.IsActive) require.True(t, secondValidatorInfo.Stake.Cmp(stakeAmount) == 0) - currentBlock, err := owner.JSONRPC().Eth().GetBlockByNumber(ethgo.Latest, false) + currentBlock, err := owner.JSONRPC().GetBlockByNumber(jsonrpc.LatestBlockNumber, false) require.NoError(t, err) // wait for couple of epochs to have some rewards accumulated - require.NoError(t, cluster.WaitForBlock(currentBlock.Number+(polybftConfig.EpochSize*2), time.Minute)) + require.NoError(t, cluster.WaitForBlock(currentBlock.Header.Number+(polybftConfig.EpochSize*2), time.Minute)) bigZero := big.NewInt(0) @@ -271,10 +272,10 @@ func TestE2E_Consensus_RegisterValidator(t *testing.T) { // wait until one of the validators mine one block to check if they joined consensus require.NoError(t, cluster.WaitUntil(3*time.Minute, 2*time.Second, func() bool { - latestBlock, err := cluster.Servers[0].JSONRPC().Eth().GetBlockByNumber(ethgo.Latest, false) + latestBlock, err := cluster.Servers[0].JSONRPC().GetBlockByNumber(jsonrpc.LatestBlockNumber, false) require.NoError(t, err) - blockMiner := latestBlock.Miner.Bytes() + blockMiner := latestBlock.Header.Miner return bytes.Equal(firstValidatorAddr.Bytes(), blockMiner) || bytes.Equal(secondValidatorAddr.Bytes(), blockMiner) @@ -309,9 +310,9 @@ func TestE2E_Consensus_Validator_Unstake(t *testing.T) { cluster.WaitForReady(t) - validatorAddr := ethgo.Address(validatorAcc.Ecdsa.Address()) + validatorAddr := validatorAcc.Ecdsa.Address() - initialValidatorBalance, err := srv.JSONRPC().Eth().GetBalance(validatorAddr, ethgo.Latest) + initialValidatorBalance, err := srv.JSONRPC().GetBalance(validatorAddr, jsonrpc.LatestBlockNumberOrHash) require.NoError(t, err) t.Logf("Balance (before unstake)=%d\n", initialValidatorBalance) @@ -332,11 +333,11 @@ func TestE2E_Consensus_Validator_Unstake(t *testing.T) { // unstake entire balance (which should remove validator from the validator set in next epoch) require.NoError(t, srv.Unstake(initialStake)) - currentBlock, err := srv.JSONRPC().Eth().GetBlockByNumber(ethgo.Latest, false) + currentBlock, err := srv.JSONRPC().GetBlockByNumber(jsonrpc.LatestBlockNumber, false) require.NoError(t, err) // wait for couple of epochs to withdraw stake - require.NoError(t, cluster.WaitForBlock(currentBlock.Number+(polybftCfg.EpochSize*2), time.Minute)) + require.NoError(t, cluster.WaitForBlock(currentBlock.Header.Number+(polybftCfg.EpochSize*2), time.Minute)) require.NoError(t, srv.WitdhrawStake()) // check that validator is no longer active (out of validator set) @@ -347,14 +348,14 @@ func TestE2E_Consensus_Validator_Unstake(t *testing.T) { t.Logf("Stake (after unstake and withdraw)=%d\n", validatorInfo.Stake) - balanceBeforeRewardsWithdraw, err := srv.JSONRPC().Eth().GetBalance(validatorAddr, ethgo.Latest) + balanceBeforeRewardsWithdraw, err := srv.JSONRPC().GetBalance(validatorAddr, jsonrpc.LatestBlockNumberOrHash) 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(validatorAddr, ethgo.Latest) + newValidatorBalance, err := srv.JSONRPC().GetBalance(validatorAddr, jsonrpc.LatestBlockNumberOrHash) require.NoError(t, err) t.Logf("Balance (after withdrawal of rewards)=%s\n", newValidatorBalance) require.True(t, newValidatorBalance.Cmp(balanceBeforeRewardsWithdraw) > 0) @@ -432,7 +433,7 @@ func TestE2E_Consensus_MintableERC20NativeToken(t *testing.T) { mintAmount := ethgo.Ether(1) // make sure minter account can mint tokens - balanceBefore, err := targetJSONRPC.Eth().GetBalance(ethgo.Address(receiver.Address()), ethgo.Latest) + balanceBefore, err := targetJSONRPC.GetBalance(receiver.Address(), jsonrpc.LatestBlockNumberOrHash) require.NoError(t, err) t.Logf("Pre-mint balance: %v=%d\n", receiver.Address(), balanceBefore) @@ -455,7 +456,7 @@ func TestE2E_Consensus_MintableERC20NativeToken(t *testing.T) { require.NoError(t, err) require.Equal(t, uint64(types.ReceiptSuccess), receipt.Status) - balanceAfter, err := targetJSONRPC.Eth().GetBalance(ethgo.Address(receiver.Address()), ethgo.Latest) + balanceAfter, err := targetJSONRPC.GetBalance(receiver.Address(), jsonrpc.LatestBlockNumberOrHash) require.NoError(t, err) t.Logf("Post-mint balance: %v=%d\n", receiver.Address(), balanceAfter) @@ -534,11 +535,11 @@ func TestE2E_Consensus_EIP1559Check(t *testing.T) { cluster.WaitForReady(t) - client := cluster.Servers[0].JSONRPC().Eth() + client := cluster.Servers[0].JSONRPC() waitUntilBalancesChanged := func(acct types.Address, initialBalance *big.Int) error { err := cluster.WaitUntil(30*time.Second, 1*time.Second, func() bool { - balance, err := client.GetBalance(ethgo.Address(acct), ethgo.Latest) + balance, err := client.GetBalance(acct, jsonrpc.LatestBlockNumberOrHash) if err != nil { return true } @@ -574,12 +575,12 @@ func TestE2E_Consensus_EIP1559Check(t *testing.T) { initialMinerBalance := big.NewInt(0) - prevMiner := ethgo.ZeroAddress + prevMiner := types.ZeroAddress.Bytes() for i, txn := range txns { - 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) + senderInitialBalance, _ := client.GetBalance(sender.Address(), jsonrpc.LatestBlockNumberOrHash) + receiverInitialBalance, _ := client.GetBalance(recipient, jsonrpc.LatestBlockNumberOrHash) + burnContractInitialBalance, _ := client.GetBalance(types.ZeroAddress, jsonrpc.LatestBlockNumberOrHash) receipt, err := relayer.SendTransaction(txn, sender) require.NoError(t, err) @@ -589,21 +590,21 @@ func TestE2E_Consensus_EIP1559Check(t *testing.T) { err = waitUntilBalancesChanged(recipient, receiverInitialBalance) require.NoError(t, err) - block, _ := client.GetBlockByHash(receipt.BlockHash, true) - finalMinerFinalBalance, _ := client.GetBalance(block.Miner, ethgo.Latest) + block, _ := client.GetBlockByHash(types.Hash(receipt.BlockHash), true) + finalMinerFinalBalance, _ := client.GetBalance(types.BytesToAddress(block.Header.Miner), jsonrpc.LatestBlockNumberOrHash) if i == 0 { - prevMiner = block.Miner + prevMiner = block.Header.Miner } - 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) + senderFinalBalance, _ := client.GetBalance(sender.Address(), jsonrpc.LatestBlockNumberOrHash) + receiverFinalBalance, _ := client.GetBalance(recipient, jsonrpc.LatestBlockNumberOrHash) + burnContractFinalBalance, _ := client.GetBalance(types.ZeroAddress, jsonrpc.LatestBlockNumberOrHash) diffReceiverBalance := new(big.Int).Sub(receiverFinalBalance, receiverInitialBalance) require.Equal(t, sendAmount, diffReceiverBalance, "Receiver balance should be increased by send amount") - if i == 1 && prevMiner != block.Miner { + if i == 1 && bytes.Equal(prevMiner, block.Header.Miner) { initialMinerBalance = big.NewInt(0) } @@ -717,12 +718,12 @@ func TestE2E_Consensus_ChangeVotingPowerByStakingPendingRewards(t *testing.T) { for i := 0; i < numOfEpochsToCheckChange; i++ { require.NoError(t, cluster.WaitForBlock(epochEndingBlock, time.Minute)) - latestBlock, err := cluster.Servers[0].JSONRPC().Eth().GetBlockByNumber(ethgo.BlockNumber(epochEndingBlock), false) + latestBlock, err := cluster.Servers[0].JSONRPC().GetBlockByNumber(jsonrpc.BlockNumber(epochEndingBlock), false) require.NoError(t, err) epochEndingBlock += epochSize - currentExtra, err := polybft.GetIbftExtra(latestBlock.ExtraData) + currentExtra, err := polybft.GetIbftExtra(latestBlock.Header.ExtraData) require.NoError(t, err) if currentExtra.Validators == nil || currentExtra.Validators.IsEmpty() { diff --git a/e2e-polybft/e2e/governance_test.go b/e2e-polybft/e2e/governance_test.go index edcbef1653..e9b47da7ce 100644 --- a/e2e-polybft/e2e/governance_test.go +++ b/e2e-polybft/e2e/governance_test.go @@ -13,10 +13,10 @@ import ( "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/jsonrpc" "github.com/0xPolygon/polygon-edge/txrelayer" "github.com/0xPolygon/polygon-edge/types" "github.com/stretchr/testify/require" - "github.com/umbracle/ethgo" ) type VoteType uint8 @@ -119,7 +119,7 @@ func TestE2E_Governance_ProposeAndExecuteSimpleProposal(t *testing.T) { return proposalState == Queued })) - currentBlockNumber, err := relayer.Client().Eth().BlockNumber() + currentBlockNumber, err := relayer.Client().BlockNumber() require.NoError(t, err) // wait for couple of more blocks because of execution delay @@ -131,7 +131,7 @@ func TestE2E_Governance_ProposeAndExecuteSimpleProposal(t *testing.T) { polybftCfg.GovernanceConfig.NetworkParamsAddr, proposalInput, proposalDescription) - currentBlockNumber, err = relayer.Client().Eth().BlockNumber() + currentBlockNumber, err = relayer.Client().BlockNumber() require.NoError(t, err) // check if epoch size changed on NetworkParams @@ -149,20 +149,20 @@ func TestE2E_Governance_ProposeAndExecuteSimpleProposal(t *testing.T) { // wait until the new epoch (with new size finishes) require.NoError(t, cluster.WaitForBlock(endOfNewEpoch, 3*time.Minute)) - block, err := relayer.Client().Eth().GetBlockByNumber( - ethgo.BlockNumber(endOfPreviousEpoch), false) + block, err := relayer.Client().GetBlockByNumber( + jsonrpc.BlockNumber(endOfPreviousEpoch), false) require.NoError(t, err) - extra, err := polybft.GetIbftExtra(block.ExtraData) + extra, err := polybft.GetIbftExtra(block.Header.ExtraData) require.NoError(t, err) oldEpoch := extra.Checkpoint.EpochNumber - block, err = relayer.Client().Eth().GetBlockByNumber( - ethgo.BlockNumber(endOfNewEpoch), false) + block, err = relayer.Client().GetBlockByNumber( + jsonrpc.BlockNumber(endOfNewEpoch), false) require.NoError(t, err) - extra, err = polybft.GetIbftExtra(block.ExtraData) + extra, err = polybft.GetIbftExtra(block.Header.ExtraData) require.NoError(t, err) newEpoch := extra.Checkpoint.EpochNumber @@ -209,7 +209,7 @@ func TestE2E_Governance_ProposeAndExecuteSimpleProposal(t *testing.T) { relayer, voterAcc.Ecdsa) } - currentBlockNumber, err := relayer.Client().Eth().BlockNumber() + currentBlockNumber, err := relayer.Client().BlockNumber() require.NoError(t, err) // wait for voting period to end @@ -277,7 +277,7 @@ func TestE2E_Governance_ProposeAndExecuteSimpleProposal(t *testing.T) { return proposalState == Queued })) - currentBlockNumber, err := relayer.Client().Eth().BlockNumber() + currentBlockNumber, err := relayer.Client().BlockNumber() require.NoError(t, err) // wait for couple of more blocks because of execution delay diff --git a/e2e-polybft/e2e/helpers_test.go b/e2e-polybft/e2e/helpers_test.go index 3290eeef6d..b623d5a6c8 100644 --- a/e2e-polybft/e2e/helpers_test.go +++ b/e2e-polybft/e2e/helpers_test.go @@ -6,10 +6,10 @@ import ( "testing" "time" + "github.com/0xPolygon/polygon-edge/jsonrpc" "github.com/stretchr/testify/require" "github.com/umbracle/ethgo" "github.com/umbracle/ethgo/abi" - "github.com/umbracle/ethgo/jsonrpc" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" "github.com/0xPolygon/polygon-edge/contracts" @@ -33,7 +33,13 @@ func ABICall(relayer txrelayer.TxRelayer, artifact *contracts.Artifact, contract return relayer.Call(senderAddr, contractAddress, input) } -func ABITransaction(relayer txrelayer.TxRelayer, key crypto.Key, artifact *contracts.Artifact, contractAddress types.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 @@ -157,7 +163,7 @@ func expectRole(t *testing.T, cluster *framework.TestCluster, contract types.Add // getFilteredLogs retrieves Ethereum logs, described by event signature within the block range func getFilteredLogs(eventSig ethgo.Hash, startBlock, endBlock uint64, - ethEndpoint *jsonrpc.Eth) ([]*ethgo.Log, error) { + ethEndpoint *jsonrpc.EthClient) ([]*ethgo.Log, error) { filter := ðgo.LogFilter{Topics: [][]*ethgo.Hash{{&eventSig}}} filter.SetFromUint64(startBlock) diff --git a/e2e-polybft/e2e/jsonrpc_test.go b/e2e-polybft/e2e/jsonrpc_test.go index 5e6b684c30..a6b04c036d 100644 --- a/e2e-polybft/e2e/jsonrpc_test.go +++ b/e2e-polybft/e2e/jsonrpc_test.go @@ -7,16 +7,13 @@ import ( "github.com/stretchr/testify/require" "github.com/umbracle/ethgo" - "github.com/umbracle/ethgo/jsonrpc" "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/helper/hex" "github.com/0xPolygon/polygon-edge/helper/tests" bladeRPC "github.com/0xPolygon/polygon-edge/jsonrpc" - "github.com/0xPolygon/polygon-edge/state" "github.com/0xPolygon/polygon-edge/types" ) @@ -25,413 +22,6 @@ var ( ) func TestE2E_JsonRPC(t *testing.T) { - senderKey, err := crypto.GenerateECDSAKey() - require.NoError(t, err) - - cluster := framework.NewTestCluster(t, 4, - framework.WithPremine(senderKey.Address()), - framework.WithHTTPS("/etc/ssl/certs/localhost.pem", "/etc/ssl/private/localhost.key"), - ) - defer cluster.Stop() - - cluster.WaitForReady(t) - - jsonRPC := cluster.Servers[0].JSONRPC() - client := jsonRPC.Eth() - debug := jsonRPC.Debug() - - // Test eth_call with override in state diff - t.Run("eth_call state override", func(t *testing.T) { - 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() - - resp, err := client.Call(ðgo.CallMsg{To: &target, Data: input}, ethgo.Latest) - require.NoError(t, err) - require.Equal(t, "0x0000000000000000000000000000000000000000000000000000000000000000", resp) - - override := ðgo.StateOverride{ - target: ethgo.OverrideAccount{ - StateDiff: &map[ethgo.Hash]ethgo.Hash{ - // storage slot 0 stores the 'val' uint256 value - {0x0}: {0x3}, - }, - }, - } - - resp, err = client.Call(ðgo.CallMsg{To: &target, Data: input}, ethgo.Latest, override) - require.NoError(t, err) - - require.Equal(t, "0x0300000000000000000000000000000000000000000000000000000000000000", resp) - }) - - // Test eth_call with zero account balance - t.Run("eth_call with zero-balance account", func(t *testing.T) { - 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 := crypto.GenerateECDSAKey() - require.NoError(t, err) - - resp, err := client.Call(ðgo.CallMsg{ - From: ethgo.Address(acctZeroBalance.Address()), - To: &target, - Data: input, - }, ethgo.Latest) - require.NoError(t, err) - require.Equal(t, "0x0000000000000000000000000000000000000000000000000000000000000000", resp) - }) - - t.Run("eth_estimateGas", func(t *testing.T) { - 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() - - estimatedGas, err := client.EstimateGas(ðgo.CallMsg{ - From: ethgo.Address(senderKey.Address()), - To: &target, - Data: input, - }) - require.NoError(t, err) - require.Equal(t, uint64(0x5bb7), estimatedGas) - }) - - t.Run("eth_estimateGas by zero-balance account", func(t *testing.T) { - 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 := crypto.GenerateECDSAKey() - require.NoError(t, err) - - resp, err := client.EstimateGas(ðgo.CallMsg{ - From: ethgo.Address(acctZeroBalance.Address()), - To: &target, - Data: input, - }) - require.NoError(t, err) - require.Equal(t, uint64(0x5bb7), resp) - }) - - t.Run("eth_estimateGas by zero-balance account - simple value transfer", func(t *testing.T) { - acctZeroBalance, err := crypto.GenerateECDSAKey() - require.NoError(t, err) - - fundedAccountAddress := senderKey.Address() - nonFundedAccountAddress := acctZeroBalance.Address() - - estimateGasFn := func(value *big.Int) { - resp, err := client.EstimateGas(ðgo.CallMsg{ - From: ethgo.Address(nonFundedAccountAddress), - To: (*ethgo.Address)(&fundedAccountAddress), - Value: value, - }) - - require.NoError(t, err) - require.Equal(t, state.TxGas, resp) - } - - estimateGasFn(ethgo.Gwei(1)) - - // transfer some funds to zero balance account - 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()) - - // now call estimate gas again for the now funded account - estimateGasFn(ethgo.Gwei(1)) - }) - - t.Run("eth_getBalance", func(t *testing.T) { - 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(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, senderKey, recipientKey.Address(), newBalance) - require.NoError(t, txn.Wait()) - require.True(t, txn.Succeed()) - - balance1, err = client.GetBalance(recipientAddr, ethgo.Latest) - require.NoError(t, err) - require.Equal(t, balance1, newBalance) - - // Test. return 0 if the balance of an existing account is empty - gasPrice, err := client.GasPrice() - require.NoError(t, err) - - estimatedGas, err := client.EstimateGas(ðgo.CallMsg{ - From: ethgo.Address(senderKey.Address()), - To: &recipientAddr, - Value: newBalance, - }) - require.NoError(t, err) - txPrice := gasPrice * estimatedGas - // 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 := 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(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) { - recipientKey, err := crypto.GenerateECDSAKey() - require.NoError(t, err) - - 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, 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, recipientKey, types.ZeroAddress, big.NewInt(0)) - require.NoError(t, txn.Wait()) - require.True(t, txn.Succeed()) - - 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(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(recipient, ethgo.BlockNumber(block.Number)) - require.NoError(t, err) - }) - - t.Run("eth_getStorageAt", func(t *testing.T) { - key1, err := crypto.GenerateECDSAKey() - require.NoError(t, err) - - txn := cluster.Transfer(t, senderKey, key1.Address(), one) - require.NoError(t, txn.Wait()) - require.True(t, txn.Succeed()) - - txn = cluster.Deploy(t, senderKey, contractsapi.TestSimple.Bytecode) - require.NoError(t, txn.Wait()) - require.True(t, txn.Succeed()) - - target := txn.Receipt().ContractAddress - - resp, err := client.GetStorageAt(target, ethgo.Hash{}, ethgo.Latest) - require.NoError(t, err) - require.Equal(t, "0x0000000000000000000000000000000000000000000000000000000000000000", resp.String()) - - setValueFn := contractsapi.TestSimple.Abi.GetMethod("setValue") - - newVal := big.NewInt(1) - - input, err := setValueFn.Encode([]interface{}{newVal}) - require.NoError(t, err) - - 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()) - - resp, err = client.GetStorageAt(target, ethgo.Hash{}, ethgo.Latest) - require.NoError(t, err) - require.Equal(t, "0x0000000000000000000000000000000000000000000000000000000000000001", resp.String()) - }) - - t.Run("eth_getCode", func(t *testing.T) { - // we use a predefined private key so that the deployed contract address is deterministic. - // 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 := crypto.NewECDSAKeyFromRawPrivECDSA(priv) - require.NoError(t, err) - - // fund the account so that it can deploy a contract - txn := cluster.Transfer(t, senderKey, key1.Address(), ethgo.Ether(1)) - require.NoError(t, txn.Wait()) - require.True(t, txn.Succeed()) - - codeAddr := ethgo.HexToAddress("0xDBfca0c43cA12759256a7Dd587Dc4c6EEC1D89A5") - - // Test. We get empty code from an empty contract - code, err := client.GetCode(codeAddr, ethgo.Latest) - require.NoError(t, err) - require.Equal(t, code, "0x") - - txn = cluster.Deploy(t, key1, contractsapi.TestSimple.Bytecode) - require.NoError(t, txn.Wait()) - require.True(t, txn.Succeed()) - - receipt := txn.Receipt() - - // Test. The deployed address is the one expected - require.Equal(t, codeAddr, receipt.ContractAddress) - - // Test. We can retrieve the code by address on latest, block number and block hash - cases := []ethgo.BlockNumberOrHash{ - ethgo.Latest, - ethgo.BlockNumber(receipt.BlockNumber), - } - for _, c := range cases { - code, err = client.GetCode(codeAddr, c) - require.NoError(t, err) - require.NotEqual(t, code, "0x") - } - - // Test. We can query in past state (when the code was empty) - code, err = client.GetCode(codeAddr, ethgo.BlockNumber(receipt.BlockNumber-1)) - require.NoError(t, err) - require.Equal(t, code, "0x") - - // Test. Query by pending should default to latest - code, err = client.GetCode(codeAddr, ethgo.Pending) - require.NoError(t, err) - require.NotEqual(t, code, "0x") - }) - - t.Run("eth_getBlockByHash", func(t *testing.T) { - key1, err := crypto.GenerateECDSAKey() - require.NoError(t, err) - txn := cluster.Transfer(t, senderKey, key1.Address(), one) - require.NoError(t, txn.Wait()) - require.True(t, txn.Succeed()) - txReceipt := txn.Receipt() - - block, err := client.GetBlockByHash(txReceipt.BlockHash, false) - require.NoError(t, err) - require.Equal(t, txReceipt.BlockNumber, block.Number) - require.Equal(t, txReceipt.BlockHash, block.Hash) - }) - - t.Run("eth_getBlockByNumber", func(t *testing.T) { - key1, err := crypto.GenerateECDSAKey() - require.NoError(t, err) - txn := cluster.Transfer(t, senderKey, key1.Address(), one) - require.NoError(t, txn.Wait()) - require.True(t, txn.Succeed()) - txReceipt := txn.Receipt() - - block, err := client.GetBlockByNumber(ethgo.BlockNumber(txReceipt.BlockNumber), false) - require.NoError(t, err) - require.Equal(t, txReceipt.BlockNumber, block.Number) - require.Equal(t, txReceipt.BlockHash, block.Hash) - }) - - t.Run("eth_getTransactionReceipt", func(t *testing.T) { - key1, err := crypto.GenerateECDSAKey() - require.NoError(t, err) - txn := cluster.Transfer(t, senderKey, key1.Address(), one) - require.NoError(t, txn.Wait()) - require.True(t, txn.Succeed()) - - // Test. We cannot retrieve a receipt of an empty hash - emptyReceipt, err := client.GetTransactionReceipt(ethgo.ZeroHash) - require.NoError(t, err) // Note that ethgo does not return an error when the item does not exists - require.Nil(t, emptyReceipt) - - // Test. We can retrieve the receipt by the hash - receipt, err := client.GetTransactionReceipt(txn.Receipt().TransactionHash) - require.NoError(t, err) - - // Test. The populated fields match with the block - block, err := client.GetBlockByHash(receipt.BlockHash, false) - require.NoError(t, err) - - require.Equal(t, receipt.TransactionHash, txn.Receipt().TransactionHash) - require.Equal(t, receipt.BlockNumber, block.Number) - require.Equal(t, receipt.BlockHash, block.Hash) - - // Test. The receipt of a deployed contract has the 'ContractAddress' field. - txn = cluster.Deploy(t, senderKey, contractsapi.TestSimple.Bytecode) - require.NoError(t, txn.Wait()) - require.True(t, txn.Succeed()) - - require.NotEqual(t, txn.Receipt().ContractAddress, ethgo.ZeroAddress) - }) - - t.Run("eth_getTransactionByHash", func(t *testing.T) { - key1, err := crypto.GenerateECDSAKey() - require.NoError(t, err) - - // Test. We should be able to query the transaction by its hash - txn := cluster.Transfer(t, senderKey, key1.Address(), one) - require.NoError(t, txn.Wait()) - require.True(t, txn.Succeed()) - - ethTxn, err := client.GetTransactionByHash(txn.Receipt().TransactionHash) - require.NoError(t, err) - - // Test. The dynamic 'from' field is populated - require.NotEqual(t, ethTxn.From, ethgo.ZeroAddress) - }) - - t.Run("debug_traceTransaction", func(t *testing.T) { - key1, err := crypto.GenerateECDSAKey() - require.NoError(t, err) - - // Test. We should be able to query the transaction by its hash - txn := cluster.Transfer(t, senderKey, key1.Address(), one) - require.NoError(t, txn.Wait()) - require.True(t, txn.Succeed()) - - txReceipt := txn.Receipt() - - // Use a wrapper function from "jsonrpc" package when the config is introduced. - trace, err := debug.TraceTransaction(txReceipt.TransactionHash, jsonrpc.TraceTransactionOptions{}) - require.NoError(t, err) - require.Equal(t, txReceipt.GasUsed, trace.Gas) - }) -} - -func TestE2E_JsonRPC_NewEthClient(t *testing.T) { const epochSize = uint64(5) preminedAcct, err := crypto.GenerateECDSAKey() @@ -512,9 +102,9 @@ func TestE2E_JsonRPC_NewEthClient(t *testing.T) { require.NoError(t, deployTxn.Wait()) require.True(t, deployTxn.Succeed()) - target := deployTxn.Receipt().ContractAddress + target := types.Address(deployTxn.Receipt().ContractAddress) - code, err := newEthClient.GetCode(types.Address(target), bladeRPC.LatestBlockNumberOrHash) + code, err := newEthClient.GetCode(target, bladeRPC.LatestBlockNumberOrHash) require.NoError(t, err) require.NotEmpty(t, code) }) @@ -548,7 +138,7 @@ func TestE2E_JsonRPC_NewEthClient(t *testing.T) { require.NoError(t, txn.Wait()) require.True(t, txn.Succeed()) - 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, "0x0000000000000000000000000000000000000000000000000000000000000001", resp.String()) }) @@ -566,7 +156,7 @@ func TestE2E_JsonRPC_NewEthClient(t *testing.T) { receipt, err := newEthClient.GetTransactionReceipt(ethTxn.Hash()) require.NoError(t, err) require.NotNil(t, receipt) - require.Equal(t, ethTxn.Hash(), receipt.TxHash) + require.Equal(t, ethTxn.Hash(), receipt.TransactionHash) }) t.Run("eth_getTransactionCount", func(t *testing.T) { @@ -607,7 +197,6 @@ func TestE2E_JsonRPC_NewEthClient(t *testing.T) { require.True(t, deployTxn.Succeed()) target := types.Address(deployTxn.Receipt().ContractAddress) - input := contractsapi.TestSimple.Abi.GetMethod("getValue").ID() estimatedGas, err := newEthClient.EstimateGas(&bladeRPC.CallMsg{ @@ -631,7 +220,6 @@ func TestE2E_JsonRPC_NewEthClient(t *testing.T) { require.True(t, deployTxn.Succeed()) target := types.Address(deployTxn.Receipt().ContractAddress) - input := contractsapi.TestSimple.Abi.GetMethod("getValue").ID() acctZeroBalance, err := crypto.GenerateECDSAKey() diff --git a/e2e-polybft/e2e/migration_test.go b/e2e-polybft/e2e/migration_test.go index c86cd23a55..2d33a164bc 100644 --- a/e2e-polybft/e2e/migration_test.go +++ b/e2e-polybft/e2e/migration_test.go @@ -17,6 +17,7 @@ import ( frameworkpolybft "github.com/0xPolygon/polygon-edge/e2e-polybft/framework" "github.com/0xPolygon/polygon-edge/e2e/framework" "github.com/0xPolygon/polygon-edge/helper/common" + "github.com/0xPolygon/polygon-edge/jsonrpc" itrie "github.com/0xPolygon/polygon-edge/state/immutable-trie" "github.com/0xPolygon/polygon-edge/txrelayer" "github.com/0xPolygon/polygon-edge/types" @@ -24,9 +25,9 @@ import ( func TestE2E_Migration(t *testing.T) { userKey, _ := crypto.GenerateECDSAKey() - userAddr := ethgo.Address(userKey.Address()) + userAddr := userKey.Address() userKey2, _ := crypto.GenerateECDSAKey() - userAddr2 := ethgo.Address(userKey2.Address()) + userAddr2 := userKey2.Address() initialBalance := ethgo.Ether(10) srvs := framework.NewTestServers(t, 1, func(config *framework.TestServerConfig) { @@ -41,17 +42,11 @@ func TestE2E_Migration(t *testing.T) { rpcClient := srv.JSONRPC() // Fetch the balances before sending - balanceSender, err := rpcClient.Eth().GetBalance( - userAddr, - ethgo.Latest, - ) + balanceSender, err := rpcClient.GetBalance(userAddr, jsonrpc.LatestBlockNumberOrHash) require.NoError(t, err) require.Equal(t, balanceSender.Cmp(initialBalance), 0) - balanceReceiver, err := rpcClient.Eth().GetBalance( - userAddr2, - ethgo.Latest, - ) + balanceReceiver, err := rpcClient.GetBalance(userAddr2, jsonrpc.LatestBlockNumberOrHash) require.NoError(t, err) if balanceReceiver.Uint64() != 0 { @@ -101,25 +96,19 @@ func TestE2E_Migration(t *testing.T) { require.Equal(t, uint64(types.ReceiptSuccess), initReceipt.Status) // Fetch the balances after sending - balanceSender, err = rpcClient.Eth().GetBalance( - userAddr, - ethgo.Latest, - ) + balanceSender, err = rpcClient.GetBalance(userAddr, jsonrpc.LatestBlockNumberOrHash) require.NoError(t, err) - balanceReceiver, err = rpcClient.Eth().GetBalance( - userAddr2, - ethgo.Latest, - ) + balanceReceiver, err = rpcClient.GetBalance(userAddr2, jsonrpc.LatestBlockNumberOrHash) require.NoError(t, err) require.Equal(t, sendAmount, balanceReceiver) - block, err := rpcClient.Eth().GetBlockByNumber(ethgo.Latest, true) + block, err := rpcClient.GetBlockByNumber(jsonrpc.LatestBlockNumber, true) if err != nil { t.Fatal(err) } - stateRoot := block.StateRoot + stateRoot := block.Header.StateRoot path := filepath.Join(srvs[0].Config.RootDir, "trie") srvs[0].Stop() @@ -131,7 +120,7 @@ func TestE2E_Migration(t *testing.T) { err = frameworkpolybft.RunEdgeCommand([]string{ "regenesis", - "--stateRoot", block.StateRoot.String(), + "--stateRoot", block.Header.StateRoot.String(), "--source-path", path, "--target-path", tmpDir, }, os.Stdout) @@ -146,7 +135,7 @@ func TestE2E_Migration(t *testing.T) { stateStorageNew := itrie.NewKV(db) - copiedStateRoot, err := itrie.HashChecker(block.StateRoot.Bytes(), stateStorageNew) + copiedStateRoot, err := itrie.HashChecker(block.Header.StateRoot.Bytes(), stateStorageNew) if err != nil { t.Fatal(err) } @@ -168,12 +157,12 @@ func TestE2E_Migration(t *testing.T) { cluster.WaitForReady(t) - senderBalanceAfterMigration, err := cluster.Servers[0].JSONRPC().Eth().GetBalance(userAddr, ethgo.Latest) + senderBalanceAfterMigration, err := cluster.Servers[0].JSONRPC().GetBalance(userAddr, jsonrpc.LatestBlockNumberOrHash) if err != nil { t.Fatal(err) } - receiverBalanceAfterMigration, err := cluster.Servers[0].JSONRPC().Eth().GetBalance(userAddr2, ethgo.Latest) + receiverBalanceAfterMigration, err := cluster.Servers[0].JSONRPC().GetBalance(userAddr2, jsonrpc.LatestBlockNumberOrHash) if err != nil { t.Fatal(err) } @@ -181,7 +170,7 @@ func TestE2E_Migration(t *testing.T) { require.Equal(t, balanceSender, senderBalanceAfterMigration) require.Equal(t, balanceReceiver, receiverBalanceAfterMigration) - deployedCode, err := cluster.Servers[0].JSONRPC().Eth().GetCode(deployedContractBalance, ethgo.Latest) + deployedCode, err := cluster.Servers[0].JSONRPC().GetCode(types.Address(deployedContractBalance), jsonrpc.LatestBlockNumberOrHash) if err != nil { t.Fatal(err) } diff --git a/e2e-polybft/e2e/txpool_test.go b/e2e-polybft/e2e/txpool_test.go index a636f3b855..f0acabaa04 100644 --- a/e2e-polybft/e2e/txpool_test.go +++ b/e2e-polybft/e2e/txpool_test.go @@ -6,10 +6,10 @@ import ( "testing" "time" + "github.com/0xPolygon/polygon-edge/jsonrpc" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/umbracle/ethgo" - "github.com/umbracle/ethgo/jsonrpc" "github.com/0xPolygon/polygon-edge/consensus/polybft" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi" @@ -32,25 +32,25 @@ func TestE2E_TxPool_Transfer(t *testing.T) { cluster.WaitForReady(t) - client := cluster.Servers[0].JSONRPC().Eth() + client := cluster.Servers[0].JSONRPC() sendAmount := 1 num := 20 - receivers := []ethgo.Address{} + receivers := []types.Address{} for i := 0; i < num; i++ { key, err := crypto.GenerateECDSAKey() require.NoError(t, err) - receivers = append(receivers, ethgo.Address(key.Address())) + receivers = append(receivers, key.Address()) } var wg sync.WaitGroup for i := 0; i < num; i++ { wg.Add(1) - go func(i int, to ethgo.Address) { + go func(i int, to types.Address) { defer wg.Done() var txData types.TxData @@ -87,7 +87,7 @@ func TestE2E_TxPool_Transfer(t *testing.T) { err = cluster.WaitUntil(2*time.Minute, 2*time.Second, func() bool { for _, receiver := range receivers { - balance, err := client.GetBalance(receiver, ethgo.Latest) + balance, err := client.GetBalance(receiver, jsonrpc.LatestBlockNumberOrHash) if err != nil { return true } @@ -116,11 +116,11 @@ func TestE2E_TxPool_Transfer_Linear(t *testing.T) { cluster.WaitForReady(t) - client := cluster.Servers[0].JSONRPC().Eth() + client := cluster.Servers[0].JSONRPC() - waitUntilBalancesChanged := func(acct ethgo.Address) error { + waitUntilBalancesChanged := func(acct types.Address) error { err := cluster.WaitUntil(30*time.Second, 2*time.Second, func() bool { - balance, err := client.GetBalance(acct, ethgo.Latest) + balance, err := client.GetBalance(acct, jsonrpc.LatestBlockNumberOrHash) if err != nil { return true } @@ -183,12 +183,12 @@ func TestE2E_TxPool_Transfer_Linear(t *testing.T) { sendTransaction(t, client, receivers[i-1], txn) - err := waitUntilBalancesChanged(ethgo.Address(receivers[i].Address())) + err := waitUntilBalancesChanged(receivers[i].Address()) require.NoError(t, err) } for i := 1; i < num; i++ { - balance, err := client.GetBalance(ethgo.Address(receivers[i].Address()), ethgo.Latest) + balance, err := client.GetBalance(receivers[i].Address(), jsonrpc.LatestBlockNumberOrHash) require.NoError(t, err) require.Equal(t, uint64(sendAmount), balance.Uint64()) } @@ -256,7 +256,7 @@ func TestE2E_TxPool_BroadcastTransactions(t *testing.T) { // Wait until the cluster is up and running cluster.WaitForReady(t) - client := cluster.Servers[0].JSONRPC().Eth() + client := cluster.Servers[0].JSONRPC() sentAmount := new(big.Int) nonce := uint64(0) @@ -293,7 +293,7 @@ func TestE2E_TxPool_BroadcastTransactions(t *testing.T) { // 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(ethgo.Address(recipient), time.Second*10) + balance, err := srv.WaitForNonZeroBalance(recipient, time.Second*10) assert.NoError(t, err) if balance != nil && balance.BitLen() > 0 { assert.Equal(t, sentAmount, balance) @@ -308,7 +308,7 @@ 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 crypto.Key, txn *types.Transaction) { +func sendTransaction(t *testing.T, client *jsonrpc.EthClient, sender crypto.Key, txn *types.Transaction) { t.Helper() chainID, err := client.ChainID() diff --git a/e2e-polybft/framework/test-cluster.go b/e2e-polybft/framework/test-cluster.go index c64cd08edb..7a4916a615 100644 --- a/e2e-polybft/framework/test-cluster.go +++ b/e2e-polybft/framework/test-cluster.go @@ -23,12 +23,12 @@ import ( "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/jsonrpc" "github.com/0xPolygon/polygon-edge/txrelayer" "github.com/0xPolygon/polygon-edge/types" "github.com/stretchr/testify/require" "github.com/umbracle/ethgo" "github.com/umbracle/ethgo/abi" - "github.com/umbracle/ethgo/jsonrpc" ) const ( @@ -863,7 +863,7 @@ func (c *TestCluster) Stats(t *testing.T) { continue } - num, err := i.JSONRPC().Eth().BlockNumber() + num, err := i.JSONRPC().BlockNumber() t.Log("Stats node", index, "err", err, "block", num, "validator", i.config.Validator) } } @@ -911,7 +911,7 @@ func (c *TestCluster) WaitForBlock(n uint64, timeout time.Duration) error { continue } - num, err := i.JSONRPC().Eth().BlockNumber() + num, err := i.JSONRPC().BlockNumber() if err != nil || num < n { ok = false @@ -1000,13 +1000,13 @@ func (c *TestCluster) InitSecrets(prefix string, count int) ([]types.Address, er return result, nil } -func (c *TestCluster) ExistsCode(t *testing.T, addr ethgo.Address) bool { +func (c *TestCluster) ExistsCode(t *testing.T, addr types.Address) bool { t.Helper() - client, err := jsonrpc.NewClient(c.Servers[0].JSONRPCAddr()) + client, err := jsonrpc.NewEthClient(c.Servers[0].JSONRPCAddr()) require.NoError(t, err) - code, err := client.Eth().GetCode(addr, ethgo.Latest) + code, err := client.GetCode(addr, jsonrpc.LatestBlockNumberOrHash) if err != nil { return false } @@ -1018,19 +1018,17 @@ func (c *TestCluster) Call(t *testing.T, to types.Address, method *abi.Method, args ...interface{}) map[string]interface{} { t.Helper() - client, err := jsonrpc.NewClient(c.Servers[0].JSONRPCAddr()) + client, err := jsonrpc.NewEthClient(c.Servers[0].JSONRPCAddr()) require.NoError(t, err) input, err := method.Encode(args) require.NoError(t, err) - toAddr := ethgo.Address(to) - - msg := ðgo.CallMsg{ - To: &toAddr, + msg := &jsonrpc.CallMsg{ + To: &to, Data: input, } - resp, err := client.Eth().Call(msg, ethgo.Latest) + resp, err := client.Call(msg, jsonrpc.LatestBlockNumber, nil) require.NoError(t, err) data, err := hex.DecodeString(resp[2:]) @@ -1090,19 +1088,19 @@ func (c *TestCluster) SendTxn(t *testing.T, sender *crypto.ECDSAKey, txn *types. c.sendTxnLock.Lock() defer c.sendTxnLock.Unlock() - client, err := jsonrpc.NewClient(c.Servers[0].JSONRPCAddr()) + client, err := jsonrpc.NewEthClient(c.Servers[0].JSONRPCAddr()) require.NoError(t, err) // initialize transaction values if not set if txn.Nonce() == 0 { - nonce, err := client.Eth().GetNonce(ethgo.Address(sender.Address()), ethgo.Latest) + nonce, err := client.GetNonce(sender.Address(), jsonrpc.LatestBlockNumberOrHash) require.NoError(t, err) txn.SetNonce(nonce) } if txn.GasPrice() == nil || txn.GasPrice() == big.NewInt(0) { - gasPrice, err := client.Eth().GasPrice() + gasPrice, err := client.GasPrice() require.NoError(t, err) txn.SetGasPrice(new(big.Int).SetUint64(gasPrice)) @@ -1111,7 +1109,7 @@ func (c *TestCluster) SendTxn(t *testing.T, sender *crypto.ECDSAKey, txn *types. if txn.Gas() == 0 { callMsg := txrelayer.ConvertTxnToCallMsg(txn) - gasLimit, err := client.Eth().EstimateGas(callMsg) + gasLimit, err := client.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) @@ -1121,7 +1119,7 @@ func (c *TestCluster) SendTxn(t *testing.T, sender *crypto.ECDSAKey, txn *types. } } - chainID, err := client.Eth().ChainID() + chainID, err := client.ChainID() require.NoError(t, err) signer := crypto.NewLondonSigner(chainID.Uint64()) @@ -1133,19 +1131,19 @@ func (c *TestCluster) SendTxn(t *testing.T, sender *crypto.ECDSAKey, txn *types. rlpTxn := signedTxn.MarshalRLPTo(nil) - hash, err := client.Eth().SendRawTransaction(rlpTxn) + hash, err := client.SendRawTransaction(rlpTxn) require.NoError(t, err) return &TestTxn{ - client: client.Eth(), + client: client, txn: txn, hash: hash, } } type TestTxn struct { - client *jsonrpc.Eth - hash ethgo.Hash + client *jsonrpc.EthClient + hash types.Hash txn *types.Transaction receipt *ethgo.Receipt } @@ -1162,18 +1160,18 @@ func (t *TestTxn) Receipt() *ethgo.Receipt { // Succeed returns whether the transaction succeed and it was not reverted func (t *TestTxn) Succeed() bool { - return t.receipt.Status == uint64(types.ReceiptSuccess) + return t.receipt != nil && t.receipt.Status == uint64(types.ReceiptSuccess) } // Failed returns whether the transaction failed func (t *TestTxn) Failed() bool { - return t.receipt.Status == uint64(types.ReceiptFailed) + return t.receipt == nil || t.receipt.Status == uint64(types.ReceiptFailed) } // 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.Failed() && t.txn.Gas() == t.receipt.GasUsed } // Wait waits for the transaction to be executed diff --git a/e2e-polybft/framework/test-server.go b/e2e-polybft/framework/test-server.go index 8f283b35d2..0934628d64 100644 --- a/e2e-polybft/framework/test-server.go +++ b/e2e-polybft/framework/test-server.go @@ -17,13 +17,13 @@ import ( "github.com/0xPolygon/polygon-edge/consensus/polybft" "github.com/0xPolygon/polygon-edge/consensus/polybft/validator" "github.com/0xPolygon/polygon-edge/consensus/polybft/wallet" + "github.com/0xPolygon/polygon-edge/jsonrpc" "github.com/0xPolygon/polygon-edge/server/proto" txpoolProto "github.com/0xPolygon/polygon-edge/txpool/proto" "github.com/0xPolygon/polygon-edge/types" "github.com/google/uuid" "github.com/stretchr/testify/require" "github.com/umbracle/ethgo" - "github.com/umbracle/ethgo/jsonrpc" "google.golang.org/grpc" ) @@ -78,8 +78,8 @@ func (t *TestServer) BridgeJSONRPCAddr() string { return t.config.BridgeJSONRPC } -func (t *TestServer) JSONRPC() *jsonrpc.Client { - clt, err := jsonrpc.NewClient(t.JSONRPCAddr()) +func (t *TestServer) JSONRPC() *jsonrpc.EthClient { + clt, err := jsonrpc.NewEthClient(t.JSONRPCAddr()) if err != nil { t.t.Fatal(err) } @@ -357,12 +357,12 @@ func (t *TestServer) HasValidatorSealed(firstBlock, lastBlock uint64, validators validatorAddr ethgo.Address) (bool, error) { rpcClient := t.JSONRPC() for i := firstBlock + 1; i <= lastBlock; i++ { - block, err := rpcClient.Eth().GetBlockByNumber(ethgo.BlockNumber(i), false) + block, err := rpcClient.GetBlockByNumber(jsonrpc.BlockNumber(i), false) if err != nil { return false, err } - extra, err := polybft.GetIbftExtra(block.ExtraData) + extra, err := polybft.GetIbftExtra(block.Header.ExtraData) if err != nil { return false, err } @@ -380,7 +380,7 @@ func (t *TestServer) HasValidatorSealed(firstBlock, lastBlock uint64, validators return false, nil } -func (t *TestServer) WaitForNonZeroBalance(address ethgo.Address, dur time.Duration) (*big.Int, error) { +func (t *TestServer) WaitForNonZeroBalance(address types.Address, dur time.Duration) (*big.Int, error) { timer := time.NewTimer(dur) defer timer.Stop() @@ -394,7 +394,7 @@ func (t *TestServer) WaitForNonZeroBalance(address ethgo.Address, dur time.Durat case <-timer.C: return nil, fmt.Errorf("timeout occurred while waiting for balance ") case <-ticker.C: - balance, err := rpcClient.Eth().GetBalance(address, ethgo.Latest) + balance, err := rpcClient.GetBalance(address, jsonrpc.LatestBlockNumberOrHash) if err != nil { return nil, fmt.Errorf("error getting balance") } diff --git a/e2e-polybft/property/property_test.go b/e2e-polybft/property/property_test.go index 28c518c7e1..66f7d7921b 100644 --- a/e2e-polybft/property/property_test.go +++ b/e2e-polybft/property/property_test.go @@ -84,7 +84,7 @@ func TestProperty_DropValidators(t *testing.T) { // stop first validator, block production should continue cluster.Servers[0].Stop() activeValidator := cluster.Servers[numNodes-1] - currentBlock, err := activeValidator.JSONRPC().Eth().BlockNumber() + currentBlock, err := activeValidator.JSONRPC().BlockNumber() require.NoError(t, err) require.NoError(t, cluster.WaitForBlock(currentBlock+1, 2*blockTime)) @@ -107,11 +107,11 @@ func TestProperty_DropValidators(t *testing.T) { wg.Wait() // check that block production is stoped - currentBlock, err = activeValidator.JSONRPC().Eth().BlockNumber() + currentBlock, err = activeValidator.JSONRPC().BlockNumber() require.NoError(t, err) oldBlockNumber := currentBlock time.Sleep(2 * blockTime) - currentBlock, err = activeValidator.JSONRPC().Eth().BlockNumber() + currentBlock, err = activeValidator.JSONRPC().BlockNumber() require.NoError(t, err) require.Equal(t, oldBlockNumber, currentBlock) diff --git a/e2e/framework/helper.go b/e2e/framework/helper.go index d55a33a79c..671f5de17d 100644 --- a/e2e/framework/helper.go +++ b/e2e/framework/helper.go @@ -211,7 +211,7 @@ func WaitUntilTxPoolFilled( // WaitUntilBlockMined waits until server mined block with bigger height than given height // otherwise returns timeout func WaitUntilBlockMined(ctx context.Context, srv *TestServer, desiredHeight uint64) (uint64, error) { - clt := srv.JSONRPC().Eth() + clt := srv.JSONRPC() res, err := tests.RetryUntilTimeout(ctx, func() (interface{}, bool) { height, err := clt.BlockNumber() if err == nil && height >= desiredHeight { diff --git a/e2e/framework/testserver.go b/e2e/framework/testserver.go index 450ce6a6b0..1e884c8cae 100644 --- a/e2e/framework/testserver.go +++ b/e2e/framework/testserver.go @@ -20,9 +20,8 @@ import ( "testing" "time" + "github.com/0xPolygon/polygon-edge/jsonrpc" "github.com/umbracle/ethgo" - "github.com/umbracle/ethgo/jsonrpc" - "github.com/umbracle/ethgo/wallet" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" empty "google.golang.org/protobuf/types/known/emptypb" @@ -104,8 +103,8 @@ func (t *TestServer) WSJSONRPCURL() string { return fmt.Sprintf("ws://%s/ws", t.JSONRPCAddr()) } -func (t *TestServer) JSONRPC() *jsonrpc.Client { - clt, err := jsonrpc.NewClient(t.HTTPJSONRPCURL()) +func (t *TestServer) JSONRPC() *jsonrpc.EthClient { + clt, err := jsonrpc.NewEthClient(t.HTTPJSONRPCURL()) if err != nil { t.t.Fatal(err) } @@ -156,7 +155,7 @@ func (t *TestServer) Stop() { } func (t *TestServer) GetLatestBlockHeight() (uint64, error) { - return t.JSONRPC().Eth().BlockNumber() + return t.JSONRPC().BlockNumber() } type InitIBFTResult struct { @@ -276,7 +275,7 @@ func (t *TestServer) Start(ctx context.Context) error { } // query the chain id - chainID, err := t.JSONRPC().Eth().ChainID() + chainID, err := t.JSONRPC().ChainID() if err != nil { return err } @@ -299,15 +298,15 @@ func (t *TestServer) DeployContract( ctx context.Context, binary string, privateKey *ecdsa.PrivateKey, -) (ethgo.Address, error) { +) (types.Address, error) { buf, err := hex.DecodeString(binary) if err != nil { - return ethgo.Address{}, err + return types.ZeroAddress, err } sender, err := crypto.GetAddressFromKey(privateKey) if err != nil { - return ethgo.ZeroAddress, fmt.Errorf("unable to extract key, %w", err) + return types.ZeroAddress, fmt.Errorf("unable to extract key, %w", err) } receipt, err := t.SendRawTx(ctx, &PreparedTransaction{ @@ -317,10 +316,10 @@ func (t *TestServer) DeployContract( Input: buf, }, privateKey) if err != nil { - return ethgo.Address{}, err + return types.ZeroAddress, err } - return receipt.ContractAddress, nil + return types.Address(receipt.ContractAddress), nil } const ( @@ -337,176 +336,6 @@ type PreparedTransaction struct { Input []byte } -type Txn struct { - key *wallet.Key - client *jsonrpc.Eth - hash *ethgo.Hash - receipt *ethgo.Receipt - raw *ethgo.Transaction - chainID *big.Int - - sendErr error - waitErr error -} - -func (t *Txn) Deploy(input []byte) *Txn { - t.raw.Input = input - - return t -} - -func (t *Txn) Transfer(to ethgo.Address, value *big.Int) *Txn { - t.raw.To = &to - t.raw.Value = value - t.raw.GasPrice = ethgo.Gwei(2).Uint64() - - return t -} - -func (t *Txn) Value(value *big.Int) *Txn { - t.raw.Value = value - - return t -} - -func (t *Txn) To(to ethgo.Address) *Txn { - t.raw.To = &to - - return t -} - -func (t *Txn) GasLimit(gas uint64) *Txn { - t.raw.Gas = gas - - return t -} - -func (t *Txn) Nonce(nonce uint64) *Txn { - t.raw.Nonce = nonce - - return t -} - -func (t *Txn) sendImpl() error { - // populate default values - if t.raw.Gas == 0 { - t.raw.Gas = 1048576 - } - - if t.raw.GasPrice == 0 { - gasPrice, err := t.client.GasPrice() - if err != nil { - return fmt.Errorf("failed to get gas price: %w", err) - } - - t.raw.GasPrice = gasPrice - } - - if t.raw.Nonce == 0 { - nextNonce, err := t.client.GetNonce(t.key.Address(), ethgo.Latest) - if err != nil { - return fmt.Errorf("failed to get nonce: %w", err) - } - - t.raw.Nonce = nextNonce - } - - signer := wallet.NewEIP155Signer(t.chainID.Uint64()) - - signedTxn, err := signer.SignTx(t.raw, t.key) - if err != nil { - return err - } - - data, _ := signedTxn.MarshalRLPTo(nil) - - txHash, err := t.client.SendRawTransaction(data) - if err != nil { - return fmt.Errorf("failed to send transaction: %w", err) - } - - t.hash = &txHash - - return nil -} - -func (t *Txn) Send() (*Txn, error) { - if t.hash != nil { - return nil, errors.New("txn already sent") - } - - t.sendErr = t.sendImpl() - - return t, nil -} - -func (t *Txn) Receipt() *ethgo.Receipt { - return t.receipt -} - -//nolint:thelper -func (t *Txn) NoFail(tt *testing.T) { - t.Wait() - - if t.sendErr != nil { - tt.Fatal(t.sendErr) - } - - if t.waitErr != nil { - tt.Fatal(t.waitErr) - } - - if t.receipt.Status != 1 { - tt.Fatal("txn failed with status 0") - } -} - -func (t *Txn) Complete() bool { - if t.sendErr != nil { - // txn failed during sending - return true - } - - if t.waitErr != nil { - // txn failed during waiting - return true - } - - if t.receipt != nil { - // txn was mined - return true - } - - return false -} - -func (t *Txn) Wait() { - if t.Complete() { - return - } - - ctx, cancelFn := context.WithTimeout(context.Background(), DefaultTimeout) - defer cancelFn() - - receipt, err := tests.WaitForReceipt(ctx, t.client, *t.hash) - if err != nil { - t.waitErr = err - } else { - t.receipt = receipt - } -} - -func (t *TestServer) Txn(key *wallet.Key) *Txn { - tt := &Txn{ - key: key, - client: t.JSONRPC().Eth(), - chainID: t.chainID, - raw: ðgo.Transaction{}, - } - - return tt -} - // SendRawTx signs the transaction with the provided private key, executes it, and returns the receipt func (t *TestServer) SendRawTx( ctx context.Context, @@ -515,7 +344,7 @@ func (t *TestServer) SendRawTx( ) (*ethgo.Receipt, error) { client := t.JSONRPC() - nextNonce, err := client.Eth().GetNonce(ethgo.Address(tx.From), ethgo.Latest) + nextNonce, err := client.GetNonce(tx.From, jsonrpc.LatestBlockNumberOrHash) if err != nil { return nil, err } @@ -533,15 +362,15 @@ func (t *TestServer) SendRawTx( return nil, err } - txHash, err := client.Eth().SendRawTransaction(signedTx.MarshalRLP()) + txHash, err := client.SendRawTransaction(signedTx.MarshalRLP()) if err != nil { return nil, err } - return tests.WaitForReceipt(ctx, t.JSONRPC().Eth(), txHash) + return tests.WaitForReceipt(ctx, t.JSONRPC(), txHash) } -func (t *TestServer) WaitForReceipt(ctx context.Context, hash ethgo.Hash) (*ethgo.Receipt, error) { +func (t *TestServer) WaitForReceipt(ctx context.Context, hash types.Hash) (*ethgo.Receipt, error) { client := t.JSONRPC() type result struct { @@ -550,7 +379,7 @@ func (t *TestServer) WaitForReceipt(ctx context.Context, hash ethgo.Hash) (*ethg } res, err := tests.RetryUntilTimeout(ctx, func() (interface{}, bool) { - receipt, err := client.Eth().GetTransactionReceipt(hash) + receipt, err := client.GetTransactionReceipt(hash) if err != nil && err.Error() != "not found" { return result{receipt, err}, false @@ -576,7 +405,7 @@ func (t *TestServer) WaitForReceipt(ctx context.Context, hash ethgo.Hash) (*ethg // GetGasTotal waits for the total gas used sum for the passed in // transactions -func (t *TestServer) GetGasTotal(txHashes []ethgo.Hash) uint64 { +func (t *TestServer) GetGasTotal(txHashes []types.Hash) uint64 { t.t.Helper() var ( @@ -596,13 +425,13 @@ func (t *TestServer) GetGasTotal(txHashes []ethgo.Hash) uint64 { for _, txHash := range txHashes { wg.Add(1) - go func(txHash ethgo.Hash) { + go func(txHash types.Hash) { defer wg.Done() ctx, cancelFn := context.WithTimeout(context.Background(), DefaultTimeout) defer cancelFn() - receipt, receiptErr := tests.WaitForReceipt(ctx, t.JSONRPC().Eth(), txHash) + receipt, receiptErr := tests.WaitForReceipt(ctx, t.JSONRPC(), txHash) if receiptErr != nil { appendReceiptErr(fmt.Errorf("unable to wait for receipt, %w", receiptErr)) diff --git a/e2e/transaction_test.go b/e2e/transaction_test.go index aec654d677..5d82a5415f 100644 --- a/e2e/transaction_test.go +++ b/e2e/transaction_test.go @@ -11,6 +11,7 @@ import ( "github.com/0xPolygon/polygon-edge/e2e/framework" "github.com/0xPolygon/polygon-edge/helper/tests" + "github.com/0xPolygon/polygon-edge/jsonrpc" "github.com/0xPolygon/polygon-edge/types" ) @@ -59,7 +60,7 @@ func TestPreminedBalance(t *testing.T) { for _, testCase := range testTable { t.Run(testCase.name, func(t *testing.T) { - balance, err := rpcClient.Eth().GetBalance(ethgo.Address(testCase.address), ethgo.Latest) + balance, err := rpcClient.GetBalance(testCase.address, jsonrpc.LatestBlockNumberOrHash) require.NoError(t, err) require.Equal(t, testCase.balance, balance) }) @@ -137,16 +138,10 @@ func TestEthTransfer(t *testing.T) { for _, testCase := range testTable { t.Run(testCase.name, func(t *testing.T) { // Fetch the balances before sending - balanceSender, err := rpcClient.Eth().GetBalance( - ethgo.Address(testCase.sender), - ethgo.Latest, - ) + balanceSender, err := rpcClient.GetBalance(testCase.sender, jsonrpc.LatestBlockNumberOrHash) require.NoError(t, err) - balanceReceiver, err := rpcClient.Eth().GetBalance( - ethgo.Address(testCase.recipient), - ethgo.Latest, - ) + balanceReceiver, err := rpcClient.GetBalance(testCase.recipient, jsonrpc.LatestBlockNumberOrHash) require.NoError(t, err) // Set the preSend balances @@ -176,16 +171,10 @@ func TestEthTransfer(t *testing.T) { } // Fetch the balances after sending - balanceSender, err = rpcClient.Eth().GetBalance( - ethgo.Address(testCase.sender), - ethgo.Latest, - ) + balanceSender, err = rpcClient.GetBalance(testCase.sender, jsonrpc.LatestBlockNumberOrHash) require.NoError(t, err) - balanceReceiver, err = rpcClient.Eth().GetBalance( - ethgo.Address(testCase.recipient), - ethgo.Latest, - ) + balanceReceiver, err = rpcClient.GetBalance(testCase.recipient, jsonrpc.LatestBlockNumberOrHash) require.NoError(t, err) expectedSenderBalance := previousSenderBalance diff --git a/e2e/txpool_test.go b/e2e/txpool_test.go index 1c744011bd..9374729769 100644 --- a/e2e/txpool_test.go +++ b/e2e/txpool_test.go @@ -9,6 +9,7 @@ import ( "time" "github.com/0xPolygon/polygon-edge/chain" + "github.com/0xPolygon/polygon-edge/jsonrpc" "github.com/stretchr/testify/require" @@ -190,7 +191,7 @@ func TestTxPool_ErrorCodes(t *testing.T) { defer waitCancelFn() convertedHash := types.StringToHash(addResponse.TxHash) - _, receiptErr := tests.WaitForReceipt(receiptCtx, srv.JSONRPC().Eth(), ethgo.Hash(convertedHash)) + _, receiptErr := tests.WaitForReceipt(receiptCtx, srv.JSONRPC(), convertedHash) if receiptErr != nil { t.Fatalf("Unable to get receipt, %v", receiptErr) @@ -280,7 +281,7 @@ func TestTxPool_RecoverableError(t *testing.T) { client := server.JSONRPC() operator := server.TxnPoolOperator() - hashes := make([]ethgo.Hash, 3) + hashes := make([]types.Hash, 3) for i, tx := range transactions { signedTx, err := signer.SignTx(tx, senderKey) @@ -294,39 +295,31 @@ func TestTxPool_RecoverableError(t *testing.T) { }) require.NoError(t, err, "Unable to send transaction, %v", err) - txHash := ethgo.Hash(types.StringToHash(response.TxHash)) - // save for later querying - hashes[i] = txHash + hashes[i] = types.StringToHash(response.TxHash) } ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second) defer cancel() // wait for the last tx to be included in a block - receipt, err := tests.WaitForReceipt(ctx, client.Eth(), hashes[2]) + receipt, err := tests.WaitForReceipt(ctx, client, hashes[2]) require.NoError(t, err) require.NotNil(t, receipt) // assert balance moved - balance, err := client.Eth().GetBalance(ethgo.Address(receiverAddress), ethgo.Latest) + balance, err := client.GetBalance(receiverAddress, jsonrpc.LatestBlockNumberOrHash) require.NoError(t, err, "failed to retrieve receiver account balance") require.Equal(t, framework.EthToWei(3).String(), balance.String()) // Query 1st and 2nd txs - firstTx, err := client.Eth().GetTransactionByHash(hashes[0]) + firstTx, err := client.GetTransactionByHash(hashes[0]) require.NoError(t, err) require.NotNil(t, firstTx) - secondTx, err := client.Eth().GetTransactionByHash(hashes[1]) + secondTx, err := client.GetTransactionByHash(hashes[1]) require.NoError(t, err) require.NotNil(t, secondTx) - - // first two are in one block - require.Equal(t, firstTx.BlockNumber, secondTx.BlockNumber) - - // last tx is included in next block - require.NotEqual(t, secondTx.BlockNumber, receipt.BlockNumber) } func TestTxPool_GetPendingTx(t *testing.T) { @@ -370,10 +363,10 @@ func TestTxPool_GetPendingTx(t *testing.T) { }) assert.NoError(t, err, "Unable to send transaction, %v", err) - txHash := ethgo.Hash(types.StringToHash(response.TxHash)) + txHash := types.StringToHash(response.TxHash) // Grab the pending transaction from the pool - tx, err := client.Eth().GetTransactionByHash(txHash) + tx, err := client.GetTransactionByHash(txHash) assert.NoError(t, err, "Unable to get transaction by hash, %v", err) assert.NotNil(t, tx) @@ -386,14 +379,14 @@ func TestTxPool_GetPendingTx(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - receipt, err := tests.WaitForReceipt(ctx, client.Eth(), txHash) + receipt, err := tests.WaitForReceipt(ctx, client, txHash) assert.NoError(t, err) assert.NotNil(t, receipt) assert.Equal(t, tx.TxnIndex, receipt.TransactionIndex) // fields should be updated - tx, err = client.Eth().GetTransactionByHash(txHash) + tx, err = client.GetTransactionByHash(txHash) assert.NoError(t, err, "Unable to get transaction by hash, %v", err) assert.NotNil(t, tx) diff --git a/gasprice/feehistory_test.go b/gasprice/feehistory_test.go index 68f2115168..2fc2005746 100644 --- a/gasprice/feehistory_test.go +++ b/gasprice/feehistory_test.go @@ -7,7 +7,6 @@ import ( "github.com/0xPolygon/polygon-edge/chain" "github.com/0xPolygon/polygon-edge/crypto" - "github.com/0xPolygon/polygon-edge/helper/tests" "github.com/0xPolygon/polygon-edge/types" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -184,7 +183,10 @@ func TestGasHelper_FeeHistory(t *testing.T) { backend := createTestBlocks(t, 10) rand.Seed(time.Now().UTC().UnixNano()) - senderKey, sender := tests.GenerateKeyAndAddr(t) + senderKey, err := crypto.GenerateECDSAPrivateKey() + require.NoError(t, err) + + sender := crypto.PubKeyToAddress(&senderKey.PublicKey) for _, b := range backend.blocksByNumber { signer := crypto.NewSigner(backend.Config().Forks.At(b.Number()), diff --git a/gasprice/gasprice_test.go b/gasprice/gasprice_test.go index aba8a0c274..2abd7c1be5 100644 --- a/gasprice/gasprice_test.go +++ b/gasprice/gasprice_test.go @@ -9,7 +9,6 @@ import ( "github.com/0xPolygon/polygon-edge/chain" "github.com/0xPolygon/polygon-edge/crypto" - "github.com/0xPolygon/polygon-edge/helper/tests" "github.com/0xPolygon/polygon-edge/types" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -74,7 +73,10 @@ func TestGasHelper_MaxPriorityFeePerGas(t *testing.T) { backend := createTestBlocks(t, 10) rand.Seed(time.Now().UTC().UnixNano()) - senderKey, sender := tests.GenerateKeyAndAddr(t) + senderKey, err := crypto.GenerateECDSAPrivateKey() + require.NoError(t, err) + + sender := crypto.PubKeyToAddress(&senderKey.PublicKey) for _, b := range backend.blocks { signer := crypto.NewSigner(backend.Config().Forks.At(b.Number()), @@ -217,7 +219,10 @@ func createTestTxs(t *testing.T, backend *backendMock, numOfTxsPerBlock, txCap i b.Transactions = make([]*types.Transaction, numOfTxsPerBlock) for i := 0; i < numOfTxsPerBlock; i++ { - senderKey, sender := tests.GenerateKeyAndAddr(t) + senderKey, err := crypto.GenerateECDSAPrivateKey() + require.NoError(t, err) + + sender := crypto.PubKeyToAddress(&senderKey.PublicKey) tx := types.NewTx(types.NewDynamicFeeTx( types.WithGasTipCap(ethgo.Gwei(uint64(rand.Intn(txCap)))), @@ -228,7 +233,7 @@ func createTestTxs(t *testing.T, backend *backendMock, numOfTxsPerBlock, txCap i types.WithTo(&types.ZeroAddress), )) - tx, err := signer.SignTx(tx, senderKey) + tx, err = signer.SignTx(tx, senderKey) require.NoError(t, err) b.Transactions[i] = tx diff --git a/helper/common/common.go b/helper/common/common.go index bd58bdaced..4400ac6e57 100644 --- a/helper/common/common.go +++ b/helper/common/common.go @@ -9,6 +9,7 @@ import ( "io/fs" "math" "math/big" + "net" "os" "os/signal" "os/user" @@ -415,3 +416,27 @@ func (f *UnsafePool[T]) Put(resetFunc func(T) T, obj T) { f.stack = append(f.stack, obj) } + +// GetFreePort asks the kernel for a free open port that is ready to use +func GetFreePort() (port int, err error) { + var addr *net.TCPAddr + + if addr, err = net.ResolveTCPAddr("tcp", "localhost:0"); err == nil { + var l *net.TCPListener + + if l, err = net.ListenTCP("tcp", addr); err == nil { + defer func(l *net.TCPListener) { + _ = l.Close() + }(l) + + netAddr, ok := l.Addr().(*net.TCPAddr) + if !ok { + return 0, errors.New("invalid type assert to TCPAddr") + } + + return netAddr.Port, nil + } + } + + return +} diff --git a/helper/tests/testing.go b/helper/tests/testing.go index 442e39c7c5..d9d1967770 100644 --- a/helper/tests/testing.go +++ b/helper/tests/testing.go @@ -6,7 +6,6 @@ import ( "errors" "fmt" "math/big" - "net" "testing" "time" @@ -17,10 +16,11 @@ import ( "github.com/umbracle/ethgo" "github.com/0xPolygon/polygon-edge/crypto" + "github.com/0xPolygon/polygon-edge/helper/common" + "github.com/0xPolygon/polygon-edge/jsonrpc" txpoolOp "github.com/0xPolygon/polygon-edge/txpool/proto" "github.com/0xPolygon/polygon-edge/types" "github.com/stretchr/testify/assert" - "github.com/umbracle/ethgo/jsonrpc" empty "google.golang.org/protobuf/types/known/emptypb" ) @@ -51,7 +51,7 @@ func GenerateTestMultiAddr(t *testing.T) multiaddr.Multiaddr { nodeID, err := peer.IDFromPrivateKey(priv) assert.NoError(t, err) - port, portErr := GetFreePort() + port, portErr := common.GetFreePort() if portErr != nil { t.Fatalf("Unable to fetch free port, %v", portErr) } @@ -130,8 +130,8 @@ func WaitUntilTxPoolEmpty( func WaitForNonce( ctx context.Context, - ethClient *jsonrpc.Eth, - addr ethgo.Address, + ethClient *jsonrpc.EthClient, + addr types.Address, expectedNonce uint64, ) ( interface{}, @@ -143,7 +143,7 @@ func WaitForNonce( } resObj, err := RetryUntilTimeout(ctx, func() (interface{}, bool) { - nonce, err := ethClient.GetNonce(addr, ethgo.Latest) + nonce, err := ethClient.GetNonce(addr, jsonrpc.LatestBlockNumberOrHash) if err != nil { // error -> stop retrying return result{nonce, err}, false @@ -171,7 +171,7 @@ func WaitForNonce( } // WaitForReceipt waits transaction receipt -func WaitForReceipt(ctx context.Context, client *jsonrpc.Eth, hash ethgo.Hash) (*ethgo.Receipt, error) { +func WaitForReceipt(ctx context.Context, client *jsonrpc.EthClient, hash types.Hash) (*ethgo.Receipt, error) { type result struct { receipt *ethgo.Receipt err error @@ -201,30 +201,6 @@ func WaitForReceipt(ctx context.Context, client *jsonrpc.Eth, hash ethgo.Hash) ( return data.receipt, data.err } -// GetFreePort asks the kernel for a free open port that is ready to use -func GetFreePort() (port int, err error) { - var addr *net.TCPAddr - - if addr, err = net.ResolveTCPAddr("tcp", "localhost:0"); err == nil { - var l *net.TCPListener - - if l, err = net.ListenTCP("tcp", addr); err == nil { - defer func(l *net.TCPListener) { - _ = l.Close() - }(l) - - netAddr, ok := l.Addr().(*net.TCPAddr) - if !ok { - return 0, errors.New("invalid type assert to TCPAddr") - } - - return netAddr.Port, nil - } - } - - return -} - type GenerateTxReqParams struct { Nonce uint64 ReferenceAddr types.Address diff --git a/jsonrpc/client.go b/jsonrpc/client.go index 6349745093..77b3e93e6c 100644 --- a/jsonrpc/client.go +++ b/jsonrpc/client.go @@ -6,6 +6,7 @@ import ( "github.com/0xPolygon/polygon-edge/helper/common" "github.com/0xPolygon/polygon-edge/helper/hex" "github.com/0xPolygon/polygon-edge/types" + "github.com/umbracle/ethgo" "github.com/umbracle/ethgo/jsonrpc" ) @@ -24,6 +25,11 @@ func NewEthClient(url string) (*EthClient, error) { return &EthClient{client}, nil } +// EndpointCall calls a specified method on the json rpc client with given params and returns the result in the out parameter +func (e *EthClient) EndpointCall(method string, out interface{}, params ...interface{}) error { + return e.client.Call(method, out, params...) +} + // GetCode returns the code of a contract func (e *EthClient) GetCode(addr types.Address, block BlockNumberOrHash) (string, error) { var res string @@ -73,8 +79,8 @@ func (e *EthClient) GetBlockByHash(hash types.Hash, full bool) (*types.Block, er } // GetTransactionByHash returns a transaction by hash -func (e *EthClient) GetTransactionByHash(hash types.Hash) (*types.Transaction, error) { - var txn *types.Transaction +func (e *EthClient) GetTransactionByHash(hash types.Hash) (*Transaction, error) { + var txn *Transaction err := e.client.Call("eth_getTransactionByHash", &txn, hash) return txn, err @@ -99,8 +105,8 @@ func (e *EthClient) SendTransaction(txn *types.Transaction) (types.Hash, error) } // GetTransactionReceipt returns the receipt of a transaction by transaction hash -func (e *EthClient) GetTransactionReceipt(hash types.Hash) (*types.Receipt, error) { - var receipt *types.Receipt +func (e *EthClient) GetTransactionReceipt(hash types.Hash) (*ethgo.Receipt, error) { + var receipt *ethgo.Receipt err := e.client.Call("eth_getTransactionReceipt", &receipt, hash) return receipt, err @@ -176,3 +182,38 @@ func (e *EthClient) MaxPriorityFeePerGas() (*big.Int, error) { return common.ParseUint256orHex(&out) } + +// FeeHistory returns base fee per gas and transaction effective priority fee +func (e *EthClient) FeeHistory( + blockCount uint64, + newestBlock BlockNumber, + rewardPercentiles []float64, +) (*FeeHistory, error) { + var out *FeeHistory + if err := e.client.Call("eth_feeHistory", &out, blockCount, + newestBlock.String(), rewardPercentiles); err != nil { + return nil, err + } + + return out, nil +} + +// Accounts returns a list of addresses owned by client +func (e *EthClient) Accounts() ([]types.Address, error) { + var out []types.Address + if err := e.client.Call("eth_accounts", &out); err != nil { + return nil, err + } + + return out, nil +} + +// GetLogs returns an array of all logs matching a given filter object +func (e *EthClient) GetLogs(filter *ethgo.LogFilter) ([]*ethgo.Log, error) { + var out []*ethgo.Log + if err := e.client.Call("eth_getLogs", &out, filter); err != nil { + return nil, err + } + + return out, nil +} diff --git a/jsonrpc/jsonrpc_test.go b/jsonrpc/jsonrpc_test.go index 32399ab84c..e941278978 100644 --- a/jsonrpc/jsonrpc_test.go +++ b/jsonrpc/jsonrpc_test.go @@ -11,7 +11,7 @@ import ( "github.com/hashicorp/go-hclog" "github.com/stretchr/testify/require" - "github.com/0xPolygon/polygon-edge/helper/tests" + "github.com/0xPolygon/polygon-edge/helper/common" "github.com/0xPolygon/polygon-edge/versioning" ) @@ -103,7 +103,7 @@ func newTestJSONRPC(t *testing.T) (*JSONRPC, error) { store := newMockStore() - port, err := tests.GetFreePort() + port, err := common.GetFreePort() require.NoError(t, err, "Unable to fetch free port, %v", err) config := &Config{ diff --git a/jsonrpc/types.go b/jsonrpc/types.go index 46b98b7cfd..2e45aca2af 100644 --- a/jsonrpc/types.go +++ b/jsonrpc/types.go @@ -1,6 +1,7 @@ package jsonrpc import ( + "encoding/json" "fmt" "math/big" "strconv" @@ -12,7 +13,10 @@ import ( "github.com/valyala/fastjson" ) -var defaultArena fastjson.ArenaPool +var ( + defaultArena fastjson.ArenaPool + defaultPool fastjson.ParserPool +) const jsonRPCMetric = "json_rpc" @@ -576,3 +580,69 @@ func (c *CallMsg) MarshalJSON() ([]byte, error) { return res, nil } + +type FeeHistory struct { + OldestBlock uint64 `json:"oldestBlock"` + Reward [][]uint64 `json:"reward,omitempty"` + BaseFee []uint64 `json:"baseFeePerGas,omitempty"` + GasUsedRatio []float64 `json:"gasUsedRatio"` +} + +func (f *FeeHistory) UnmarshalJSON(data []byte) error { + var raw feeHistoryResult + + if err := json.Unmarshal(data, &raw); err != nil { + return err + } + + f.OldestBlock = uint64(raw.OldestBlock) + + if raw.Reward != nil { + f.Reward = make([][]uint64, 0, len(raw.Reward)) + for _, r := range raw.Reward { + elem := make([]uint64, 0, len(r)) + for _, i := range r { + elem = append(elem, uint64(i)) + } + + f.Reward = append(f.Reward, elem) + } + } + + f.BaseFee = make([]uint64, 0, len(raw.BaseFeePerGas)) + for _, i := range raw.BaseFeePerGas { + f.BaseFee = append(f.BaseFee, uint64(i)) + } + + f.GasUsedRatio = raw.GasUsedRatio + + return nil +} + +type Transaction struct { + *types.Transaction + + BlockNumber uint64 `json:"blockNumber"` + BlockHash types.Hash `json:"blockHash"` + TxnIndex uint64 `json:"transactionIndex"` +} + +func (t *Transaction) UnmarshalJSON(data []byte) error { + p := defaultPool.Get() + defer defaultPool.Put(p) + + v, err := p.Parse(string(data)) + if err != nil { + return err + } + + if err := t.Transaction.UnmarshalJSONWith(v); err != nil { + return err + } + + t.BlockNumber = v.GetUint64("blockNumber") + t.BlockHash = types.Hash(v.GetStringBytes("blockHash")) + t.TxnIndex = v.GetUint64("transactionIndex") + + return nil +} diff --git a/network/e2e_testing.go b/network/e2e_testing.go index b94edf6b84..0f19dcabfe 100644 --- a/network/e2e_testing.go +++ b/network/e2e_testing.go @@ -262,7 +262,7 @@ func initBootnodes(server *Server, bootnodes ...string) { func CreateServer(params *CreateServerParams) (*Server, error) { cfg := DefaultConfig() - port, portErr := tests.GetFreePort() + port, portErr := common.GetFreePort() if portErr != nil { return nil, fmt.Errorf("unable to fetch free port, %w", portErr) diff --git a/txrelayer/txrelayer.go b/txrelayer/txrelayer.go index 405efd8246..200f6601f3 100644 --- a/txrelayer/txrelayer.go +++ b/txrelayer/txrelayer.go @@ -9,8 +9,8 @@ import ( "sync" "time" + "github.com/0xPolygon/polygon-edge/jsonrpc" "github.com/umbracle/ethgo" - "github.com/umbracle/ethgo/jsonrpc" "github.com/0xPolygon/polygon-edge/crypto" "github.com/0xPolygon/polygon-edge/types" @@ -43,14 +43,14 @@ type TxRelayer interface { // (this function is meant only for testing purposes and is about to be removed at some point) SendTransactionLocal(txn *types.Transaction) (*ethgo.Receipt, error) // Client returns jsonrpc client - Client() *jsonrpc.Client + Client() *jsonrpc.EthClient } var _ TxRelayer = (*TxRelayerImpl)(nil) type TxRelayerImpl struct { ipAddress string - client *jsonrpc.Client + client *jsonrpc.EthClient receiptTimeout time.Duration numRetries int @@ -70,7 +70,7 @@ func NewTxRelayer(opts ...TxRelayerOption) (TxRelayer, error) { } if t.client == nil { - client, err := jsonrpc.NewClient(t.ipAddress) + client, err := jsonrpc.NewEthClient(t.ipAddress) if err != nil { return nil, err } @@ -83,13 +83,13 @@ func NewTxRelayer(opts ...TxRelayerOption) (TxRelayer, error) { // Call executes a message call immediately without creating a transaction on the blockchain func (t *TxRelayerImpl) Call(from types.Address, to types.Address, input []byte) (string, error) { - callMsg := ðgo.CallMsg{ - From: ethgo.Address(from), - To: (*ethgo.Address)(&to), + callMsg := &jsonrpc.CallMsg{ + From: from, + To: &to, Data: input, } - return t.client.Eth().Call(callMsg, ethgo.Pending) + return t.client.Call(callMsg, jsonrpc.PendingBlockNumber, nil) } // SendTransaction signs given transaction by provided key and sends it to the blockchain @@ -123,22 +123,22 @@ func (t *TxRelayerImpl) SendTransaction(txn *types.Transaction, key crypto.Key) } // Client returns jsonrpc client -func (t *TxRelayerImpl) Client() *jsonrpc.Client { +func (t *TxRelayerImpl) Client() *jsonrpc.EthClient { return t.client } -func (t *TxRelayerImpl) sendTransactionLocked(txn *types.Transaction, key crypto.Key) (ethgo.Hash, error) { +func (t *TxRelayerImpl) sendTransactionLocked(txn *types.Transaction, key crypto.Key) (types.Hash, error) { t.lock.Lock() defer t.lock.Unlock() - nonce, err := t.client.Eth().GetNonce(ethgo.Address(key.Address()), ethgo.Pending) + nonce, err := t.client.GetNonce(key.Address(), jsonrpc.PendingBlockNumberOrHash) if err != nil { - return ethgo.ZeroHash, fmt.Errorf("failed to get nonce: %w", err) + return types.ZeroHash, fmt.Errorf("failed to get nonce: %w", err) } - chainID, err := t.client.Eth().ChainID() + chainID, err := t.client.ChainID() if err != nil { - return ethgo.ZeroHash, err + return types.ZeroHash, err } txn.SetChainID(chainID) @@ -152,8 +152,8 @@ func (t *TxRelayerImpl) sendTransactionLocked(txn *types.Transaction, key crypto maxPriorityFee := txn.GetGasTipCap() if maxPriorityFee == nil { // retrieve the max priority fee per gas - if maxPriorityFee, err = t.Client().Eth().MaxPriorityFeePerGas(); err != nil { - return ethgo.ZeroHash, fmt.Errorf("failed to get max priority fee per gas: %w", err) + if maxPriorityFee, err = t.Client().MaxPriorityFeePerGas(); err != nil { + return types.ZeroHash, fmt.Errorf("failed to get max priority fee per gas: %w", err) } // set retrieved max priority fee per gas increased by certain percentage @@ -164,12 +164,17 @@ func (t *TxRelayerImpl) sendTransactionLocked(txn *types.Transaction, key crypto if txn.GetGasFeeCap() == nil { // retrieve the latest base fee - feeHist, err := t.Client().Eth().FeeHistory(1, ethgo.Latest, nil) + feeHist, err := t.Client().FeeHistory(1, jsonrpc.PendingBlockNumber, nil) if err != nil { - return ethgo.ZeroHash, fmt.Errorf("failed to get fee history: %w", err) + return types.ZeroHash, fmt.Errorf("failed to get fee history: %w", err) + } + + baseFee := big.NewInt(0) + + if len(feeHist.BaseFee) != 0 { + baseFee = baseFee.SetUint64(feeHist.BaseFee[len(feeHist.BaseFee)-1]) } - baseFee := feeHist.BaseFee[len(feeHist.BaseFee)-1] // set max fee per gas as sum of base fee and max priority fee // (increased by certain percentage) maxFeePerGas := new(big.Int).Add(baseFee, maxPriorityFee) @@ -178,9 +183,9 @@ func (t *TxRelayerImpl) sendTransactionLocked(txn *types.Transaction, key crypto txn.SetGasFeeCap(new(big.Int).Add(maxFeePerGas, compMaxFeePerGas)) } } else if txn.GasPrice() == nil || txn.GasPrice().Uint64() == 0 { - gasPrice, err := t.Client().Eth().GasPrice() + gasPrice, err := t.Client().GasPrice() if err != nil { - return ethgo.ZeroHash, fmt.Errorf("failed to get gas price: %w", err) + return types.ZeroHash, fmt.Errorf("failed to get gas price: %w", err) } gasPriceBigInt := new(big.Int).SetUint64(gasPrice + (gasPrice * feeIncreasePercentage / 100)) @@ -188,9 +193,9 @@ func (t *TxRelayerImpl) sendTransactionLocked(txn *types.Transaction, key crypto } if txn.Gas() == 0 { - gasLimit, err := t.client.Eth().EstimateGas(ConvertTxnToCallMsg(txn)) + gasLimit, err := t.client.EstimateGas(ConvertTxnToCallMsg(txn)) if err != nil { - return ethgo.ZeroHash, fmt.Errorf("failed to estimate gas: %w", err) + return types.ZeroHash, fmt.Errorf("failed to estimate gas: %w", err) } txn.SetGas(gasLimit + (gasLimit * gasLimitIncreasePercentage / 100)) @@ -203,7 +208,7 @@ func (t *TxRelayerImpl) sendTransactionLocked(txn *types.Transaction, key crypto return key.Sign(hash.Bytes()) }) if err != nil { - return ethgo.ZeroHash, err + return types.ZeroHash, err } if t.writer != nil { @@ -223,7 +228,7 @@ func (t *TxRelayerImpl) sendTransactionLocked(txn *types.Transaction, key crypto rlpTxn := signedTxn.MarshalRLP() - return t.client.Eth().SendRawTransaction(rlpTxn) + return t.client.SendRawTransaction(rlpTxn) } // SendTransactionLocal sends non-signed transaction @@ -237,40 +242,40 @@ func (t *TxRelayerImpl) SendTransactionLocal(txn *types.Transaction) (*ethgo.Rec return t.waitForReceipt(txnHash) } -func (t *TxRelayerImpl) sendTransactionLocalLocked(txn *types.Transaction) (ethgo.Hash, error) { +func (t *TxRelayerImpl) sendTransactionLocalLocked(txn *types.Transaction) (types.Hash, error) { t.lock.Lock() defer t.lock.Unlock() - accounts, err := t.client.Eth().Accounts() + accounts, err := t.client.Accounts() if err != nil { - return ethgo.ZeroHash, err + return types.ZeroHash, err } if len(accounts) == 0 { - return ethgo.ZeroHash, errNoAccounts + return types.ZeroHash, errNoAccounts } txn.SetFrom(types.Address(accounts[0])) - gasLimit, err := t.client.Eth().EstimateGas(ConvertTxnToCallMsg(txn)) + gasLimit, err := t.client.EstimateGas(ConvertTxnToCallMsg(txn)) if err != nil { - return ethgo.ZeroHash, err + return types.ZeroHash, err } txn.SetGas(gasLimit) txn.SetGasPrice(new(big.Int).SetUint64(defaultGasPrice)) - return t.client.Eth().SendTransaction(convertTxn(txn)) + return t.client.SendTransaction(txn) } -func (t *TxRelayerImpl) waitForReceipt(hash ethgo.Hash) (*ethgo.Receipt, error) { +func (t *TxRelayerImpl) waitForReceipt(hash types.Hash) (*ethgo.Receipt, error) { // A negative numRetries means we don't want to receive the receipt after SendTransaction/SendTransactionLocal calls if t.numRetries < 0 { return nil, nil } for count := 0; count < t.numRetries; count++ { - receipt, err := t.client.Eth().GetTransactionReceipt(hash) + receipt, err := t.client.GetTransactionReceipt(hash) if err != nil { if err.Error() != "not found" { return nil, err @@ -288,80 +293,25 @@ func (t *TxRelayerImpl) waitForReceipt(hash ethgo.Hash) (*ethgo.Receipt, error) } // ConvertTxnToCallMsg converts txn instance to call message -func ConvertTxnToCallMsg(txn *types.Transaction) *ethgo.CallMsg { - gasPrice := uint64(0) +func ConvertTxnToCallMsg(txn *types.Transaction) *jsonrpc.CallMsg { + gasPrice := big.NewInt(0) if txn.GasPrice() != nil { - gasPrice = txn.GasPrice().Uint64() + gasPrice = gasPrice.Set(txn.GasPrice()) } - return ðgo.CallMsg{ - From: ethgo.Address(txn.From()), - To: (*ethgo.Address)(txn.To()), + return &jsonrpc.CallMsg{ + From: txn.From(), + To: 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(), + Gas: txn.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) -func WithClient(client *jsonrpc.Client) TxRelayerOption { +func WithClient(client *jsonrpc.EthClient) TxRelayerOption { return func(t *TxRelayerImpl) { t.client = client } diff --git a/types/access_list_tx.go b/types/access_list_tx.go index 2c601704f3..f9886555aa 100644 --- a/types/access_list_tx.go +++ b/types/access_list_tx.go @@ -134,7 +134,7 @@ func (t *TxAccessList) unmarshalJSON(v *fastjson.Value) error { for _, elem := range elems { accessTuple := AccessTuple{} - addr, err := unmarshalJSONAddr(elem, "address") + addr, err := UnmarshalJSONAddr(elem, "address") if err != nil { return err } @@ -395,21 +395,21 @@ func (tx *AccessListTxn) unmarshalJSON(v *fastjson.Value) error { return err } - gasPrice, err := unmarshalJSONBigInt(v, "gasPrice") + gasPrice, err := UnmarshalJSONBigInt(v, "gasPrice") if err != nil { return err } tx.setGasPrice(gasPrice) - chainID, err := unmarshalJSONBigInt(v, "chainId") + chainID, err := UnmarshalJSONBigInt(v, "chainId") if err != nil { return err } tx.setChainID(chainID) - if hasKey(v, "accessList") { + if HasKey(v, "accessList") { if err := tx.AccessList.unmarshalJSON(v.Get("accessList")); err != nil { return err } diff --git a/types/base_tx.go b/types/base_tx.go index 982c68e4c6..50a2801342 100644 --- a/types/base_tx.go +++ b/types/base_tx.go @@ -109,14 +109,14 @@ func (tx *BaseTx) copy() *BaseTx { } func (tx *BaseTx) unmarshalJSON(v *fastjson.Value) error { - hash, err := unmarshalJSONHash(v, "hash") + hash, err := UnmarshalJSONHash(v, "hash") if err != nil { return err } tx.setHash(hash) - from, err := unmarshalJSONAddr(v, "from") + from, err := UnmarshalJSONAddr(v, "from") if err != nil { return err } @@ -124,11 +124,11 @@ func (tx *BaseTx) unmarshalJSON(v *fastjson.Value) error { tx.setFrom(from) // Do not decode 'to' if it doesn't exist. - if hasKey(v, "to") { + if HasKey(v, "to") { if v.Get("to").String() != "null" { var to Address - if to, err = unmarshalJSONAddr(v, "to"); err != nil { + if to, err = UnmarshalJSONAddr(v, "to"); err != nil { return err } @@ -136,45 +136,45 @@ func (tx *BaseTx) unmarshalJSON(v *fastjson.Value) error { } } - input, err := unmarshalJSONBytes(v, "input") + input, err := UnmarshalJSONBytes(v, "input") if err != nil { return err } tx.setInput(input) - value, err := unmarshalJSONBigInt(v, "value") + value, err := UnmarshalJSONBigInt(v, "value") if err != nil { return err } tx.setValue(value) - nonce, err := unmarshalJSONUint64(v, "nonce") + nonce, err := UnmarshalJSONUint64(v, "nonce") if err != nil { return err } tx.setNonce(nonce) - vParity, err := unmarshalJSONBigInt(v, "v") + vParity, err := UnmarshalJSONBigInt(v, "v") if err != nil { return err } - r, err := unmarshalJSONBigInt(v, "r") + r, err := UnmarshalJSONBigInt(v, "r") if err != nil { return err } - s, err := unmarshalJSONBigInt(v, "s") + s, err := UnmarshalJSONBigInt(v, "s") if err != nil { return err } tx.setSignatureValues(vParity, r, s) - gas, err := unmarshalJSONUint64(v, "gas") + gas, err := UnmarshalJSONUint64(v, "gas") if err != nil { return err } diff --git a/types/dynamic_fee_tx.go b/types/dynamic_fee_tx.go index a90c650fd2..94cad7ac64 100644 --- a/types/dynamic_fee_tx.go +++ b/types/dynamic_fee_tx.go @@ -253,28 +253,28 @@ func (tx *DynamicFeeTx) unmarshalJSON(v *fastjson.Value) error { return err } - gasTipCap, err := unmarshalJSONBigInt(v, "maxPriorityFeePerGas") + gasTipCap, err := UnmarshalJSONBigInt(v, "maxPriorityFeePerGas") if err != nil { return err } tx.setGasTipCap(gasTipCap) - gasFeeCap, err := unmarshalJSONBigInt(v, "maxFeePerGas") + gasFeeCap, err := UnmarshalJSONBigInt(v, "maxFeePerGas") if err != nil { return err } tx.setGasFeeCap(gasFeeCap) - chainID, err := unmarshalJSONBigInt(v, "chainId") + chainID, err := UnmarshalJSONBigInt(v, "chainId") if err != nil { return err } tx.setChainID(chainID) - if hasKey(v, "accessList") { + if HasKey(v, "accessList") { if err := tx.AccessList.unmarshalJSON(v.Get("accessList")); err != nil { return err } diff --git a/types/json.go b/types/json.go new file mode 100644 index 0000000000..f749a3f3c7 --- /dev/null +++ b/types/json.go @@ -0,0 +1,137 @@ +package types + +import ( + "fmt" + "math/big" + "strings" + + "github.com/0xPolygon/polygon-edge/helper/common" + "github.com/0xPolygon/polygon-edge/helper/hex" + "github.com/valyala/fastjson" +) + +var ( + DefaultPool fastjson.ParserPool +) + +func UnmarshalJSONHash(v *fastjson.Value, key string) (Hash, error) { + hash := Hash{} + + b := v.GetStringBytes(key) + if len(b) == 0 { + return ZeroHash, fmt.Errorf("field '%s' not found", key) + } + + err := hash.UnmarshalText(b) + + return hash, err +} + +func UnmarshalJSONAddr(v *fastjson.Value, key string) (Address, error) { + b := v.GetStringBytes(key) + if len(b) == 0 { + return ZeroAddress, fmt.Errorf("field '%s' not found", key) + } + + a := Address{} + err := a.UnmarshalText(b) + + return a, err +} + +func UnmarshalJSONBytes(v *fastjson.Value, key string, bits ...int) ([]byte, error) { + vv := v.Get(key) + if vv == nil { + return nil, fmt.Errorf("field '%s' not found", key) + } + + str := vv.String() + str = strings.Trim(str, "\"") + + if !strings.HasPrefix(str, "0x") { + return nil, fmt.Errorf("field '%s' does not have 0x prefix: '%s'", key, str) + } + + str = str[2:] + if len(str)%2 != 0 { + str = "0" + str + } + + buf, err := hex.DecodeString(str) + if err != nil { + return nil, err + } + + if len(bits) > 0 && bits[0] != len(buf) { + return nil, fmt.Errorf("field '%s' invalid length, expected %d but found %d: %s", key, bits[0], len(buf), str) + } + + return buf, nil +} + +func UnmarshalJSONUint64(v *fastjson.Value, key string) (uint64, error) { + vv := v.Get(key) + if vv == nil { + return 0, fmt.Errorf("field '%s' not found", key) + } + + str := vv.String() + str = strings.Trim(str, "\"") + + return common.ParseUint64orHex(&str) +} + +func UnmarshalJSONBigInt(v *fastjson.Value, key string) (*big.Int, error) { + vv := v.Get(key) + if vv == nil { + return nil, fmt.Errorf("field '%s' not found", key) + } + + str := vv.String() + str = strings.Trim(str, "\"") + + return common.ParseUint256orHex(&str) +} + +func UnmarshalJSONNonce(n *Nonce, v *fastjson.Value, key string) error { + b := v.GetStringBytes(key) + if len(b) == 0 { + return fmt.Errorf("field '%s' not found", key) + } + + return UnmarshalTextByte(n[:], b, 8) +} + +func UnmarshalJSONBloom(bloom *Bloom, v *fastjson.Value, key string) error { + b := v.GetStringBytes(key) + if len(b) == 0 { + return fmt.Errorf("field '%s' not found", key) + } + + return UnmarshalTextByte(bloom[:], b, BloomByteLength) +} + +func UnmarshalTextByte(dst, src []byte, size int) error { + str := string(src) + str = strings.Trim(str, "\"") + + b, err := hex.DecodeHex(str) + if err != nil { + return err + } + + if len(b) != size { + return fmt.Errorf("length %d is not correct, expected %d", len(b), size) + } + + copy(dst, b) + + return nil +} + +// HasKey is a helper function for checking if given key exists in json +func HasKey(v *fastjson.Value, key string) bool { + value := v.Get(key) + + return value != nil && value.Type() != fastjson.TypeNull +} diff --git a/types/json_unmarshal.go b/types/json_unmarshal.go index 3d57b89df9..b9fbea925b 100644 --- a/types/json_unmarshal.go +++ b/types/json_unmarshal.go @@ -1,21 +1,13 @@ package types import ( - "fmt" - "math/big" - "strings" - - "github.com/0xPolygon/polygon-edge/helper/common" - "github.com/0xPolygon/polygon-edge/helper/hex" "github.com/valyala/fastjson" ) -var defaultPool fastjson.ParserPool - // UnmarshalJSON implements the unmarshal interface func (b *Block) UnmarshalJSON(buf []byte) error { - p := defaultPool.Get() - defer defaultPool.Put(p) + p := DefaultPool.Get() + defer DefaultPool.Put(p) v, err := p.Parse(string(buf)) if err != nil { @@ -35,7 +27,7 @@ func (b *Block) UnmarshalJSON(buf []byte) error { if len(elems) != 0 && elems[0].Type() != fastjson.TypeString { for _, elem := range elems { txn := new(Transaction) - if err := txn.unmarshalJSON(elem); err != nil { + if err := txn.UnmarshalJSONWith(elem); err != nil { return err } @@ -62,8 +54,8 @@ func (b *Block) UnmarshalJSON(buf []byte) error { } func (h *Header) UnmarshalJSON(buf []byte) error { - p := defaultPool.Get() - defer defaultPool.Put(p) + p := DefaultPool.Get() + defer DefaultPool.Put(p) v, err := p.Parse(string(buf)) if err != nil { @@ -76,67 +68,67 @@ func (h *Header) UnmarshalJSON(buf []byte) error { func (h *Header) unmarshalJSON(v *fastjson.Value) error { var err error - if h.Hash, err = unmarshalJSONHash(v, "hash"); err != nil { + if h.Hash, err = UnmarshalJSONHash(v, "hash"); err != nil { return err } - if h.ParentHash, err = unmarshalJSONHash(v, "parentHash"); err != nil { + if h.ParentHash, err = UnmarshalJSONHash(v, "parentHash"); err != nil { return err } - if h.Sha3Uncles, err = unmarshalJSONHash(v, "sha3Uncles"); err != nil { + if h.Sha3Uncles, err = UnmarshalJSONHash(v, "sha3Uncles"); err != nil { return err } - if h.TxRoot, err = unmarshalJSONHash(v, "transactionsRoot"); err != nil { + if h.TxRoot, err = UnmarshalJSONHash(v, "transactionsRoot"); err != nil { return err } - if h.StateRoot, err = unmarshalJSONHash(v, "stateRoot"); err != nil { + if h.StateRoot, err = UnmarshalJSONHash(v, "stateRoot"); err != nil { return err } - if h.ReceiptsRoot, err = unmarshalJSONHash(v, "receiptsRoot"); err != nil { + if h.ReceiptsRoot, err = UnmarshalJSONHash(v, "receiptsRoot"); err != nil { return err } - if h.Miner, err = unmarshalJSONBytes(v, "miner"); err != nil { + if h.Miner, err = UnmarshalJSONBytes(v, "miner"); err != nil { return err } - if h.Number, err = unmarshalJSONUint64(v, "number"); err != nil { + if h.Number, err = UnmarshalJSONUint64(v, "number"); err != nil { return err } - if h.GasLimit, err = unmarshalJSONUint64(v, "gasLimit"); err != nil { + if h.GasLimit, err = UnmarshalJSONUint64(v, "gasLimit"); err != nil { return err } - if h.GasUsed, err = unmarshalJSONUint64(v, "gasUsed"); err != nil { + if h.GasUsed, err = UnmarshalJSONUint64(v, "gasUsed"); err != nil { return err } - if h.MixHash, err = unmarshalJSONHash(v, "mixHash"); err != nil { + if h.MixHash, err = UnmarshalJSONHash(v, "mixHash"); err != nil { return err } - if err = unmarshalJSONNonce(&h.Nonce, v, "nonce"); err != nil { + if err = UnmarshalJSONNonce(&h.Nonce, v, "nonce"); err != nil { return err } - if h.Timestamp, err = unmarshalJSONUint64(v, "timestamp"); err != nil { + if h.Timestamp, err = UnmarshalJSONUint64(v, "timestamp"); err != nil { return err } - if h.Difficulty, err = unmarshalJSONUint64(v, "difficulty"); err != nil { + if h.Difficulty, err = UnmarshalJSONUint64(v, "difficulty"); err != nil { return err } - if h.ExtraData, err = unmarshalJSONBytes(v, "extraData"); err != nil { + if h.ExtraData, err = UnmarshalJSONBytes(v, "extraData"); err != nil { return err } - if h.BaseFee, err = unmarshalJSONUint64(v, "baseFee"); err != nil { + if h.BaseFee, err = UnmarshalJSONUint64(v, "baseFee"); err != nil { if err.Error() != "field 'baseFee' not found" { return err } @@ -147,28 +139,28 @@ func (h *Header) unmarshalJSON(v *fastjson.Value) error { // UnmarshalJSON implements the unmarshal interface func (t *Transaction) UnmarshalJSON(buf []byte) error { - p := defaultPool.Get() - defer defaultPool.Put(p) + p := DefaultPool.Get() + defer DefaultPool.Put(p) v, err := p.Parse(string(buf)) if err != nil { return err } - return t.unmarshalJSON(v) + return t.UnmarshalJSONWith(v) } -func (t *Transaction) unmarshalJSON(v *fastjson.Value) error { - if hasKey(v, "type") { - txnType, err := unmarshalJSONUint64(v, "type") +func (t *Transaction) UnmarshalJSONWith(v *fastjson.Value) error { + if HasKey(v, "type") { + txnType, err := UnmarshalJSONUint64(v, "type") if err != nil { return err } t.InitInnerData(TxType(txnType)) } else { - if hasKey(v, "chainId") { - if hasKey(v, "maxFeePerGas") { + if HasKey(v, "chainId") { + if HasKey(v, "maxFeePerGas") { t.InitInnerData(DynamicFeeTxType) } else { t.InitInnerData(AccessListTxType) @@ -183,16 +175,16 @@ func (t *Transaction) unmarshalJSON(v *fastjson.Value) error { // UnmarshalJSON implements the unmarshal interface func (r *Receipt) UnmarshalJSON(buf []byte) error { - p := defaultPool.Get() - defer defaultPool.Put(p) + p := DefaultPool.Get() + defer DefaultPool.Put(p) v, err := p.Parse(string(buf)) if err != nil { return nil } - if hasKey(v, "contractAddress") { - contractAddr, err := unmarshalJSONAddr(v, "contractAddress") + if HasKey(v, "contractAddress") { + contractAddr, err := UnmarshalJSONAddr(v, "contractAddress") if err != nil { return err } @@ -200,29 +192,29 @@ func (r *Receipt) UnmarshalJSON(buf []byte) error { r.ContractAddress = &contractAddr } - if r.TxHash, err = unmarshalJSONHash(v, "transactionHash"); err != nil { + if r.TxHash, err = UnmarshalJSONHash(v, "transactionHash"); err != nil { return err } - if r.GasUsed, err = unmarshalJSONUint64(v, "gasUsed"); err != nil { + if r.GasUsed, err = UnmarshalJSONUint64(v, "gasUsed"); err != nil { return err } - if r.CumulativeGasUsed, err = unmarshalJSONUint64(v, "cumulativeGasUsed"); err != nil { + if r.CumulativeGasUsed, err = UnmarshalJSONUint64(v, "cumulativeGasUsed"); err != nil { return err } - if err = unmarshalJSONBloom(&r.LogsBloom, v, "logsBloom"); err != nil { + if err = UnmarshalJSONBloom(&r.LogsBloom, v, "logsBloom"); err != nil { return err } - if r.Root, err = unmarshalJSONHash(v, "root"); err != nil { + if r.Root, err = UnmarshalJSONHash(v, "root"); err != nil { return err } - if hasKey(v, "status") { + if HasKey(v, "status") { // post-byzantium fork - status, err := unmarshalJSONUint64(v, "status") + status, err := UnmarshalJSONUint64(v, "status") if err != nil { return err } @@ -247,8 +239,8 @@ func (r *Receipt) UnmarshalJSON(buf []byte) error { // UnmarshalJSON implements the unmarshal interface func (r *Log) UnmarshalJSON(buf []byte) error { - p := defaultPool.Get() - defer defaultPool.Put(p) + p := DefaultPool.Get() + defer DefaultPool.Put(p) v, err := p.Parse(string(buf)) if err != nil { @@ -261,11 +253,11 @@ func (r *Log) UnmarshalJSON(buf []byte) error { func (r *Log) unmarshalJSON(v *fastjson.Value) error { var err error - if r.Address, err = unmarshalJSONAddr(v, "address"); err != nil { + if r.Address, err = UnmarshalJSONAddr(v, "address"); err != nil { return err } - if r.Data, err = unmarshalJSONBytes(v, "data"); err != nil { + if r.Data, err = UnmarshalJSONBytes(v, "data"); err != nil { return err } @@ -287,125 +279,3 @@ func (r *Log) unmarshalJSON(v *fastjson.Value) error { return nil } - -func unmarshalJSONHash(v *fastjson.Value, key string) (Hash, error) { - hash := Hash{} - - b := v.GetStringBytes(key) - if len(b) == 0 { - return ZeroHash, fmt.Errorf("field '%s' not found", key) - } - - err := hash.UnmarshalText(b) - - return hash, err -} - -func unmarshalJSONAddr(v *fastjson.Value, key string) (Address, error) { - b := v.GetStringBytes(key) - if len(b) == 0 { - return ZeroAddress, fmt.Errorf("field '%s' not found", key) - } - - a := Address{} - err := a.UnmarshalText(b) - - return a, err -} - -func unmarshalJSONBytes(v *fastjson.Value, key string, bits ...int) ([]byte, error) { - vv := v.Get(key) - if vv == nil { - return nil, fmt.Errorf("field '%s' not found", key) - } - - str := vv.String() - str = strings.Trim(str, "\"") - - if !strings.HasPrefix(str, "0x") { - return nil, fmt.Errorf("field '%s' does not have 0x prefix: '%s'", key, str) - } - - str = str[2:] - if len(str)%2 != 0 { - str = "0" + str - } - - buf, err := hex.DecodeString(str) - if err != nil { - return nil, err - } - - if len(bits) > 0 && bits[0] != len(buf) { - return nil, fmt.Errorf("field '%s' invalid length, expected %d but found %d: %s", key, bits[0], len(buf), str) - } - - return buf, nil -} - -func unmarshalJSONUint64(v *fastjson.Value, key string) (uint64, error) { - vv := v.Get(key) - if vv == nil { - return 0, fmt.Errorf("field '%s' not found", key) - } - - str := vv.String() - str = strings.Trim(str, "\"") - - return common.ParseUint64orHex(&str) -} - -func unmarshalJSONBigInt(v *fastjson.Value, key string) (*big.Int, error) { - vv := v.Get(key) - if vv == nil { - return nil, fmt.Errorf("field '%s' not found", key) - } - - str := vv.String() - str = strings.Trim(str, "\"") - - return common.ParseUint256orHex(&str) -} - -func unmarshalJSONNonce(n *Nonce, v *fastjson.Value, key string) error { - b := v.GetStringBytes(key) - if len(b) == 0 { - return fmt.Errorf("field '%s' not found", key) - } - - return unmarshalTextByte(n[:], b, 8) -} - -func unmarshalJSONBloom(bloom *Bloom, v *fastjson.Value, key string) error { - b := v.GetStringBytes(key) - if len(b) == 0 { - return fmt.Errorf("field '%s' not found", key) - } - - return unmarshalTextByte(bloom[:], b, BloomByteLength) -} - -func unmarshalTextByte(dst, src []byte, size int) error { - str := string(src) - str = strings.Trim(str, "\"") - - b, err := hex.DecodeHex(str) - if err != nil { - return err - } - - if len(b) != size { - return fmt.Errorf("length %d is not correct, expected %d", len(b), size) - } - - copy(dst, b) - - return nil -} - -// hasKey is a helper function for checking if given key exists in json -func hasKey(v *fastjson.Value, key string) bool { - value := v.Get(key) - - return value != nil && value.Type() != fastjson.TypeNull -} diff --git a/types/legacy_tx.go b/types/legacy_tx.go index f78aca36ee..9ed937bc82 100644 --- a/types/legacy_tx.go +++ b/types/legacy_tx.go @@ -205,7 +205,7 @@ func (tx *LegacyTx) unmarshalJSON(v *fastjson.Value) error { return err } - gasPrice, err := unmarshalJSONBigInt(v, "gasPrice") + gasPrice, err := UnmarshalJSONBigInt(v, "gasPrice") if err != nil { return err } diff --git a/types/receipt.go b/types/receipt.go index a482d9f2bb..2701d0d493 100644 --- a/types/receipt.go +++ b/types/receipt.go @@ -41,6 +41,14 @@ func (r *Receipt) SetStatus(s ReceiptStatus) { r.Status = &s } +func (r *Receipt) HasFailed() bool { + if r.Status != nil { + return *r.Status == ReceiptFailed + } + + return true +} + func (r *Receipt) SetContractAddress(contractAddress Address) { r.ContractAddress = &contractAddress } diff --git a/types/state_tx.go b/types/state_tx.go index ff62671a49..21a00e2f16 100644 --- a/types/state_tx.go +++ b/types/state_tx.go @@ -205,7 +205,7 @@ func (tx *StateTx) unmarshalJSON(v *fastjson.Value) error { return err } - gasPrice, err := unmarshalJSONBigInt(v, "gasPrice") + gasPrice, err := UnmarshalJSONBigInt(v, "gasPrice") if err != nil { return err }