Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduces Decay Computation and Submission - Pre-Confirmations Decay (Part 3 of 3) #38

Merged
merged 14 commits into from
Mar 20, 2024
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ require (
github.com/ethereum/go-ethereum v1.13.5
github.com/google/go-cmp v0.6.0
github.com/lib/pq v1.10.9
github.com/primevprotocol/contracts-abi v0.2.0
github.com/primevprotocol/contracts-abi v0.2.3
github.com/prometheus/client_golang v1.14.0
github.com/testcontainers/testcontainers-go v0.27.0
github.com/urfave/cli/v2 v2.27.1
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -312,8 +312,8 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c h1:ncq/mPwQF4JjgDlrVEn3C11VoGHZN7m8qihwgMEtzYw=
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
github.com/primevprotocol/contracts-abi v0.2.0 h1:fzADMI4pVpLVOagZ6K1dOeibYDc89TNyuwymSKzU9ls=
github.com/primevprotocol/contracts-abi v0.2.0/go.mod h1:dE2KkvEqC+itvPa3SCrqQfvH5Hfnfn6omNRwWDTdIp8=
github.com/primevprotocol/contracts-abi v0.2.3 h1:4jZGl0hrEdP1yensIrs4Sh2DNU6EG+BBNtKvrH5liR0=
github.com/primevprotocol/contracts-abi v0.2.3/go.mod h1:dE2KkvEqC+itvPa3SCrqQfvH5Hfnfn6omNRwWDTdIp8=
github.com/prometheus/client_golang v1.14.0 h1:nJdhIvne2eSX/XRAFV9PcvFFRbrjbcTUj0VP62TMhnw=
github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
Expand Down
9 changes: 8 additions & 1 deletion pkg/node/node.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package node

Check failure on line 1 in pkg/node/node.go

View workflow job for this annotation

GitHub Actions / Build and Test

: # github.com/primevprotocol/mev-oracle/pkg/node

import (
"context"
Expand All @@ -6,6 +6,7 @@
"errors"
"fmt"
"io"
"log"
"log/slog"
"math/big"
"time"
Expand Down Expand Up @@ -83,6 +84,12 @@
return nil, err
}

l2Client, err := ethclient.Dial(opts.SettlementRPCUrl)
if err != nil {
log.Fatal().Err(err).Msg("Failed to connect to the L2 Ethereum client")
return nil, err
}

ctx, cancel := context.WithCancel(context.Background())

var listenerL1Client l1Listener.EthClient
Expand Down Expand Up @@ -144,7 +151,7 @@
}
oc := &rollupclient.OracleSession{Contract: oracleContract, CallOpts: callOpts}

updtr := updater.NewUpdater(nd.logger.With("component", "updater"), l1Client, st, oc, pc)
updtr := updater.NewUpdater(nd.logger.With("component", "updater"), l1Client, l2Client, st, oc, pc)
updtrClosed := updtr.Start(ctx)

