Skip to content

Commit 3ba1b80

Browse files
authored
Merge pull request #841 from jshufro/jms/modularstate
More modular state utils
2 parents 2d09e83 + df7eb6f commit 3ba1b80

File tree

12 files changed

+186
-279
lines changed

12 files changed

+186
-279
lines changed

bindings/utils/state/common.go

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,20 @@ const (
99
threadLimit int = 10
1010
)
1111

12-
// Global constants
13-
var zero = big.NewInt(0)
12+
// BigTime is a variable-sized big.Int from an evm 256-bit integer that represents a Unix time in seconds
13+
type bigTime struct {
14+
big.Int
15+
}
16+
17+
// BigDuration is a variable-sized big.Int from an evm 256-bit integer that represents a duration in seconds
18+
type bigDuration struct {
19+
big.Int
20+
}
1421

15-
// Converts a time on the chain (as Unix time in seconds) to a time.Time struct
16-
func convertToTime(value *big.Int) time.Time {
17-
return time.Unix(value.Int64(), 0)
22+
func (b *bigTime) toTime() time.Time {
23+
return time.Unix(b.Int64(), 0)
1824
}
1925

20-
// Converts a duration on the chain (as a number of seconds) to a time.Duration struct
21-
func convertToDuration(value *big.Int) time.Duration {
22-
return time.Duration(value.Uint64()) * time.Second
26+
func (b *bigDuration) toDuration() time.Duration {
27+
return time.Duration(b.Uint64()) * time.Second
2328
}

bindings/utils/state/minipool.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,7 @@ func CalculateCompleteMinipoolShares(rp *rocketpool.RocketPool, contracts *Netwo
200200

201201
// Calculate the Beacon shares
202202
beaconBalance := big.NewInt(0).Set(beaconBalances[j])
203-
if beaconBalance.Cmp(zero) > 0 {
203+
if beaconBalance.Sign() > 0 {
204204
mc.AddCall(mpContract, &details.NodeShareOfBeaconBalance, "calculateNodeShare", beaconBalance)
205205
mc.AddCall(mpContract, &details.UserShareOfBeaconBalance, "calculateUserShare", beaconBalance)
206206
} else {
@@ -214,7 +214,7 @@ func CalculateCompleteMinipoolShares(rp *rocketpool.RocketPool, contracts *Netwo
214214
totalBalance.Sub(totalBalance, details.NodeRefundBalance) // Remove node refund
215215

216216
// Calculate the node and user shares
217-
if totalBalance.Cmp(zero) > 0 {
217+
if totalBalance.Sign() > 0 {
218218
mc.AddCall(mpContract, &details.NodeShareOfBalanceIncludingBeacon, "calculateNodeShare", totalBalance)
219219
mc.AddCall(mpContract, &details.UserShareOfBalanceIncludingBeacon, "calculateUserShare", totalBalance)
220220
} else {
@@ -581,7 +581,7 @@ func addMinipoolShareCalls(rp *rocketpool.RocketPool, mc *multicall.MultiCaller,
581581
mpContract := mp.GetContract()
582582

583583
details.DistributableBalance = big.NewInt(0).Sub(details.Balance, details.NodeRefundBalance)
584-
if details.DistributableBalance.Cmp(zero) >= 0 {
584+
if details.DistributableBalance.Sign() >= 0 {
585585
mc.AddCall(mpContract, &details.NodeShareOfBalance, "calculateNodeShare", details.DistributableBalance)
586586
mc.AddCall(mpContract, &details.UserShareOfBalance, "calculateUserShare", details.DistributableBalance)
587587
} else {

bindings/utils/state/network.go

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -76,9 +76,9 @@ func NewNetworkDetails(rp *rocketpool.RocketPool, contracts *NetworkContracts) (
7676

7777
// Local vars for things that need to be converted
7878
var rewardIndex *big.Int
79-
var intervalStart *big.Int
80-
var intervalDuration *big.Int
81-
var scrubPeriodSeconds *big.Int
79+
var intervalStart *bigTime
80+
var intervalDuration *bigDuration
81+
var scrubPeriodSeconds *bigDuration
8282
var totalQueueCapacity *big.Int
8383
var effectiveQueueCapacity *big.Int
8484
var totalQueueLength *big.Int
@@ -90,9 +90,9 @@ func NewNetworkDetails(rp *rocketpool.RocketPool, contracts *NetworkContracts) (
9090
var balancesBlock *big.Int
9191
var balancesSubmissionFrequency *big.Int
9292
var minipoolLaunchTimeout *big.Int
93-
var promotionScrubPeriodSeconds *big.Int
94-
var windowStartRaw *big.Int
95-
var windowLengthRaw *big.Int
93+
var promotionScrubPeriodSeconds *bigDuration
94+
var windowStartRaw *bigDuration
95+
var windowLengthRaw *bigDuration
9696

9797
// Multicall getters
9898
contracts.Multicaller.AddCall(contracts.RocketNetworkPrices, &details.RplPrice, "getRPLPrice")
@@ -143,9 +143,9 @@ func NewNetworkDetails(rp *rocketpool.RocketPool, contracts *NetworkContracts) (
143143

144144
// Conversion for raw parameters
145145
details.RewardIndex = rewardIndex.Uint64()
146-
details.IntervalStart = convertToTime(intervalStart)
147-
details.IntervalDuration = convertToDuration(intervalDuration)
148-
details.ScrubPeriod = convertToDuration(scrubPeriodSeconds)
146+
details.IntervalStart = intervalStart.toTime()
147+
details.IntervalDuration = intervalDuration.toDuration()
148+
details.ScrubPeriod = scrubPeriodSeconds.toDuration()
149149
details.SmoothingPoolAddress = *contracts.RocketSmoothingPool.Address
150150
details.QueueCapacity = minipool.QueueCapacity{
151151
Total: totalQueueCapacity,
@@ -161,9 +161,9 @@ func NewNetworkDetails(rp *rocketpool.RocketPool, contracts *NetworkContracts) (
161161
details.NodeFee = eth.WeiToEth(nodeFee)
162162
details.BalancesBlock = balancesBlock.Uint64()
163163
details.MinipoolLaunchTimeout = minipoolLaunchTimeout
164-
details.PromotionScrubPeriod = convertToDuration(promotionScrubPeriodSeconds)
165-
details.BondReductionWindowStart = convertToDuration(windowStartRaw)
166-
details.BondReductionWindowLength = convertToDuration(windowLengthRaw)
164+
details.PromotionScrubPeriod = promotionScrubPeriodSeconds.toDuration()
165+
details.BondReductionWindowStart = windowStartRaw.toDuration()
166+
details.BondReductionWindowLength = windowLengthRaw.toDuration()
167167

168168
// Get various balances
169169
addresses := []common.Address{

bindings/utils/state/odao.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,8 @@ type OracleDaoMemberDetails struct {
2828
RPLBondAmount *big.Int `json:"rplBondAmount"`
2929
ReplacementAddress common.Address `json:"replacementAddress"`
3030
IsChallenged bool `json:"isChallenged"`
31-
joinedTimeRaw *big.Int `json:"-"`
32-
lastProposalTimeRaw *big.Int `json:"-"`
31+
joinedTimeRaw *bigTime `json:"-"`
32+
lastProposalTimeRaw *bigTime `json:"-"`
3333
}
3434

3535
// Gets the details for an Oracle DAO member using the efficient multicall contract
@@ -182,7 +182,7 @@ func addOracleDaoMemberDetailsCalls(contracts *NetworkContracts, mc *multicall.M
182182

183183
// Fixes a member details struct with supplemental logic
184184
func fixupOracleDaoMemberDetails(details *OracleDaoMemberDetails) error {
185-
details.JoinedTime = convertToTime(details.joinedTimeRaw)
186-
details.LastProposalTime = convertToTime(details.lastProposalTimeRaw)
185+
details.JoinedTime = details.joinedTimeRaw.toTime()
186+
details.LastProposalTime = details.lastProposalTimeRaw.toTime()
187187
return nil
188188
}

rocketpool/node/collectors/node-collector.go

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,6 @@ func (collector *NodeCollector) Collect(channel chan<- prometheus.Metric) {
266266
rewardsInterval := state.NetworkDetails.IntervalDuration
267267
inflationInterval := state.NetworkDetails.RPLInflationIntervalRate
268268
totalRplSupply := state.NetworkDetails.RPLTotalSupply
269-
totalEffectiveStake := collector.stateLocker.GetTotalEffectiveRPLStake()
270269
nodeOperatorRewardsPercent := eth.WeiToEth(state.NetworkDetails.NodeOperatorRewardsPercent)
271270
previousIntervalTotalNodeWeight := big.NewInt(0)
272271
ethBalance := eth.WeiToEth(nd.BalanceETH)
@@ -280,9 +279,6 @@ func (collector *NodeCollector) Collect(channel chan<- prometheus.Metric) {
280279
var beaconHead beacon.BeaconHead
281280
unclaimedEthRewards := float64(0)
282281
unclaimedRplRewards := float64(0)
283-
if totalEffectiveStake == nil {
284-
return
285-
}
286282

287283
// Get the cumulative claimed and unclaimed RPL rewards
288284
wg.Go(func() error {
@@ -531,7 +527,7 @@ func (collector *NodeCollector) Collect(channel chan<- prometheus.Metric) {
531527
* period we don't attempt an estimate and simply use 0.
532528
*/
533529
estimatedRewards := float64(0)
534-
if totalEffectiveStake.Cmp(big.NewInt(0)) == 1 && nodeWeight.Cmp(big.NewInt(0)) == 1 && state.NetworkDetails.RewardIndex > 0 {
530+
if nodeWeight.Cmp(big.NewInt(0)) == 1 && state.NetworkDetails.RewardIndex > 0 {
535531

536532
nodeWeightSum := big.NewInt(0).Add(nodeWeight, previousIntervalTotalNodeWeight)
537533

rocketpool/node/collectors/rpl-collector.go

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ type RplCollector struct {
1818
totalValueStaked *prometheus.Desc
1919

2020
// The total effective amount of RPL staked on the network
21+
// Obsolete, but still populated so the dashboard can show it.
2122
totalEffectiveStaked *prometheus.Desc
2223

2324
// The date and time of the next RPL rewards checkpoint
@@ -81,20 +82,18 @@ func (collector *RplCollector) Collect(channel chan<- prometheus.Metric) {
8182

8283
rplPriceFloat := eth.WeiToEth(state.NetworkDetails.RplPrice)
8384
totalValueStakedFloat := eth.WeiToEth(state.NetworkDetails.TotalRPLStake)
84-
totalEffectiveStake := collector.stateLocker.GetTotalEffectiveRPLStake()
8585
lastCheckpoint := state.NetworkDetails.IntervalStart
8686
rewardsInterval := state.NetworkDetails.IntervalDuration
8787
nextRewardsTime := float64(lastCheckpoint.Add(rewardsInterval).Unix()) * 1000
88-
if totalEffectiveStake == nil {
89-
return
90-
}
9188

9289
channel <- prometheus.MustNewConstMetric(
9390
collector.rplPrice, prometheus.GaugeValue, rplPriceFloat)
9491
channel <- prometheus.MustNewConstMetric(
9592
collector.totalValueStaked, prometheus.GaugeValue, totalValueStakedFloat)
93+
// All staked RPL is effective RPL, but this metric is on the dashboard so we
94+
// should keep populating it for now.
9695
channel <- prometheus.MustNewConstMetric(
97-
collector.totalEffectiveStaked, prometheus.GaugeValue, eth.WeiToEth(totalEffectiveStake))
96+
collector.totalEffectiveStaked, prometheus.GaugeValue, totalValueStakedFloat)
9897
channel <- prometheus.MustNewConstMetric(
9998
collector.checkpointTime, prometheus.GaugeValue, nextRewardsTime)
10099
}
Lines changed: 6 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,32 @@
11
package collectors
22

33
import (
4-
"math/big"
54
"sync"
65

76
"github.com/rocket-pool/smartnode/shared/services/state"
87
)
98

109
type StateLocker struct {
11-
state *state.NetworkState
12-
totalEffectiveStake *big.Int
10+
state *state.NetworkState
1311

1412
// Internal fields
15-
lock *sync.Mutex
13+
lock *sync.RWMutex
1614
}
1715

1816
func NewStateLocker() *StateLocker {
1917
return &StateLocker{
20-
lock: &sync.Mutex{},
18+
lock: &sync.RWMutex{},
2119
}
2220
}
2321

24-
func (l *StateLocker) UpdateState(state *state.NetworkState, totalEffectiveStake *big.Int) {
22+
func (l *StateLocker) UpdateState(state *state.NetworkState) {
2523
l.lock.Lock()
2624
defer l.lock.Unlock()
2725
l.state = state
28-
if totalEffectiveStake != nil {
29-
l.totalEffectiveStake = totalEffectiveStake
30-
}
3126
}
3227

3328
func (l *StateLocker) GetState() *state.NetworkState {
34-
l.lock.Lock()
35-
defer l.lock.Unlock()
29+
l.lock.RLock()
30+
defer l.lock.RUnlock()
3631
return l.state
3732
}
38-
39-
func (l *StateLocker) GetTotalEffectiveRPLStake() *big.Int {
40-
l.lock.Lock()
41-
defer l.lock.Unlock()
42-
return l.totalEffectiveStake
43-
}

rocketpool/node/node.go

Lines changed: 6 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@ import (
2727
// Config
2828
var tasksInterval, _ = time.ParseDuration("5m")
2929
var taskCooldown, _ = time.ParseDuration("10s")
30-
var totalEffectiveStakeCooldown, _ = time.ParseDuration("1h")
3130

3231
const (
3332
MaxConcurrentEth1Requests = 200
@@ -172,9 +171,6 @@ func run(c *cli.Context) error {
172171
wg := new(sync.WaitGroup)
173172
wg.Add(2)
174173

175-
// Timestamp for caching total effective RPL stake
176-
lastTotalEffectiveStakeTime := time.Unix(0, 0)
177-
178174
// Run task loop
179175
go func() {
180176
// we assume clients are synced on startup so that we don't send unnecessary alerts
@@ -213,18 +209,13 @@ func run(c *cli.Context) error {
213209
}
214210

215211
// Update the network state
216-
updateTotalEffectiveStake := false
217-
if time.Since(lastTotalEffectiveStakeTime) > totalEffectiveStakeCooldown {
218-
updateTotalEffectiveStake = true
219-
lastTotalEffectiveStakeTime = time.Now() // Even if the call below errors out, this will prevent contant errors related to this flag
220-
}
221-
state, totalEffectiveStake, err := updateNetworkState(m, &updateLog, nodeAccount.Address, updateTotalEffectiveStake)
212+
state, err := updateNetworkState(m, &updateLog, nodeAccount.Address)
222213
if err != nil {
223214
errorLog.Println(err)
224215
time.Sleep(taskCooldown)
225216
continue
226217
}
227-
stateLocker.UpdateState(state, totalEffectiveStake)
218+
stateLocker.UpdateState(state)
228219

229220
// Manage the fee recipient for the node
230221
if err := manageFeeRecipient.run(state); err != nil {
@@ -382,13 +373,13 @@ func removeLegacyFeeRecipientFiles(c *cli.Context) error {
382373
}
383374

384375
// Update the latest network state at each cycle
385-
func updateNetworkState(m *state.NetworkStateManager, log *log.ColorLogger, nodeAddress common.Address, calculateTotalEffectiveStake bool) (*state.NetworkState, *big.Int, error) {
376+
func updateNetworkState(m *state.NetworkStateManager, log *log.ColorLogger, nodeAddress common.Address) (*state.NetworkState, error) {
386377
// Get the state of the network
387-
state, totalEffectiveStake, err := m.GetHeadStateForNode(nodeAddress, calculateTotalEffectiveStake)
378+
state, err := m.GetHeadStateForNode(nodeAddress)
388379
if err != nil {
389-
return nil, nil, fmt.Errorf("error updating network state: %w", err)
380+
return nil, fmt.Errorf("error updating network state: %w", err)
390381
}
391-
return state, totalEffectiveStake, nil
382+
return state, nil
392383
}
393384

394385
// Checks if the user-inputted priorityFee is greater than the oracle based maxFee

0 commit comments

Comments
 (0)