Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

## Prerequisites

- [GoLang 1.6](https://golang.org/doc/install)
- [GoLang 1.16+](https://golang.org/doc/install)
- [PostgreSQL 14.1](https://www.postgresql.org/download/)
- [Flow CLI](https://docs.onflow.org/flow-cli/install/)
- Note: See below for how install v0.30.2 (required)
Expand Down Expand Up @@ -45,6 +45,17 @@ CREATE DATABASE flow_snapshot;
CREATE DATABASE flow_snapshot_test;
```

NOTE: in some system configurations `sudo -i -u postgres` will return an error so you can run the following:

```bash
psql
CREATE USER postgres;
ALTER USER postgres PASSWORD 'admin';
ALTER USER postgres WITH SUPERUSER;
CREATE DATABASE flow_snapshot WITH OWNER = postgres;
CREATE DATABASE flow_snapshot_test WITH OWNER = postgres;
```

#### Install Migrate Tool

To run the `make` migrate scripts, you need to have the `migrate` CLI installed in your local path. Follow the [steps here](https://github.com/golang-migrate/migrate/tree/master/cmd/migrate) to install `migrate` on your machine.
Expand Down Expand Up @@ -87,10 +98,14 @@ make testmigratedown

#### Dealing with Dirty Schema Migrations

Reset Schema Migrations
```bash
UPDATE schema_migrations SET dirty = false
```

### Testing

1. Run `flow emulator` from this top-level directory (the private key for the `emulator-account` in `flow.json` must match the private key hard-coded in the test suite). Install the `flow` CLI [here](https://docs.onflow.org/flow-cli/install/)
1. Run `flow emulator` from this top-level directory (the private key for the `emulator-account` in top level `flow.json` must match the private key hard-coded in the test suite eg. `backend/cadence/V2/tests/flow.json`). Install the `flow` CLI [here](https://docs.onflow.org/flow-cli/install/)
2. Run migrations against the test database (if migrations aren't up to date): `make testmigrateup`
3. Run the test suite: `make test`

Expand All @@ -110,7 +125,7 @@ docker run -it --network=host --rm --name vt-test vt-test:latest

Before running the app you should:

1. Run `flow emulator` from this top-level directory (the private key for the `emulator-account` in `flow.json` must match the private key hard-coded in the test suite). Install the `flow` CLI [here](https://docs.onflow.org/flow-cli/install/)
1. Run `flow emulator` from this top-level directory (the private key for the `emulator-account` in top level`flow.json` must match the private key hard-coded in the test suite eg. `backend/cadence/V2/tests/flow.json`). Install the `flow` CLI [here](https://docs.onflow.org/flow-cli/install/)
2. Run migrations against the database (if migrations aren't up to date): `make migrateup`

#### Go Executable
Expand Down
1 change: 1 addition & 0 deletions backend/main/server/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,7 @@ func (a *App) getResultsForProposal(w http.ResponseWriter, r *http.Request) {

// First, get the proposal by proposalId
p := models.Proposal{ID: proposalId}

if err := p.GetProposalById(a.DB); err != nil {
switch err.Error() {
case pgx.ErrNoRows.Error():
Expand Down
6 changes: 2 additions & 4 deletions backend/main/shared/snapshot-flow.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,11 +157,9 @@ func (c *SnapshotClient) GetAddressBalanceAtBlockHeight(
address string,
blockheight uint64,
balancePointer interface{},
contract Contract) error {
// Send dummy data for tests
contract Contract,
) error {
if c.bypass() {
DummyBalance.Addr = address
balancePointer = &DummyBalance
return nil
}
var url string
Expand Down
17 changes: 10 additions & 7 deletions backend/main/strategies/staked_token_weighted_default.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,19 @@ func (s *StakedTokenWeightedDefault) FetchBalance(
Addr: c.Contract_addr,
}

if err := s.SnapshotClient.GetAddressBalanceAtBlockHeight(b.Addr, b.BlockHeight, b, *contract); err != nil {
log.Error().Err(err).Msg("error querying address b at blockheight")
if err := s.SnapshotClient.GetAddressBalanceAtBlockHeight(
b.Addr,
b.BlockHeight,
b,
*contract,
); err != nil {
log.Error().Err(err).Msg("error fetching balance")
return nil, err
}

if b.ID == "" {
if err := b.CreateBalance(db); err != nil {
log.Error().Err(err).Msg("error saving b to DB")
return nil, err
}
if err := b.CreateBalance(db); err != nil {
log.Error().Err(err).Msg("error creating balance in the DB")
return nil, err
}

return b, nil
Expand Down
24 changes: 17 additions & 7 deletions backend/main/strategies/token_weighted_default.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/DapperCollectives/CAST/backend/main/models"
"github.com/DapperCollectives/CAST/backend/main/shared"
s "github.com/DapperCollectives/CAST/backend/main/shared"
"github.com/jackc/pgx/v4"
"github.com/rs/zerolog/log"
)

Expand All @@ -26,21 +27,30 @@ func (s *TokenWeightedDefault) FetchBalance(
return nil, err
}

if err := b.GetBalanceByAddressAndBlockHeight(db); err != nil && err.Error() != pgx.ErrNoRows.Error() {
log.Error().Err(err).Msg("error fetching balance from DB")
return nil, err
}

//@TODO should get contract by matching strategy name
var contract = &shared.Contract{
Name: c.Contract_name,
Addr: c.Contract_addr,
}

if err := s.SnapshotClient.GetAddressBalanceAtBlockHeight(b.Addr, b.BlockHeight, b, *contract); err != nil {
log.Error().Err(err).Msg("error querying address b at blockheight")
if err := s.SnapshotClient.GetAddressBalanceAtBlockHeight(
b.Addr,
b.BlockHeight,
b,
*contract,
); err != nil {
log.Error().Err(err).Msg("error fetching balance")
return nil, err
}

if b.ID == "" {
if err := b.CreateBalance(db); err != nil {
log.Error().Err(err).Msg("error saving b to DB")
return nil, err
}
if err := b.CreateBalance(db); err != nil {
log.Error().Err(err).Msg("error creating balance in the DB")
return nil, err
}

return b, nil
Expand Down
1 change: 1 addition & 0 deletions backend/main/strategies_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@ func TestBalanceOfNFTsStrategy(t *testing.T) {
//weight should be the same as before the cheat vote was added
//because the cheat vote should be ignored by the server
//therefor the cheatResults should be the same as the correctResults

assert.Equal(t, correctResults.Proposal_id, cheatResults.Proposal_id)
assert.Equal(t, correctResults.Results_float["a"], cheatResults.Results_float["a"])
assert.Equal(t, correctResults.Results_float["b"], cheatResults.Results_float["b"])
Expand Down
15 changes: 0 additions & 15 deletions backend/main/test_utils/community_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -244,18 +244,3 @@ func (otu *OverflowTestUtils) GetCommunityUsersAPIByType(id int, userType string
response := otu.ExecuteRequest(req)
return response
}

// func GenerateValidUpdateCommunityPayload(addr string) []byte {
// // this does a deep copy
// community := ValidUpdateCommunityStruct

// community.Signing_addr = addr
// timestamp := fmt.Sprint(time.Now().UnixNano() / int64(time.Millisecond))
// community.Timestamp = timestamp
// compositeSignatures := SignMessage(ServiceAccountAddress, ValidServiceAccountKey, timestamp)

// community.Composite_signatures = compositeSignatures

// jsonStr, _ := json.Marshal(community)
// fmt.Printf("payload: %v\n", string(jsonStr))
// return []byte(jsonStr)
16 changes: 2 additions & 14 deletions backend/main/test_utils/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,6 @@ var InvalidServiceAccountKey = "5687d75f957bf64591b55eb19227706e3c8712c1387225b8
// VOTES
//////////

// func GenerateValidVotePayload(proposalId int, choice string) []byte {
// timestamp := time.Now().UnixNano() / int64(time.Millisecond)
// hexChoice := hex.EncodeToString([]byte(choice))
// message := "1:" + hexChoice + ":" + fmt.Sprint(timestamp)
// compositeSignatures := SignMessage(ServiceAccountAddress, ValidServiceAccountKey, message)

// vote := models.Vote{Proposal_id: proposalId, Addr: ServiceAccountAddress, Choice: choice,
// Composite_signatures: compositeSignatures, Message: message}

// jsonStr, _ := json.Marshal(vote)
// return []byte(jsonStr)
// }

func (otu *OverflowTestUtils) AddDummyVotesAndBalances(votes *[]VoteWithBalance) {
for _, vote := range *votes {
// Insert Vote
Expand All @@ -49,7 +36,7 @@ func (otu *OverflowTestUtils) AddDummyVotesAndBalances(votes *[]VoteWithBalance)
_, err = otu.A.DB.Conn.Exec(otu.A.DB.Context, `
INSERT INTO balances(id, addr, primary_account_balance, secondary_address, secondary_account_balance, staking_balance, script_result, stakes, block_height)
VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9)
`, uuid.New(), vote.Addr, vote.Primary_account_balance, "0x0", 0, vote.Staking_balance, "SUCCESS", []string{}, vote.Block_height)
`, uuid.New(), vote.Addr, vote.Primary_account_balance, "0x0", 0, vote.Staking_balance, "SUCCESS", []string{}, 1)
if err != nil {
log.Error().Err(err).Msg("AddDummyVotesAndBalances DB err - balances")
}
Expand All @@ -58,6 +45,7 @@ func (otu *OverflowTestUtils) AddDummyVotesAndBalances(votes *[]VoteWithBalance)

func (otu *OverflowTestUtils) AddDummyVotesAndNFTs(votes *[]VoteWithBalance) {
for _, vote := range *votes {

// Insert Vote
_, err := otu.A.DB.Conn.Exec(otu.A.DB.Context, `
INSERT INTO votes(proposal_id, addr, choice, composite_signatures, message)
Expand Down
36 changes: 19 additions & 17 deletions backend/main/test_utils/proposal_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,23 +17,25 @@ import (
// PROPOSALS
//////////////

var strategy = "token-weighted-default"
var proposalBody = "<html>something</html>"
var published = "published"
var blockHeight uint64 = 1

var DefaultProposalStruct = models.Proposal{
Name: "Test Proposal",
Body: &proposalBody,
Choices: []shared.Choice{
{Choice_text: "a"},
{Choice_text: "b"},
},
Creator_addr: ServiceAccountAddress,
Strategy: &strategy,
Status: &published,
Block_height: &blockHeight,
}
var (
proposalBody = "<html>something</html>"
published = "published"
tokenWeightedDefault = "token-weighted-default"
blockHeight uint64 = 1

DefaultProposalStruct = models.Proposal{
Name: "Test Proposal",
Body: &proposalBody,
Choices: []shared.Choice{
{Choice_text: "a"},
{Choice_text: "b"},
},
Creator_addr: ServiceAccountAddress,
Strategy: &tokenWeightedDefault,
Status: &published,
Block_height: &blockHeight,
}
)

func (otu *OverflowTestUtils) GetProposalsForCommunityAPI(communityId int) *httptest.ResponseRecorder {
req, _ := http.NewRequest("GET", "/communities/"+strconv.Itoa(communityId)+"/proposals", nil)
Expand Down
2 changes: 2 additions & 0 deletions backend/main/test_utils/strategy_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ func (otu *OverflowTestUtils) TallyResultsForStakedTokenWeightedDefault(
r *models.ProposalResults,
) *models.ProposalResults {

fmt.Printf("Tallying results for staked token weighted default\n")

for _, v := range *votes {
r.Results_float[v.Choice] += float64(v.Staking_balance) * math.Pow(10, -8)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
UPDATE voting_strategies
SET description = 'one address is simply only allowed one vote, assets do not come into play.'
WHERE key = 'one-address-one-vote';
UPDATE voting_strategies
SET description = 'a weight will be added for each NFT in a user address that matches the contract of the proposal'
WHERE key = 'balance-of-nfts';
6 changes: 6 additions & 0 deletions backend/migrations/000026_update_voting_strategy_desc.up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
UPDATE voting_strategies
SET description = 'A weight will be added for each NFT in a user address that matches the contract of the proposal'
WHERE key = 'balance-of-nfts';
UPDATE voting_strategies
SET description = 'One address is simply only allowed one vote, assets do not come into play.'
WHERE key = 'one-address-one-vote';
11 changes: 9 additions & 2 deletions frontend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
## Prerequisites

- [Yarn](https://classic.yarnpkg.com/lang/en/docs/install)
- [GoLang 1.6](https://golang.org/doc/install)
- [Node/NPM](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)
- [GoLang 1.16+](https://golang.org/doc/install)
- [Node/NPM v16](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)
- [Flow CLI](https://docs.onflow.org/flow-cli/install/)
- Note: See below for how install v0.30.2 (required)

Expand All @@ -14,6 +14,13 @@
yarn install
```

Installing Node via [NVM](https://github.com/nvm-sh/nvm#installation-and-update)
```bash
nvm install v16.13.0
nvm use 16
node -v
```

## Development

#### Contracts
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export const CommunityUsersForm = ({
<div className="is-flex flex-1">
<WrapperResponsive
tag="h5"
classNames="title is-6 mb-2 is-flex"
classNames="title is-6 is-flex is-align-items-center"
extraClassesMobile="mt-4"
>
{title}
Expand Down
27 changes: 7 additions & 20 deletions frontend/packages/client/src/components/CommunityAbout.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import React from 'react';
import Blockies from 'react-blockies';
import { kebabToString } from 'utils';
import { Title } from '.';

const CommunityMemberInfo = ({ name }) => {
return (
<div className="is-flex is-align-items-center py-3">
<div className="is-flex is-align-items-center py-1">
<div className="is-flex pr-4">
<Blockies seed={name} size={8} scale={4} className="blockies" />
</div>
Expand All @@ -13,14 +14,6 @@ const CommunityMemberInfo = ({ name }) => {
);
};

const Title = ({ role, styles = {} } = {}) => {
return (
<h6 className="small-text has-text-weight-bold is-uppercase" style={styles}>
{role}
</h6>
);
};

const CommunityAbout = ({
textAbout = '',
adminMembers = [],
Expand All @@ -31,10 +24,8 @@ const CommunityAbout = ({
return (
<div>
<div className="columns is-multiline mt-0">
<div className="column is-12">
<Title role={'About'} />
</div>
<div className="column is-12">
<div className="column is-12 pt-0">
<Title>About</Title>
<p className="mb-5 has-text-grey">{textAbout}</p>
</div>
<div className={`column is-12`}>
Expand All @@ -47,13 +38,9 @@ const CommunityAbout = ({
/>
</div>
<div className="column is-12">
<Title
role={'Details'}
styles={{ paddingBottom: isMobile ? '24px' : '48px' }}
/>
<div className="columns flex-1">
<div className="column is-6">
<Title role={'Strategies'} styles={{ paddingBottom: '24px' }} />
<Title>Strategies</Title>
{strategies.map((item, index) => (
<div
className="is-flex is-align-items-center py-1"
Expand Down Expand Up @@ -84,13 +71,13 @@ const CommunityAbout = ({
<div className="column is-12">
<div className="columns flex-1">
<div className="column is-6">
<Title role={'Admins'} styles={{ paddingBottom: '24px' }} />
<Title>Admin</Title>
{adminMembers.map((item, index) => (
<CommunityMemberInfo name={item.name} key={`member-${index}`} />
))}
</div>
<div className="column is-6">
<Title role={'Authors'} styles={{ paddingBottom: '24px' }} />
<Title>Authors</Title>
{authorsMembers.map((item, index) => (
<CommunityMemberInfo name={item.name} key={`member-${index}`} />
))}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ export default function StepThree({
/>
<input
type="text"
placeholder="Proposal threshold"
placeholder="Proposal Threshold"
name="proposal_threshold"
className="rounded-sm border-light p-3 column is-full is-full-mobile mt-4"
value={proposalThreshold}
Expand Down
Loading