settlr := settler.NewSettler(
Expand Down
17 changes: 10 additions & 7 deletions pkg/settler/settler.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,14 @@ const (
)

type Settlement struct {
CommitmentIdx []byte
TxHash string
BlockNum int64
Builder string
Amount uint64
BidID []byte
Type SettlementType
CommitmentIdx []byte
TxHash string
BlockNum int64
Builder string
Amount uint64
BidID []byte
Type SettlementType
DecayPercentage int64
}

type Return struct {
Expand Down Expand Up @@ -70,6 +71,7 @@ type Oracle interface {
blockNum *big.Int,
builder string,
isSlash bool,
residualDecay *big.Int,
) (*types.Transaction, error)
UnlockFunds(opts *bind.TransactOpts, bidIDs [][32]byte) (*types.Transaction, error)
}
Expand Down Expand Up @@ -256,6 +258,7 @@ RESTART:
big.NewInt(settlement.BlockNum),
settlement.Builder,
settlement.Type == SettlementTypeSlash,
big.NewInt(settlement.DecayPercentage),
)
if err != nil {
return fmt.Errorf("process commitment: %w nonce %d", err, opts.Nonce.Uint64())
Expand Down
1 change: 1 addition & 0 deletions pkg/settler/settler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ func (t *testOracle) ProcessBuilderCommitmentForBlockNumber(
blockNum *big.Int,
builder string,
isSlash bool,
residualDecay *big.Int,
) (*types.Transaction, error) {
t.mu.Lock()
defer t.mu.Unlock()
Expand Down
9 changes: 7 additions & 2 deletions pkg/store/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ CREATE TABLE IF NOT EXISTS settlements (
bid_id BYTEA,
chainhash BYTEA,
nonce BIGINT,
settled BOOLEAN
settled BOOLEAN,
decay_percentage BIGINT
);`

var winnersTable = `
Expand Down Expand Up @@ -159,6 +160,7 @@ func (s *Store) AddSettlement(
builder string,
bidID []byte,
settlementType settler.SettlementType,
decayPercentage int64,
) error {
columns := []string{
"commitment_index",
Expand All @@ -171,6 +173,7 @@ func (s *Store) AddSettlement(
"settled",
"chainhash",
"nonce",
"decay_percentage",
}
values := []interface{}{
commitmentIdx,
Expand All @@ -183,6 +186,7 @@ func (s *Store) AddSettlement(
false,
nil,
0,
decayPercentage,
}
placeholder := make([]string, len(values))
for i := range columns {
Expand Down Expand Up @@ -211,7 +215,7 @@ func (s *Store) SubscribeSettlements(ctx context.Context) <-chan settler.Settlem
RETRY:
for {
queryStr := `
SELECT commitment_index, transaction, block_number, builder_address, amount, bid_id, type
SELECT commitment_index, transaction, block_number, builder_address, amount, bid_id, type, decay_percentage
FROM settlements
WHERE settled = false AND chainhash IS NULL AND type != 'return'
ORDER BY block_number ASC`
Expand All @@ -232,6 +236,7 @@ func (s *Store) SubscribeSettlements(ctx context.Context) <-chan settler.Settlem
&s.Amount,
&s.BidID,
&s.Type,
&s.DecayPercentage,
)
if err != nil {
_ = results.Close()
Expand Down
1 change: 1 addition & 0 deletions pkg/store/store_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,7 @@ func TestStore(t *testing.T) {
settlement.Builder,
settlement.BidID,
settlement.Type,
settlement.DecayPercentage,
)
if err != nil {
t.Fatalf("Failed to add settlement: %s", err)
Expand Down
36 changes: 33 additions & 3 deletions pkg/updater/updater.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"log/slog"
"math"
"math/big"
"strings"

Expand Down Expand Up @@ -33,10 +34,11 @@ type WinnerRegister interface {
builder string,
bidID []byte,
settlementType settler.SettlementType,
decayPercentage int64,
) error
}

type L1Client interface {
type EVMClient interface {
BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error)
}

Expand All @@ -51,7 +53,8 @@ type Preconf interface {

type Updater struct {
logger *slog.Logger
l1Client L1Client
l1Client EVMClient
l2Client EVMClient
winnerRegister WinnerRegister
preconfClient Preconf
rollupClient Oracle
Expand All @@ -61,14 +64,16 @@ type Updater struct {

func NewUpdater(
logger *slog.Logger,
l1Client L1Client,
l1Client EVMClient,
l2Client EVMClient,
winnerRegister WinnerRegister,
rollupClient Oracle,
preconfClient Preconf,
) *Updater {
return &Updater{
logger: logger,
l1Client: l1Client,
l2Client: l2Client,
winnerRegister: winnerRegister,
preconfClient: preconfClient,
rollupClient: rollupClient,
Expand Down Expand Up @@ -149,6 +154,12 @@ func (u *Updater) Start(ctx context.Context) <-chan struct{} {
return fmt.Errorf("failed to get commitment: %w", err)
}

l2Block, err := u.l2Client.BlockByNumber(ctx, commitment.BlockCommitedAt)
if err != nil {
return fmt.Errorf("failed to get L2 Block: %w", err)
}
decayPercentage := computeDecayPercentage(commitment.DecayStartTimeStamp, commitment.DecayEndTimeStamp, l2Block.Header().Time)

settlementType := settler.SettlementTypeReturn

if commitment.Commiter.Cmp(builderAddr) == 0 {
Expand All @@ -174,6 +185,7 @@ func (u *Updater) Start(ctx context.Context) <-chan struct{} {
commitment.Commiter.Hex(),
commitment.CommitmentHash[:],
settlementType,
decayPercentage,
)
if err != nil {
return fmt.Errorf("failed to add settlement: %w", err)
Expand Down Expand Up @@ -221,3 +233,21 @@ func (u *Updater) Start(ctx context.Context) <-chan struct{} {

return doneChan
}

// computeDecayPercentage takes startTimestamp, endTimestamp, commitTimestamp and computes a linear decay percentage
// The computation does not care what format the timestamps are in, as long as they are consistent
// (e.g they could be unix or unixMili timestamps)
func computeDecayPercentage(startTimestamp, endTimestamp, commitTimestamp uint64) int64 {
if startTimestamp >= endTimestamp || startTimestamp > commitTimestamp {
return 0
}

// Calculate the total time in seconds
totalTime := endTimestamp - startTimestamp
// Calculate the time passed in seconds
timePassed := commitTimestamp - startTimestamp
// Calculate the decay percentage
decayPercentage := float64(timePassed) / float64(totalTime)

return int64(math.Round(decayPercentage * 100))
ckartik marked this conversation as resolved.
Show resolved Hide resolved
}
Loading
Loading