Skip to content

Commit f1ce12e

Browse files
committed
Fixed PR_REVIEW notes, added helpers for tracing transfer
1 parent 275caec commit f1ce12e

File tree

10 files changed

+152
-96
lines changed

10 files changed

+152
-96
lines changed

app/app.go

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -631,12 +631,7 @@ func New(
631631
}
632632

633633
if app.evmRPCConfig.LiveEVMTracer != "" {
634-
// PR_REVIEW_NOTE: So I moved this code from `ProcessBlock` and there, I had access to `ctx` so the code was actually looking
635-
// like `evmtypes.DefaultChainConfig().EthereumConfig(app.EvmKeeper.ChainID(ctx))`. But here, I don't have access to `ctx`
636-
// Is there another mean to get the EVM chainID from here? I need it to call `OnSeiBlockchainInit` on the logger,
637-
// so another solution would be to call this one later when EVM chainID is known. Last resort, we have a sync.Once
638-
// that we can use to call it only once.
639-
chainConfig := evmtypes.DefaultChainConfig().EthereumConfig(big.NewInt(int64(app.evmRPCConfig.LiveEVMTracerChainID)))
634+
chainConfig := evmtypes.DefaultChainConfig().EthereumConfig(app.EvmKeeper.ChainID())
640635
evmTracer, err := evmtracers.NewBlockchainTracer(evmtracers.GlobalLiveTracerRegistry, app.evmRPCConfig.LiveEVMTracer, chainConfig)
641636
if err != nil {
642637
panic(fmt.Sprintf("error creating EVM tracer due to %s", err))

evmrpc/config.go

Lines changed: 8 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -56,19 +56,9 @@ type Config struct {
5656
// The EVM tracer to use when doing node synchronization, applies to
5757
// all block produced but traces only EVM transactions.
5858
//
59-
// Refer to <TBC> for registered tracers
60-
//
61-
// PR_REVIEW_NOTE: It his an acceptable way of documenting the available tracers?
62-
// PR_REVIEW_NOTE: This section renders as `[evm]` in config but is named EVMRPC on top,
63-
// is live tracing of block synchronization should be here? Maybe "higher"
64-
// in the config hierarchy? We might think also about a way that later, we could
65-
// different trace active for Cosmos related function and EVM related function.
59+
// Refer to x/evm/tracers/registry.go#GlobalLiveTracerRegistry for registered tracers.
6660
LiveEVMTracer string `mapstructure:"live_evm_tracer"`
6761

68-
// PR_REVIEW_NOTE: This is a hackish workaround because I didn't how to get it in `app/app.go#New`,
69-
// this will not be part of the final PR.
70-
LiveEVMTracerChainID int `mapstructure:"live_evm_tracer_chain_id"`
71-
7262
// list of CORS allowed origins, separated by comma
7363
CORSOrigins string `mapstructure:"cors_origins"`
7464

@@ -108,6 +98,7 @@ var DefaultConfig = Config{
10898
IdleTimeout: rpc.DefaultHTTPTimeouts.IdleTimeout,
10999
SimulationGasLimit: 10_000_000, // 10M
110100
SimulationEVMTimeout: 60 * time.Second,
101+
LiveEVMTracer: "",
111102
CORSOrigins: "*",
112103
WSOrigins: "*",
113104
FilterTimeout: 120 * time.Second,
@@ -130,6 +121,7 @@ const (
130121
flagIdleTimeout = "evm.idle_timeout"
131122
flagSimulationGasLimit = "evm.simulation_gas_limit"
132123
flagSimulationEVMTimeout = "evm.simulation_evm_timeout"
124+
flagLiveEVMTracer = "evm.live_evm_tracer"
133125
flagCORSOrigins = "evm.cors_origins"
134126
flagWSOrigins = "evm.ws_origins"
135127
flagFilterTimeout = "evm.filter_timeout"
@@ -139,9 +131,6 @@ const (
139131
flagDenyList = "evm.deny_list"
140132
flagMaxLogNoBlock = "evm.max_log_no_block"
141133
flagMaxBlocksForLog = "evm.max_blocks_for_log"
142-
flagLiveEVMTracer = "evm.live_evm_tracer"
143-
// PR_REVIEW_NOTE: This is going to go away, temporary hack
144-
flagLiveEVMTracerChainID = "evm.live_evm_tracer_chain_id"
145134
)
146135

147136
func ReadConfig(opts servertypes.AppOptions) (Config, error) {
@@ -197,6 +186,11 @@ func ReadConfig(opts servertypes.AppOptions) (Config, error) {
197186
return cfg, err
198187
}
199188
}
189+
if v := opts.Get(flagLiveEVMTracer); v != nil {
190+
if cfg.LiveEVMTracer, err = cast.ToStringE(v); err != nil {
191+
return cfg, err
192+
}
193+
}
200194
if v := opts.Get(flagCORSOrigins); v != nil {
201195
if cfg.CORSOrigins, err = cast.ToStringE(v); err != nil {
202196
return cfg, err
@@ -242,16 +236,6 @@ func ReadConfig(opts servertypes.AppOptions) (Config, error) {
242236
return cfg, err
243237
}
244238
}
245-
if v := opts.Get(flagLiveEVMTracer); v != nil {
246-
if cfg.LiveEVMTracer, err = cast.ToStringE(v); err != nil {
247-
return cfg, err
248-
}
249-
}
250-
if v := opts.Get(flagLiveEVMTracerChainID); v != nil {
251-
if cfg.LiveEVMTracerChainID, err = cast.ToIntE(v); err != nil {
252-
return cfg, err
253-
}
254-
}
255239

256240
return cfg, nil
257241
}

evmrpc/config_test.go

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ type opts struct {
2020
idleTimeout interface{}
2121
simulationGasLimit interface{}
2222
simulationEVMTimeout interface{}
23+
liveEVMTracer interface{}
2324
corsOrigins interface{}
2425
wsOrigins interface{}
2526
filterTimeout interface{}
@@ -29,8 +30,6 @@ type opts struct {
2930
denyList interface{}
3031
maxLogNoBlock interface{}
3132
maxBlocksForLog interface{}
32-
liveEVMTracer interface{}
33-
liveEVMTracerChainID interface{}
3433
}
3534

3635
func (o *opts) Get(k string) interface{} {
@@ -64,6 +63,9 @@ func (o *opts) Get(k string) interface{} {
6463
if k == "evm.simulation_evm_timeout" {
6564
return o.simulationEVMTimeout
6665
}
66+
if k == "evm.live_evm_tracer" {
67+
return o.liveEVMTracer
68+
}
6769
if k == "evm.cors_origins" {
6870
return o.corsOrigins
6971
}
@@ -91,12 +93,6 @@ func (o *opts) Get(k string) interface{} {
9193
if k == "evm.max_blocks_for_log" {
9294
return o.maxBlocksForLog
9395
}
94-
if k == "evm.live_evm_tracer" {
95-
return o.liveEVMTracer
96-
}
97-
if k == "evm.live_evm_tracer_chain_id" {
98-
return o.liveEVMTracerChainID
99-
}
10096
panic(fmt.Errorf("unknown key: %s", k))
10197
}
10298

@@ -114,15 +110,14 @@ func TestReadConfig(t *testing.T) {
114110
time.Duration(60),
115111
"",
116112
"",
113+
"",
117114
time.Duration(5),
118115
time.Duration(5),
119116
1000,
120117
false,
121118
make([]string, 0),
122119
20000,
123120
1000,
124-
"",
125-
0,
126121
}
127122
_, err := evmrpc.ReadConfig(&goodOpts)
128123
require.Nil(t, err)

precompiles/bank/bank.go

Lines changed: 10 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import (
1010
sdk "github.com/cosmos/cosmos-sdk/types"
1111
"github.com/ethereum/go-ethereum/accounts/abi"
1212
"github.com/ethereum/go-ethereum/common"
13-
"github.com/ethereum/go-ethereum/core/tracing"
1413
"github.com/ethereum/go-ethereum/core/vm"
1514
pcommon "github.com/sei-protocol/sei-chain/precompiles/common"
1615
"github.com/sei-protocol/sei-chain/utils"
@@ -225,46 +224,28 @@ func (p Precompile) sendNative(ctx sdk.Context, method *abi.Method, args []inter
225224
return nil, err
226225
}
227226

228-
usei, wei, err := pcommon.HandlePaymentUseiWei(ctx, p.evmKeeper.GetSeiAddressOrDefault(ctx, p.address), senderSeiAddr, value, p.bankKeeper)
227+
precompiledSeiAddr := p.evmKeeper.GetSeiAddressOrDefault(ctx, p.address)
228+
229+
usei, wei, err := pcommon.HandlePaymentUseiWei(ctx, precompiledSeiAddr, senderSeiAddr, value, p.bankKeeper)
229230
if err != nil {
230231
return nil, err
231232
}
232233

233-
if hooks := tracers.GetCtxEthTracingHooks(ctx); hooks != nil && hooks.OnBalanceChange != nil && !wei.IsZero() {
234-
// Precompile address got wei removed from it
235-
newBalance := p.bankKeeper.GetWeiBalance(ctx, p.evmKeeper.GetSeiAddressOrDefault(ctx, p.address)).BigInt()
236-
oldBalance := new(big.Int).Add(newBalance, wei.BigInt())
237-
238-
hooks.OnBalanceChange(p.address, oldBalance, newBalance, tracing.BalanceChangeTransfer)
239-
240-
// Sender received wei from the precompile address
241-
newBalance = p.bankKeeper.GetWeiBalance(ctx, senderSeiAddr).BigInt()
242-
oldBalance = new(big.Int).Sub(newBalance, wei.BigInt())
243-
244-
hooks.OnBalanceChange(caller, oldBalance, newBalance, tracing.BalanceChangeTransfer)
234+
if hooks := tracers.GetCtxEthTracingHooks(ctx); hooks != nil && hooks.OnBalanceChange != nil && (value.Sign() != 0) {
235+
tracers.TraceTransferEVMValue(ctx, hooks, p.bankKeeper, precompiledSeiAddr, p.address, senderSeiAddr, caller, value)
245236
}
246237

247238
if err := p.bankKeeper.SendCoinsAndWei(ctx, senderSeiAddr, receiverSeiAddr, usei, wei); err != nil {
248239
return nil, err
249240
}
250241

251-
if hooks := tracers.GetCtxEthTracingHooks(ctx); hooks != nil && hooks.OnBalanceChange != nil && !wei.IsZero() {
252-
// Sender address got wei removed from it
253-
newBalance := p.bankKeeper.GetWeiBalance(ctx, senderSeiAddr).BigInt()
254-
oldBalance := new(big.Int).Add(newBalance, wei.BigInt())
255-
256-
hooks.OnBalanceChange(caller, oldBalance, newBalance, tracing.BalanceChangeTransfer)
257-
258-
// Receiver received wei from the sender address
259-
evmReceiverAddr, err := p.evmKeeper.GetEVMAddressFromBech32OrDefault(ctx, receiverAddr)
260-
if err != nil {
261-
panic(fmt.Errorf("failed to get EVM address from Sei bech32 address input %q, this shouldn't happen at this point since SendCoinsAndWei above worked: %w", receiverAddr, err))
242+
if hooks := tracers.GetCtxEthTracingHooks(ctx); hooks != nil && hooks.OnBalanceChange != nil && (value.Sign() != 0) {
243+
receveirEvmAddr, found := p.evmKeeper.GetEVMAddress(ctx, receiverSeiAddr)
244+
if !found {
245+
return nil, fmt.Errorf("sei address %s is not associated, this shouldn't happen at this point since SendCoinsAndWei above worked", receiverSeiAddr)
262246
}
263247

264-
newBalance = p.bankKeeper.GetWeiBalance(ctx, receiverSeiAddr).BigInt()
265-
oldBalance = new(big.Int).Sub(newBalance, wei.BigInt())
266-
267-
hooks.OnBalanceChange(evmReceiverAddr, oldBalance, newBalance, tracing.BalanceChangeTransfer)
248+
tracers.TraceTransferEVMValue(ctx, hooks, p.bankKeeper, senderSeiAddr, caller, receiverSeiAddr, receveirEvmAddr, value)
268249
}
269250

270251
return method.Outputs.Pack(true)

precompiles/bank/bank_test.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"github.com/cosmos/cosmos-sdk/types/tx/signing"
1313
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
1414
"github.com/ethereum/go-ethereum/common"
15+
ethtracing "github.com/ethereum/go-ethereum/core/tracing"
1516
ethtypes "github.com/ethereum/go-ethereum/core/types"
1617
"github.com/ethereum/go-ethereum/core/vm"
1718
"github.com/ethereum/go-ethereum/crypto"
@@ -20,6 +21,8 @@ import (
2021
"github.com/sei-protocol/sei-chain/x/evm/ante"
2122
"github.com/sei-protocol/sei-chain/x/evm/keeper"
2223
"github.com/sei-protocol/sei-chain/x/evm/state"
24+
"github.com/sei-protocol/sei-chain/x/evm/tracers"
25+
"github.com/sei-protocol/sei-chain/x/evm/tracing"
2326
"github.com/sei-protocol/sei-chain/x/evm/types"
2427
"github.com/sei-protocol/sei-chain/x/evm/types/ethtx"
2528
"github.com/stretchr/testify/require"
@@ -39,7 +42,18 @@ func (tx mockTx) GetSignaturesV2() ([]signing.SignatureV2, error) { return nil,
3942

4043
func TestRun(t *testing.T) {
4144
testApp := testkeeper.EVMTestApp
45+
46+
var balanceChanges []balanceChange
47+
4248
ctx := testApp.NewContext(false, tmtypes.Header{}).WithBlockHeight(2)
49+
ctx = tracers.SetCtxBlockchainTracer(ctx, &tracing.Hooks{
50+
Hooks: &ethtracing.Hooks{
51+
OnBalanceChange: func(addr common.Address, prev, new *big.Int, reason ethtracing.BalanceChangeReason) {
52+
balanceChanges = append(balanceChanges, balanceChange{prev.String(), new.String()})
53+
},
54+
},
55+
})
56+
4357
k := &testApp.EvmKeeper
4458

4559
// Setup sender addresses and environment
@@ -137,6 +151,15 @@ func TestRun(t *testing.T) {
137151
require.Nil(t, err)
138152
require.Empty(t, res.VmError)
139153

154+
// Test balance changes, there is 8 but we care about the first 4 here
155+
require.Equal(t, 8, len(balanceChanges))
156+
require.Equal(t, []balanceChange{
157+
{"9800000000000000000", "9799989999999999900"},
158+
{"0", "10000000000100"},
159+
{"10000000000100", "0"},
160+
{"9799989999999999900", "9800000000000000000"},
161+
}, balanceChanges[0:4], "balance changes do not match, actual are:\n\n%s", balanceChangesValues(balanceChanges[0:4]))
162+
140163
evts := ctx.EventManager().ABCIEvents()
141164

142165
for _, evt := range evts {
@@ -289,3 +312,19 @@ func TestAddress(t *testing.T) {
289312
require.Nil(t, err)
290313
require.Equal(t, common.HexToAddress(bank.BankAddress), p.Address())
291314
}
315+
316+
type balanceChange struct {
317+
// We use string to avoid big.Int equality issues
318+
old string
319+
new string
320+
}
321+
322+
func balanceChangesValues(changes []balanceChange) string {
323+
out := make([]string, len(changes))
324+
for i, change := range changes {
325+
out[i] = fmt.Sprintf("{%q, %q}", change.old, change.new)
326+
}
327+
328+
return strings.Join(out, "\n")
329+
330+
}

x/evm/module.go

Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,11 @@ import (
44
"encoding/json"
55
"fmt"
66
"math"
7-
"math/big"
87

98
// this line is used by starport scaffolding # 1
109

1110
"github.com/ethereum/go-ethereum/common"
1211
"github.com/ethereum/go-ethereum/core"
13-
"github.com/ethereum/go-ethereum/core/tracing"
1412
ethtypes "github.com/ethereum/go-ethereum/core/types"
1513
"github.com/ethereum/go-ethereum/core/vm"
1614
"github.com/gorilla/mux"
@@ -237,13 +235,11 @@ func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.Val
237235
panic(err)
238236
}
239237

240-
if evmHooks != nil && evmHooks.OnBalanceChange != nil && !weiBalance.IsZero() {
241-
// Only if the corresponding EVM address exists that we tracer the EVM balance change
242-
evmAddress := am.keeper.GetEVMAddressOrDefault(ctx, coinbaseAddress)
243-
newBalance := am.keeper.BankKeeper().GetWeiBalance(ctx, coinbaseAddress).BigInt()
244-
oldBalance := new(big.Int).Sub(newBalance, weiBalance.BigInt())
238+
if evmHooks != nil && evmHooks.OnBalanceChange != nil {
239+
fromEVMAddr := am.keeper.GetEVMAddressOrDefault(ctx, coinbaseAddress)
240+
toEVMAddr := am.keeper.GetEVMAddressOrDefault(ctx, coinbase)
245241

246-
evmHooks.OnBalanceChange(evmAddress, oldBalance, newBalance, tracing.BalanceIncreaseRewardTransactionFee)
242+
tracers.TraceTransferUseiAndWei(ctx, evmHooks, am.keeper.BankKeeper(), coinbaseAddress, fromEVMAddr, coinbase, toEVMAddr, balance, weiBalance)
247243
}
248244
}
249245
surplus = surplus.Add(deferredInfo.Surplus)
@@ -259,17 +255,13 @@ func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.Val
259255
if surplusWei.GT(sdk.ZeroInt()) {
260256
if err := am.keeper.BankKeeper().AddWei(ctx, evmModuleAddress, surplusWei); err != nil {
261257
ctx.Logger().Error("failed to send wei surplus of %s to EVM module account", surplusWei)
262-
} else {
263-
if evmHooks != nil && evmHooks.OnBalanceChange != nil {
264-
// Only if the corresponding EVM address exists that we tracer the EVM balance change
265-
evmAddress := am.keeper.GetEVMAddressOrDefault(ctx, evmModuleAddress)
266-
newBalance := am.keeper.BankKeeper().GetWeiBalance(ctx, evmModuleAddress).BigInt()
267-
oldBalance := new(big.Int).Sub(newBalance, surplusWei.BigInt())
268-
269-
evmHooks.OnBalanceChange(evmAddress, oldBalance, newBalance, tracing.BalanceIncreaseRewardMineBlock)
270-
}
271258
}
272259
}
260+
261+
if evmHooks != nil && evmHooks.OnBalanceChange != nil && (surplusUsei.GT(sdk.ZeroInt()) || surplusWei.GT(sdk.ZeroInt())) {
262+
tracers.TraceBlockReward(ctx, evmHooks, am.keeper.BankKeeper(), evmModuleAddress, am.keeper.GetEVMAddressOrDefault(ctx, evmModuleAddress), sdk.NewCoin(am.keeper.GetBaseDenom(ctx), surplusUsei), surplusWei)
263+
}
264+
273265
am.keeper.SetTxHashesOnHeight(ctx, ctx.BlockHeight(), utils.Map(evmTxDeferredInfoList, func(i keeper.EvmTxDeferredInfo) common.Hash { return i.TxHash }))
274266
am.keeper.SetBlockBloom(ctx, ctx.BlockHeight(), utils.Map(evmTxDeferredInfoList, func(i keeper.EvmTxDeferredInfo) ethtypes.Bloom { return i.TxBloom }))
275267
return []abci.ValidatorUpdate{}

x/evm/state/balance.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,6 @@ func (s *DBImpl) AddBalance(evmAddr common.Address, amt *big.Int, reason tracing
7676
}
7777

7878
if s.logger != nil && s.logger.OnBalanceChange != nil {
79-
// We could modify AddWei instead so it returns us the old/new balance directly.
8079
newBalance := s.GetBalance(evmAddr)
8180
oldBalance := new(big.Int).Sub(newBalance, amt)
8281

0 commit comments

Comments
 (0)