-
Notifications
You must be signed in to change notification settings - Fork 195
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fix(evm): proper tx gas refund outside of CallContract #2132
Merged
Merged
Changes from 9 commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
62f7baf
fix(evm): proper block gas calculation in precompile calls
onikonychev d25a668
chore: changelog update
onikonychev ba6fc13
fix(evm): proper tx gas refund
onikonychev 5b57729
fix: moved gas comsumption from call_contract to msg_server
onikonychev 62de834
test: added integration tests for gas used
onikonychev 06d7d98
test: fixed test for funtoken created from coin
onikonychev bde298e
chore: lint
onikonychev 1f0b2ca
Merge branch 'main' into fix/gas-refund
k-yang f680e2c
Apply suggestions from code review
k-yang e87aa36
Merge branch 'main' of github.com:NibiruChain/nibiru into fix/gas-refund
onikonychev 0ad6b91
fix: cleanup
onikonychev 07cd9f8
Merge branch 'fix/gas-refund' of github.com:NibiruChain/nibiru into f…
onikonychev 1a9d256
Merge branch 'main' into fix/gas-refund
onikonychev b4c7bba
fix: minor test fix
onikonychev 0932e28
test: fixed tests after merge
onikonychev 404a5da
fix: getting current nonce for a specified address
onikonychev c35f125
Merge branch 'main' into fix/gas-refund
onikonychev 82e42e4
Merge branch 'main' into fix/gas-refund
Unique-Divine File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,180 @@ | ||
package backend_test | ||
|
||
import ( | ||
"math/big" | ||
|
||
"github.com/ethereum/go-ethereum/common/hexutil" | ||
gethcore "github.com/ethereum/go-ethereum/core/types" | ||
|
||
"github.com/NibiruChain/nibiru/v2/eth" | ||
"github.com/NibiruChain/nibiru/v2/eth/rpc" | ||
"github.com/NibiruChain/nibiru/v2/x/common/testutil" | ||
"github.com/NibiruChain/nibiru/v2/x/evm" | ||
"github.com/NibiruChain/nibiru/v2/x/evm/embeds" | ||
"github.com/NibiruChain/nibiru/v2/x/evm/evmtest" | ||
"github.com/NibiruChain/nibiru/v2/x/evm/precompile" | ||
) | ||
|
||
// TestGasUsedTransfers verifies that gas used is correctly calculated for simple transfers. | ||
// Test creates 2 eth transfer txs that are supposed to be included in the same block. | ||
// It checks that gas used is the same for both txs and the total block gas is greater than the sum of 2 gas used. | ||
func (s *BackendSuite) TestGasUsedTransfers() { | ||
// Start with new block | ||
s.Require().NoError(s.network.WaitForNextBlock()) | ||
balanceBefore := s.getUnibiBalance(s.fundedAccEthAddr) | ||
|
||
// Send 2 similar transfers | ||
randomEthAddr := evmtest.NewEthPrivAcc().EthAddr | ||
txHash1 := s.SendNibiViaEthTransfer(randomEthAddr, amountToSend, false) | ||
txHash2 := s.SendNibiViaEthTransfer(randomEthAddr, amountToSend, false) | ||
|
||
blockNumber1, _, receipt1 := WaitForReceipt(s, txHash1) | ||
blockNumber2, _, receipt2 := WaitForReceipt(s, txHash2) | ||
|
||
s.Require().NotNil(receipt1) | ||
s.Require().NotNil(receipt2) | ||
|
||
s.Require().Equal(gethcore.ReceiptStatusSuccessful, receipt1.Status) | ||
s.Require().Equal(gethcore.ReceiptStatusSuccessful, receipt2.Status) | ||
|
||
// Expect txs are included into one block | ||
s.Require().Equal(blockNumber1, blockNumber2) | ||
|
||
// Ensure that gas used is the same for both transactions | ||
s.Require().Equal(receipt1.GasUsed, receipt2.GasUsed) | ||
|
||
// Get block receipt and check gas used | ||
block, err := s.backend.GetBlockByNumber(rpc.NewBlockNumber(blockNumber1), false) | ||
s.Require().NoError(err) | ||
s.Require().NotNil(block) | ||
s.Require().NotNil(block["gasUsed"]) | ||
s.Require().GreaterOrEqual(block["gasUsed"].(*hexutil.Big).ToInt().Uint64(), receipt1.GasUsed+receipt2.GasUsed) | ||
|
||
// Balance after should be equal to balance before minus gas used and amount sent | ||
balanceAfter := s.getUnibiBalance(s.fundedAccEthAddr) | ||
s.Require().Equal( | ||
receipt1.GasUsed+receipt2.GasUsed+2, | ||
evm.WeiToNative(balanceBefore.ToInt()).Uint64()-evm.WeiToNative(balanceAfter.ToInt()).Uint64(), | ||
) | ||
} | ||
|
||
// TestGasUsedFunTokens verifies that gas used is correctly calculated for precompile "sendToBank" txs. | ||
// Test creates 3 txs: 2 successful and one failing. | ||
// Successful txs gas should be refunded and failing tx should consume 100% of the gas limit. | ||
// It also checks that txs are included in the same block and block gas is greater or equals | ||
// to the total gas used by txs. | ||
func (s *BackendSuite) TestGasUsedFunTokens() { | ||
// Create funtoken from erc20 | ||
erc20Addr, err := eth.NewEIP55AddrFromStr(testContractAddress.String()) | ||
s.Require().NoError(err) | ||
|
||
_, err = s.backend.GetTransactionCount(s.fundedAccEthAddr, rpc.EthPendingBlockNumber) | ||
s.Require().NoError(err) | ||
|
||
txResp, err := s.network.BroadcastMsgs(s.node.Address, &evm.MsgCreateFunToken{ | ||
Sender: s.node.Address.String(), | ||
FromErc20: &erc20Addr, | ||
}) | ||
s.Require().NoError(err) | ||
s.Require().NotNil(txResp) | ||
s.Require().NoError(s.network.WaitForNextBlock()) | ||
|
||
randomNibiAddress := testutil.AccAddress() | ||
packedArgsPass, err := embeds.SmartContract_FunToken.ABI.Pack( | ||
"sendToBank", | ||
erc20Addr.Address, | ||
big.NewInt(1), | ||
randomNibiAddress.String(), | ||
) | ||
s.Require().NoError(err) | ||
|
||
nonce, err := s.backend.GetTransactionCount(s.fundedAccEthAddr, rpc.EthPendingBlockNumber) | ||
s.Require().NoError(err) | ||
|
||
balanceBefore := s.getUnibiBalance(s.fundedAccEthAddr) | ||
|
||
txHash1 := SendTransaction( | ||
s, | ||
&gethcore.LegacyTx{ | ||
Nonce: uint64(*nonce), | ||
To: &precompile.PrecompileAddr_FunToken, | ||
Data: packedArgsPass, | ||
Gas: 1_500_000, | ||
GasPrice: big.NewInt(1), | ||
}, | ||
false, | ||
) | ||
|
||
packedArgsFail, err := embeds.SmartContract_FunToken.ABI.Pack( | ||
"sendToBank", | ||
erc20Addr.Address, | ||
big.NewInt(1), | ||
"invalidAddress", | ||
) | ||
s.Require().NoError(err) | ||
txHash2 := SendTransaction( // should fail due to invalid recipient address | ||
s, | ||
&gethcore.LegacyTx{ | ||
Nonce: uint64(*nonce + 1), | ||
To: &precompile.PrecompileAddr_FunToken, | ||
Data: packedArgsFail, | ||
Gas: 1_500_000, | ||
GasPrice: big.NewInt(1), | ||
}, | ||
false, | ||
) | ||
txHash3 := SendTransaction( | ||
s, | ||
&gethcore.LegacyTx{ | ||
Nonce: uint64(*nonce + 2), | ||
To: &precompile.PrecompileAddr_FunToken, | ||
Data: packedArgsPass, | ||
Gas: 1_500_000, | ||
GasPrice: big.NewInt(1), | ||
}, | ||
false, | ||
) | ||
blockNumber1, _, receipt1 := WaitForReceipt(s, txHash1) | ||
blockNumber2, _, receipt2 := WaitForReceipt(s, txHash2) | ||
blockNumber3, _, receipt3 := WaitForReceipt(s, txHash3) | ||
|
||
s.Require().NotNil(receipt1) | ||
s.Require().NotNil(receipt2) | ||
s.Require().NotNil(receipt3) | ||
|
||
s.Require().NotNil(blockNumber1) | ||
s.Require().NotNil(blockNumber2) | ||
s.Require().NotNil(blockNumber3) | ||
|
||
// TXs should have been included in the same block | ||
s.Require().Equal(blockNumber1, blockNumber2) | ||
s.Require().Equal(blockNumber2, blockNumber3) | ||
|
||
// 1 and 3 should pass and 2 should fail | ||
s.Require().Equal(gethcore.ReceiptStatusSuccessful, receipt1.Status) | ||
s.Require().Equal(gethcore.ReceiptStatusFailed, receipt2.Status) | ||
s.Require().Equal(gethcore.ReceiptStatusSuccessful, receipt3.Status) | ||
|
||
// TX 1 and 3 should have gas used lower than specified gas limit | ||
s.Require().Less(receipt1.GasUsed, uint64(500_000)) | ||
s.Require().Less(receipt3.GasUsed, uint64(500_000)) | ||
|
||
// TX 2 should have gas used equal to specified gas limit as it failed | ||
s.Require().Equal(uint64(1_500_000), receipt2.GasUsed) | ||
|
||
block, err := s.backend.GetBlockByNumber(rpc.NewBlockNumber(blockNumber1), false) | ||
s.Require().NoError(err) | ||
s.Require().NotNil(block) | ||
s.Require().NotNil(block["gasUsed"]) | ||
s.Require().GreaterOrEqual( | ||
block["gasUsed"].(*hexutil.Big).ToInt().Uint64(), | ||
receipt1.GasUsed+receipt2.GasUsed+receipt3.GasUsed, | ||
) | ||
|
||
// Balance after should be equal to balance before minus gas used | ||
balanceAfter := s.getUnibiBalance(s.fundedAccEthAddr) | ||
s.Require().Equal( | ||
receipt1.GasUsed+receipt2.GasUsed+receipt3.GasUsed, | ||
evm.WeiToNative(balanceBefore.ToInt()).Uint64()-evm.WeiToNative(balanceAfter.ToInt()).Uint64(), | ||
) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -72,22 +72,21 @@ | |
|
||
k.updateBlockBloom(ctx, evmResp, uint64(txConfig.LogIndex)) | ||
|
||
blockGasUsed, err := k.AddToBlockGasUsed(ctx, evmResp.GasUsed) | ||
if err != nil { | ||
return nil, errors.Wrap(err, "error adding transient gas used to block") | ||
} | ||
|
||
// refund gas in order to match the Ethereum gas consumption instead of the | ||
// default SDK one. | ||
refundGas := uint64(0) | ||
if evmMsg.Gas() > blockGasUsed { | ||
refundGas = evmMsg.Gas() - blockGasUsed | ||
if evmMsg.Gas() > evmResp.GasUsed { | ||
refundGas = evmMsg.Gas() - evmResp.GasUsed | ||
} | ||
weiPerGas := txMsg.EffectiveGasPriceWeiPerGas(evmConfig.BaseFeeWei) | ||
if err = k.RefundGas(ctx, evmMsg.From(), refundGas, weiPerGas); err != nil { | ||
return nil, errors.Wrapf(err, "error refunding leftover gas to sender %s", evmMsg.From()) | ||
} | ||
|
||
blockGasUsed, err := k.AddToBlockGasUsed(ctx, evmResp.GasUsed) | ||
if err != nil { | ||
return nil, errors.Wrap(err, "error adding transient gas used to block") | ||
} | ||
// reset the gas meter for current TxMsg (EthereumTx) | ||
k.ResetGasMeterAndConsumeGas(ctx, blockGasUsed) | ||
|
||
|
@@ -563,8 +562,15 @@ | |
coin.Amount.BigInt(), | ||
) | ||
if err != nil { | ||
k.ResetGasMeterAndConsumeGas(ctx, ctx.GasMeter().Limit()) | ||
return nil, err | ||
} | ||
blockGasUsed, errBlockGasUsed := k.AddToBlockGasUsed(ctx, evmResp.GasUsed) | ||
if errBlockGasUsed != nil { | ||
return nil, errors.Wrap(errBlockGasUsed, "error adding transient gas used") | ||
} | ||
k.ResetGasMeterAndConsumeGas(ctx, blockGasUsed) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Shouldn't we consume |
||
|
||
if evmResp.Failed() { | ||
return nil, | ||
fmt.Errorf("failed to mint erc-20 tokens of contract %s", erc20Addr.String()) | ||
|
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Assess potential error impact on block gas used.
This snippet adds to the block’s total gas usage and then checks for errors. Confirm that an error during
AddToBlockGasUsed
or subsequent steps won’t accidentally skip the consumption of already-calculated usage, resulting in potential gas mismatch.