|
| 1 | +package stakingindex |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + |
| 6 | + "github.com/pkg/errors" |
| 7 | + |
| 8 | + "github.com/iotexproject/iotex-address/address" |
| 9 | + |
| 10 | + "github.com/iotexproject/iotex-core/v2/action/protocol" |
| 11 | + "github.com/iotexproject/iotex-core/v2/state" |
| 12 | +) |
| 13 | + |
| 14 | +var ( |
| 15 | + voteViewKeyPrefix = []byte("voteview") |
| 16 | + voteViewNS = state.StakingViewNamespace |
| 17 | +) |
| 18 | + |
| 19 | +// CandidateVotesManager defines the interface to manage candidate votes |
| 20 | +type CandidateVotesManager interface { |
| 21 | + Load(ctx context.Context, sr protocol.StateReader) (CandidateVotes, error) |
| 22 | + Store(ctx context.Context, sm protocol.StateManager, candVotes CandidateVotes) error |
| 23 | +} |
| 24 | + |
| 25 | +type candidateVotesManager struct { |
| 26 | + contractAddr address.Address |
| 27 | +} |
| 28 | + |
| 29 | +// NewCandidateVotesManager creates a new instance of CandidateVotesManager |
| 30 | +func NewCandidateVotesManager(contractAddr address.Address) CandidateVotesManager { |
| 31 | + return &candidateVotesManager{ |
| 32 | + contractAddr: contractAddr, |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +func (s *candidateVotesManager) Store(ctx context.Context, sm protocol.StateManager, candVotes CandidateVotes) error { |
| 37 | + if _, err := sm.PutState(candVotes, |
| 38 | + protocol.KeyOption(s.key()), |
| 39 | + protocol.NamespaceOption(voteViewNS), |
| 40 | + ); err != nil { |
| 41 | + return errors.Wrap(err, "failed to put candidate votes state") |
| 42 | + } |
| 43 | + return nil |
| 44 | +} |
| 45 | + |
| 46 | +func (s *candidateVotesManager) Load(ctx context.Context, sr protocol.StateReader) (CandidateVotes, error) { |
| 47 | + cur := newCandidateVotes() |
| 48 | + _, err := sr.State(cur, |
| 49 | + protocol.KeyOption(s.key()), |
| 50 | + protocol.NamespaceOption(voteViewNS), |
| 51 | + ) |
| 52 | + if err != nil { |
| 53 | + return nil, errors.Wrap(err, "failed to get candidate votes state") |
| 54 | + } |
| 55 | + return cur, nil |
| 56 | +} |
| 57 | + |
| 58 | +func (s *candidateVotesManager) key() []byte { |
| 59 | + return append(voteViewKeyPrefix, s.contractAddr.Bytes()...) |
| 60 | +} |
0 commit comments