|
| 1 | +package backends_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "math/big" |
| 6 | + "testing" |
| 7 | + |
| 8 | + ethereum "github.com/ethereum/go-ethereum" |
| 9 | + "github.com/ethereum/go-ethereum/accounts/abi/bind" |
| 10 | + "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" |
| 11 | + "github.com/ethereum/go-ethereum/common" |
| 12 | + "github.com/ethereum/go-ethereum/core" |
| 13 | + "github.com/ethereum/go-ethereum/core/types" |
| 14 | + "github.com/ethereum/go-ethereum/crypto" |
| 15 | +) |
| 16 | + |
| 17 | +func TestSimulatedBackend(t *testing.T) { |
| 18 | + var gasLimit uint64 = 8000029 |
| 19 | + key, _ := crypto.GenerateKey() // nolint: gosec |
| 20 | + auth := bind.NewKeyedTransactor(key) |
| 21 | + genAlloc := make(core.GenesisAlloc) |
| 22 | + genAlloc[auth.From] = core.GenesisAccount{Balance: big.NewInt(9223372036854775807)} |
| 23 | + |
| 24 | + sim := backends.NewSimulatedBackend(genAlloc, gasLimit) |
| 25 | + |
| 26 | + // should return an error if the tx is not found |
| 27 | + txHash := common.HexToHash("2") |
| 28 | + _, isPending, err := sim.TransactionByHash(context.Background(), txHash) |
| 29 | + |
| 30 | + if isPending { |
| 31 | + t.Fatal("transaction should not be pending") |
| 32 | + } |
| 33 | + if err != ethereum.NotFound { |
| 34 | + t.Fatalf("err should be `ethereum.NotFound` but received %v", err) |
| 35 | + } |
| 36 | + |
| 37 | + // generate a transaction and confirm you can retrieve it |
| 38 | + code := `6060604052600a8060106000396000f360606040526008565b00` |
| 39 | + var gas uint64 = 3000000 |
| 40 | + tx := types.NewContractCreation(0, big.NewInt(0), gas, big.NewInt(1), common.FromHex(code)) |
| 41 | + tx, _ = types.SignTx(tx, types.HomesteadSigner{}, key) |
| 42 | + |
| 43 | + err = sim.SendTransaction(context.Background(), tx) |
| 44 | + if err != nil { |
| 45 | + t.Fatal("error sending transaction") |
| 46 | + } |
| 47 | + |
| 48 | + txHash = tx.Hash() |
| 49 | + _, isPending, err = sim.TransactionByHash(context.Background(), txHash) |
| 50 | + if err != nil { |
| 51 | + t.Fatalf("error getting transaction with hash: %v", txHash.String()) |
| 52 | + } |
| 53 | + if !isPending { |
| 54 | + t.Fatal("transaction should have pending status") |
| 55 | + } |
| 56 | + |
| 57 | + sim.Commit() |
| 58 | + tx, isPending, err = sim.TransactionByHash(context.Background(), txHash) |
| 59 | + if err != nil { |
| 60 | + t.Fatalf("error getting transaction with hash: %v", txHash.String()) |
| 61 | + } |
| 62 | + if isPending { |
| 63 | + t.Fatal("transaction should not have pending status") |
| 64 | + } |
| 65 | + |
| 66 | +} |
0 commit comments