|
| 1 | +package base |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + |
| 6 | + sdk "github.com/cosmos/cosmos-sdk/types" |
| 7 | + sdkmempool "github.com/cosmos/cosmos-sdk/types/mempool" |
| 8 | +) |
| 9 | + |
| 10 | +var ( |
| 11 | + _ MempoolInterface = (*DefaultMempool[int64])(nil) |
| 12 | + _ sdkmempool.Iterator = (*DefaultIterator)(nil) |
| 13 | +) |
| 14 | + |
| 15 | +// DefaultMempool implements a simple mempool that stores all transactions |
| 16 | +type DefaultMempool[C comparable] struct { |
| 17 | + txs []sdk.Tx |
| 18 | + MaxTx int |
| 19 | +} |
| 20 | + |
| 21 | +// NewDefaultMempool creates a new DefaultMempool |
| 22 | +func NewDefaultMempool[C comparable](maxTxs int) *DefaultMempool[C] { |
| 23 | + return &DefaultMempool[C]{ |
| 24 | + txs: make([]sdk.Tx, 0), |
| 25 | + MaxTx: maxTxs, |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +// Insert implements MempoolInterface. |
| 30 | +func (mp *DefaultMempool[C]) Insert(_ context.Context, tx sdk.Tx) error { |
| 31 | + if mp.MaxTx > 0 && mp.CountTx() >= mp.MaxTx { |
| 32 | + return sdkmempool.ErrMempoolTxMaxCapacity |
| 33 | + } else if mp.MaxTx < 0 { |
| 34 | + return nil |
| 35 | + } |
| 36 | + mp.txs = append(mp.txs, tx) |
| 37 | + return nil |
| 38 | +} |
| 39 | + |
| 40 | +// Remove implements MempoolInterface. |
| 41 | +func (mp *DefaultMempool[C]) Remove(tx sdk.Tx) error { |
| 42 | + for i, t := range mp.txs { |
| 43 | + if t == tx { |
| 44 | + mp.txs = append(mp.txs[:i], mp.txs[i+1:]...) |
| 45 | + return nil |
| 46 | + } |
| 47 | + } |
| 48 | + return nil |
| 49 | +} |
| 50 | + |
| 51 | +// Select implements MempoolInterface. |
| 52 | +func (mp *DefaultMempool[C]) Select(_ context.Context, _ [][]byte) sdkmempool.Iterator { |
| 53 | + if len(mp.txs) == 0 { |
| 54 | + return nil |
| 55 | + } |
| 56 | + |
| 57 | + return &DefaultIterator{ |
| 58 | + txs: mp.txs, |
| 59 | + curr: 0, |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +// CountTx implements MempoolInterface. |
| 64 | +func (mp *DefaultMempool[C]) CountTx() int { |
| 65 | + return len(mp.txs) |
| 66 | +} |
| 67 | + |
| 68 | +// Contains implements MempoolInterface. |
| 69 | +func (mp *DefaultMempool[C]) Contains(tx sdk.Tx) bool { |
| 70 | + for _, t := range mp.txs { |
| 71 | + if t == tx { |
| 72 | + return true |
| 73 | + } |
| 74 | + } |
| 75 | + return false |
| 76 | +} |
| 77 | + |
| 78 | +// DefaultIterator implements sdkmempool.Iterator |
| 79 | +type DefaultIterator struct { |
| 80 | + txs []sdk.Tx |
| 81 | + curr int |
| 82 | +} |
| 83 | + |
| 84 | +// Next implements sdkmempool.Iterator |
| 85 | +func (i *DefaultIterator) Next() sdkmempool.Iterator { |
| 86 | + if i.curr >= len(i.txs)-1 { |
| 87 | + return nil |
| 88 | + } |
| 89 | + i.curr++ |
| 90 | + return i |
| 91 | +} |
| 92 | + |
| 93 | +// Tx implements sdkmempool.Iterator |
| 94 | +func (i *DefaultIterator) Tx() sdk.Tx { |
| 95 | + return i.txs[i.curr] |
| 96 | +} |
0 commit comments