Skip to content

Commit

Permalink
Release-v1.9.2 → main (#725)
Browse files Browse the repository at this point in the history
* liveclient rename

* total token strategy

* typo

---------

Co-authored-by: Deniz Mert Edincik <[email protected]>
  • Loading branch information
vishalchangrani and bluesign authored Aug 15, 2023
1 parent 71ced1c commit a27d741
Show file tree
Hide file tree
Showing 6 changed files with 182 additions and 13 deletions.
1 change: 1 addition & 0 deletions backend/main/server/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ type Strategy interface {

var strategyMap = map[string]Strategy{
"token-weighted-default": &strategies.TokenWeightedDefault{},
"total-token-weighted-default": &strategies.TotalTokenWeightedDefault{},
"staked-token-weighted-default": &strategies.StakedTokenWeightedDefault{},
"one-address-one-vote": &strategies.OneAddressOneVote{},
"balance-of-nfts": &strategies.BalanceOfNfts{},
Expand Down
2 changes: 1 addition & 1 deletion backend/main/server/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -556,7 +556,7 @@ func (h *Helpers) createProposal(p models.Proposal) (models.Proposal, errorRespo
p.Max_weight = strategy.Contract.MaxWeight
}

header, err := h.A.FlowAdapter.Client.GetLatestBlockHeader(context.Background(), true)
header, err := h.A.FlowAdapter.LiveClient.GetLatestBlockHeader(context.Background(), true)
if err != nil {
log.Error().Err(err).Msg("Couldn't get block header")
return models.Proposal{}, errIncompleteRequest
Expand Down
23 changes: 11 additions & 12 deletions backend/main/shared/flow.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import (
type FlowAdapter struct {
Config FlowConfig
ArchiveClient *client.Client
Client *client.Client
LiveClient *client.Client
Context context.Context
CustomScriptsMap map[string]CustomScript
URL string
Expand Down Expand Up @@ -92,7 +92,6 @@ func NewFlowClient(flowEnv string, customScriptsMap map[string]CustomScript) *Fl
}

log.Info().Msgf("FLOW URL: %s", adapter.URL)

// create flow client
FlowClient, err := client.New(adapter.URL, grpc.WithInsecure())
if err != nil {
Expand All @@ -107,19 +106,19 @@ func NewFlowClient(flowEnv string, customScriptsMap map[string]CustomScript) *Fl
log.Panic().Msgf("Failed to connect to %s.", adapter.ArchiveURL)
}

adapter.Client = FlowClient
adapter.LiveClient = FlowClient
adapter.ArchiveClient = FlowClientArchive

return &adapter
}

func (fa *FlowAdapter) GetAccountAtBlockHeight(addr string, blockheight uint64) (*flow.Account, error) {
hexAddr := flow.HexToAddress(addr)
return fa.Client.GetAccountAtBlockHeight(fa.Context, hexAddr, blockheight)
return fa.ArchiveClient.GetAccountAtBlockHeight(fa.Context, hexAddr, blockheight)
}

func (fa *FlowAdapter) GetCurrentBlockHeight() (int, error) {
block, err := fa.Client.GetLatestBlock(fa.Context, true)
block, err := fa.LiveClient.GetLatestBlock(fa.Context, true)
if err != nil {
return 0, err
}
Expand Down Expand Up @@ -185,7 +184,7 @@ func (fa *FlowAdapter) ValidateSignature(address, message string, sigs *[]Compos
}

// call the script to verify the signature on chain
value, err := fa.Client.ExecuteScriptAtLatestBlock(
value, err := fa.LiveClient.ExecuteScriptAtLatestBlock(
fa.Context,
script,
[]cadence.Value{
Expand Down Expand Up @@ -239,7 +238,7 @@ func (fa *FlowAdapter) EnforceTokenThreshold(scriptPath, creatorAddr string, c *
script = fa.ReplaceContractPlaceholders(string(script[:]), c, isFungible)

//call the non-fungible token script to verify balance
cadenceValue, err = fa.Client.ExecuteScriptAtLatestBlock(
cadenceValue, err = fa.LiveClient.ExecuteScriptAtLatestBlock(
fa.Context,
script,
[]cadence.Value{
Expand All @@ -259,7 +258,7 @@ func (fa *FlowAdapter) EnforceTokenThreshold(scriptPath, creatorAddr string, c *
script = fa.ReplaceContractPlaceholders(string(script[:]), c, isFungible)

//call the fungible-token script to verify balance
cadenceValue, err = fa.Client.ExecuteScriptAtLatestBlock(
cadenceValue, err = fa.LiveClient.ExecuteScriptAtLatestBlock(
fa.Context,
script,
[]cadence.Value{
Expand Down Expand Up @@ -385,7 +384,7 @@ func (fa *FlowAdapter) GetNFTIds(voterAddr string, c *Contract, path string) ([]

script = fa.ReplaceContractPlaceholders(string(script[:]), c, false)

cadenceValue, err := fa.Client.ExecuteScriptAtLatestBlock(
cadenceValue, err := fa.LiveClient.ExecuteScriptAtLatestBlock(
fa.Context,
script,
[]cadence.Value{
Expand Down Expand Up @@ -416,7 +415,7 @@ func (fa *FlowAdapter) GetFloatNFTIds(voterAddr string, c *Contract) ([]interfac

script = fa.ReplaceContractPlaceholders(string(script[:]), c, false)

cadenceValue, err := fa.Client.ExecuteScriptAtLatestBlock(
cadenceValue, err := fa.LiveClient.ExecuteScriptAtLatestBlock(
fa.Context,
script,
[]cadence.Value{
Expand Down Expand Up @@ -447,7 +446,7 @@ func (fa *FlowAdapter) CheckIfUserHasEvent(voterAddr string, c *Contract) (bool,

script = fa.ReplaceContractPlaceholders(string(script[:]), c, false)

cadenceValue, err := fa.Client.ExecuteScriptAtLatestBlock(
cadenceValue, err := fa.LiveClient.ExecuteScriptAtLatestBlock(
fa.Context,
script,
[]cadence.Value{
Expand Down Expand Up @@ -484,7 +483,7 @@ func (fa *FlowAdapter) GetEventNFT(voterAddr string, c *Contract) (interface{},

script = fa.ReplaceContractPlaceholders(string(script[:]), c, false)

cadenceValue, err := fa.Client.ExecuteScriptAtLatestBlock(
cadenceValue, err := fa.LiveClient.ExecuteScriptAtLatestBlock(
fa.Context,
script,
[]cadence.Value{
Expand Down
164 changes: 164 additions & 0 deletions backend/main/strategies/total_token_weighted_default.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
package strategies

import (
"fmt"
"math"

"github.com/DapperCollectives/CAST/backend/main/models"
"github.com/DapperCollectives/CAST/backend/main/shared"
s "github.com/DapperCollectives/CAST/backend/main/shared"
"github.com/rs/zerolog/log"
)

type TotalTokenWeightedDefault struct {
s.StrategyStruct
DB *s.Database
}

func (s *TotalTokenWeightedDefault) FetchBalance(
b *models.Balance,
p *models.Proposal,
) (*models.Balance, error) {

var c models.Community
if err := c.GetCommunityByProposalId(s.DB, b.Proposal_id); err != nil {
return nil, err
}

strategy, err := models.MatchStrategyByProposal(*c.Strategies, *p.Strategy)
if err != nil {
log.Error().Err(err).Msg("Unable to find strategy for contract")
return nil, err
}

if err := s.FetchBalanceFromSnapshot(&strategy, b); err != nil {
log.Error().Err(err).Msg("Error calling snapshot client")
return nil, err
}
if err := b.CreateBalance(s.DB); err != nil {
log.Error().Err(err).Msg("Error creating balance in the database.")
return nil, err
}

return b, nil
}

func (s *TotalTokenWeightedDefault) FetchBalanceFromSnapshot(
strategy *models.Strategy,
b *models.Balance,
) error {

var ftBalance = &shared.FTBalanceResponse{}
ftBalance.NewFTBalance()

if *strategy.Contract.Name == "FlowToken" {
if err := s.FlowAdapter.GetAddressBalanceAtBlockHeight(
b.Addr,
b.BlockHeight,
ftBalance,
&strategy.Contract,
); err != nil {
log.Error().Err(err).Msg("Error fetching balance from snapshot client")
return err
}
b.PrimaryAccountBalance = ftBalance.PrimaryAccountBalance
b.SecondaryAccountBalance = ftBalance.SecondaryAccountBalance
b.StakingBalance = ftBalance.StakingBalance

} else {
if err := s.FlowAdapter.GetAddressBalanceAtBlockHeight(
b.Addr,
b.BlockHeight,
ftBalance,
&strategy.Contract,
); err != nil {
log.Error().Err(err).Msg("Error fetching balance.")
return err
}
b.PrimaryAccountBalance = ftBalance.Balance
b.SecondaryAccountBalance = 0
b.StakingBalance = 0
}

return nil
}
func (s *TotalTokenWeightedDefault) TallyVotes(
votes []*models.VoteWithBalance,
r *models.ProposalResults,
p *models.Proposal,
) (models.ProposalResults, error) {
var zero uint64 = 0

for _, vote := range votes {
if *vote.StakingBalance != zero {
var allowedBalance float64

totalBalance := float64(*vote.StakingBalance) + float64(*vote.PrimaryAccountBalance) + float64(*vote.SecondaryAccountBalance)

if p.Max_weight != nil {
allowedBalance = p.EnforceMaxWeight(totalBalance)
} else {
allowedBalance = totalBalance
}

r.Results[vote.Choice] += int(allowedBalance)
r.Results_float[vote.Choice] += allowedBalance * math.Pow(10, -8)
}
}

return *r, nil
}

func (s *TotalTokenWeightedDefault) GetVoteWeightForBalance(
vote *models.VoteWithBalance,
proposal *models.Proposal,
) (float64, error) {
var weight float64
var ERROR error = fmt.Errorf("no weight found, address: %s, strategy: %s", vote.Addr, *proposal.Strategy)

totalBalance := float64(*vote.StakingBalance) + float64(*vote.PrimaryAccountBalance) + float64(*vote.SecondaryAccountBalance)

weight = totalBalance * math.Pow(10, -8)

switch {
case proposal.Max_weight != nil && weight > *proposal.Max_weight:
weight = *proposal.Max_weight
return weight, nil
case proposal.Max_weight != nil && weight < *proposal.Max_weight:
return weight, nil
case weight > 0.00:
return weight, nil
case weight == 0.00:
return 0.00, nil
default:
return weight, ERROR
}
}

func (s *TotalTokenWeightedDefault) GetVotes(
votes []*models.VoteWithBalance,
proposal *models.Proposal,
) ([]*models.VoteWithBalance, error) {

for _, vote := range votes {
weight, err := s.GetVoteWeightForBalance(vote, proposal)
if err != nil {
return nil, err
}
vote.Weight = &weight
}

return votes, nil
}

func (s *TotalTokenWeightedDefault) RequiresSnapshot() bool {
return true
}

func (s *TotalTokenWeightedDefault) InitStrategy(
f *shared.FlowAdapter,
db *shared.Database,
) {
s.FlowAdapter = f
s.DB = db
}
4 changes: 4 additions & 0 deletions backend/migrations/000042_add_staked_token_strategy.up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
ALTER TYPE strategies ADD VALUE 'total-token-weighted-default';
COMMIT;
INSERT INTO voting_strategies (key, name, description)
VALUES ('total-token-weighted-default', 'Total Token Weighted', 'Vote weight is proportional to the number tokens total ( primary / staked / locked ).');
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DELETE FROM voting_strategies WHERE key = 'total-token-weighted-default'

0 comments on commit a27d741

Please sign in to comment.