This repository has been archived by the owner on Jan 19, 2022. It is now read-only.
/
mock_ethereum.go
78 lines (67 loc) · 1.95 KB
/
mock_ethereum.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package sdk
import (
"context"
"github.com/ethereum/go-ethereum/accounts/abi/bind/backends"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/event"
"math/big"
)
type MockEthereum struct {
ctx context.Context
cancel context.CancelFunc
Backend *MockBackend
}
func NewMockEthereum() *MockEthereum {
return &MockEthereum{Backend: NewMockBackend()}
}
func (eth *MockEthereum) Start() {
eth.ctx, eth.cancel = context.WithCancel(context.Background())
go func() {
txCh := make(chan *types.Transaction, 1)
sub := eth.Backend.SubscribeNewTransaction(txCh)
defer sub.Unsubscribe()
// mine block when there is transaction
for {
select {
case <-eth.ctx.Done():
return
case <-txCh:
eth.Backend.Commit()
}
}
}()
}
func (eth *MockEthereum) Stop() {
eth.cancel()
}
type MockBackend struct {
*backends.SimulatedBackend
newTxFeed event.Feed
}
func NewMockBackend() *MockBackend {
balance := new(big.Int)
balance.SetString("100000000000000000000", 10) // 100 eth in wei
genesisAlloc := make(map[common.Address]core.GenesisAccount)
for _, privateKey := range PredefinedPrivateKeys {
account, _ := retrieveAccount(privateKey)
genesisAlloc[account.address] = core.GenesisAccount{Balance: balance}
}
blockGasLimit := uint64(4712388)
backend := backends.NewSimulatedBackend(genesisAlloc, blockGasLimit)
mock := &MockBackend{SimulatedBackend: backend}
return mock
}
func (b *MockBackend) SendTransaction(ctx context.Context, tx *types.Transaction) error {
// previous transactions must have been committed
b.newTxFeed.Send(tx)
err := b.SimulatedBackend.SendTransaction(ctx, tx)
return err
}
func (b *MockBackend) SubscribeNewTransaction(ch chan *types.Transaction) event.Subscription {
return b.newTxFeed.Subscribe(ch)
}
func (b *MockBackend) NetworkID(ctx context.Context) (*big.Int, error) {
return big.NewInt(2020), nil
}