github.com/amazechain/amc@v0.1.3/internal/txspool/read_state.go (about) 1 package txspool 2 3 import ( 4 "context" 5 "github.com/amazechain/amc/common/account" 6 "github.com/amazechain/amc/common/types" 7 "github.com/amazechain/amc/modules" 8 "github.com/holiman/uint256" 9 "github.com/ledgerwatch/erigon-lib/kv" 10 ) 11 12 type ReadState interface { 13 GetNonce(types.Address) uint64 14 GetBalance(types.Address) *uint256.Int 15 State(types.Address) (*account.StateAccount, error) 16 } 17 18 type StateCli struct { 19 db kv.RoDB 20 ctx context.Context 21 } 22 23 func StateClient(ctx context.Context, db kv.RoDB) ReadState { 24 return &StateCli{ 25 db: db, 26 ctx: ctx, 27 } 28 } 29 30 func (c *StateCli) GetNonce(addr types.Address) uint64 { 31 var nonce uint64 32 _ = c.db.View(c.ctx, func(tx kv.Tx) error { 33 v, err := tx.GetOne(modules.Account, addr.Bytes()) 34 if err != nil { 35 return err 36 } 37 if len(v) == 0 { 38 return nil 39 } 40 sc := new(account.StateAccount) 41 if err := sc.DecodeForStorage(v); nil != err { 42 return err 43 } 44 nonce = uint64(sc.Nonce) 45 return nil 46 }) 47 return nonce 48 } 49 50 func (c *StateCli) GetBalance(addr types.Address) *uint256.Int { 51 balance := uint256.NewInt(0) 52 _ = c.db.View(c.ctx, func(tx kv.Tx) error { 53 v, err := tx.GetOne(modules.Account, addr.Bytes()) 54 if err != nil { 55 return err 56 } 57 if len(v) == 0 { 58 return nil 59 } 60 sc := new(account.StateAccount) 61 if err := sc.DecodeForStorage(v); nil != err { 62 return err 63 } 64 balance = &sc.Balance 65 return nil 66 }) 67 return balance 68 } 69 func (c *StateCli) State(addr types.Address) (*account.StateAccount, error) { 70 s := new(account.StateAccount) 71 err := c.db.View(c.ctx, func(tx kv.Tx) error { 72 v, err := tx.GetOne(modules.Account, addr.Bytes()) 73 if err != nil { 74 return err 75 } 76 if len(v) == 0 { 77 return nil 78 } 79 80 if err := s.DecodeForStorage(v); nil != err { 81 return err 82 } 83 return nil 84 }) 85 return s, err 86 }