ethereumproject / go-ethereum

Go language implementation of the original/classic design of the Ethereum protocol
GNU Lesser General Public License v3.0
441 stars 166 forks source link

With SimulatedBackend, how do we know the pending block number and "nonce"? #680

Closed akasandra closed 5 years ago

akasandra commented 5 years ago

In my golang program,

I am trying to take use function:

// BalanceAt returns the wei balance of a certain account in the blockchain.
func (b *SimulatedBackend) BalanceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (*big.Int, error) {

From simulated.go, there is a mention of pendingBlock, which could be used to know the block number:

// Commit imports all the pending transactions as a single block and starts a
// fresh new state.
func (b *SimulatedBackend) Commit() {
    b.mu.Lock()
    defer b.mu.Unlock()

    if _, err := b.blockchain.InsertChain([]*types.Block{b.pendingBlock}); err != nil {
        panic(err) // This cannot happen unless the simulator is wrong, fail in that case
    }
    b.rollback()
}

However, pendingBlock, blockchain and other things are not exported for public use, and i do not see a way to know the block number for SimulatedBackend in order to know balance of some address.

The same situation with nonce, SendTransaction() requires nonce, but the only way i've found is to create local managed counter and increment after every transaction.

Is this all intended implementation or what's wrong for me?

akasandra commented 5 years ago

For last block number, use nil as block number.

To get current nonce, use:

nonce, err := sim.PendingNonceAt(context.TODO(), sender.PublicKey())