Skip to content

Commit

Permalink
accounts/abi/bind/backends: add support for historical state (ethereu…
Browse files Browse the repository at this point in the history
  • Loading branch information
gzliudan committed Jan 10, 2025
1 parent 715dc3a commit 6ed5877
Showing 1 changed file with 28 additions and 12 deletions.
40 changes: 28 additions & 12 deletions accounts/abi/bind/backends/simulated.go
Original file line number Diff line number Diff line change
Expand Up @@ -209,15 +209,28 @@ func (b *SimulatedBackend) rollback() {
b.pendingState, _ = state.New(b.pendingBlock.Root(), statedb.Database())
}

// stateByBlockNumber retrieves a state by a given blocknumber.
func (b *SimulatedBackend) stateByBlockNumber(ctx context.Context, blockNumber *big.Int) (*state.StateDB, error) {
if blockNumber == nil || blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) == 0 {
return b.blockchain.State()
}
block, err := b.BlockByNumber(ctx, blockNumber)
if err != nil {
return nil, err
}
return b.blockchain.StateAt(block.Hash())
}

// CodeAt returns the code associated with a certain account in the blockchain.
func (b *SimulatedBackend) CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error) {
b.mu.Lock()
defer b.mu.Unlock()

if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
return nil, errBlockNumberUnsupported
statedb, err := b.stateByBlockNumber(ctx, blockNumber)
if err != nil {
return nil, err
}
statedb, _ := b.blockchain.State()

return statedb.GetCode(contract), nil
}

Expand All @@ -226,10 +239,11 @@ func (b *SimulatedBackend) BalanceAt(ctx context.Context, contract common.Addres
b.mu.Lock()
defer b.mu.Unlock()

if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
return nil, errBlockNumberUnsupported
statedb, err := b.stateByBlockNumber(ctx, blockNumber)
if err != nil {
return nil, err
}
statedb, _ := b.blockchain.State()

return statedb.GetBalance(contract), nil
}

Expand All @@ -238,10 +252,11 @@ func (b *SimulatedBackend) NonceAt(ctx context.Context, contract common.Address,
b.mu.Lock()
defer b.mu.Unlock()

if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
return 0, errBlockNumberUnsupported
statedb, err := b.stateByBlockNumber(ctx, blockNumber)
if err != nil {
return 0, err
}
statedb, _ := b.blockchain.State()

return statedb.GetNonce(contract), nil
}

Expand All @@ -250,10 +265,11 @@ func (b *SimulatedBackend) StorageAt(ctx context.Context, contract common.Addres
b.mu.Lock()
defer b.mu.Unlock()

if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
return nil, errBlockNumberUnsupported
statedb, err := b.stateByBlockNumber(ctx, blockNumber)
if err != nil {
return nil, err
}
statedb, _ := b.blockchain.State()

val := statedb.GetState(contract, key)
return val[:], nil
}
Expand Down

0 comments on commit 6ed5877

Please sign in to comment.