Skip to content

Commit

Permalink
feat: finished vote
Browse files Browse the repository at this point in the history
Signed-off-by: Pablo Maldonado <pablomaldonadoturci@gmail.com>
  • Loading branch information
md0x committed Jun 16, 2023
1 parent 250a679 commit 92f1509
Show file tree
Hide file tree
Showing 9 changed files with 138 additions and 43 deletions.
87 changes: 63 additions & 24 deletions bacalhau-container/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ import addresses from "./addresses.json" assert { type: "json" }
import GovernorABI from "./contracts/GovernorContract.json" assert { type: "json" }
import TokenABI from "./contracts/DefiKicksDataGovernanceToken.json" assert { type: "json" }
import LilypadABI from "./contracts/LilypadEventsUpgradeable.json" assert { type: "json" }
import { timelockDecrypt, timelockEncrypt } from "tlock-js"
import { HttpChainClient, HttpCachingChain } from "drand-client"

import { getProposals } from "./tiles.js"
import { getProposals, getVotes } from "./tiles.js"

const getIpfsFile = async (ipfsHash) => {
let config = {
Expand Down Expand Up @@ -63,13 +65,27 @@ async function getIpfsHash(adapterId, nodeUrl, contractAddress) {
return ipfsHash
}

export const timelockDecryption = async (ciphertext) => {
const fastestNodeClient = await getFastestNode()
const result = await timelockDecrypt(ciphertext, fastestNodeClient)
return result
}

const testnetUnchainedUrl =
"https://pl-eu.testnet.drand.sh/7672797f548f3f4748ac4bf3352fc6c6b6468c9ad40ad456a397545c6e2df5bf"

const getFastestNode = async () => {
const chain = new HttpCachingChain(testnetUnchainedUrl)
const client = new HttpChainClient(chain)

return client
}

async function run() {
const proposalName = process.env.PROPOSAL_NAME

const proposalData = await getProposals()

// const test2 = await getIpfsHash(proposalData[1].name,process.env.NODE_URL,addresses.registry)

console.log("Proposal Data: ", JSON.stringify(proposalData, null, 2))

const proposal = proposalData.find((p) => p.name === proposalName)
Expand All @@ -81,42 +97,65 @@ async function run() {

const jobId = proposal?.jobId

const test = await getIpfsFile("QmNjkECL37oveLZuFuNHNWfpYSaWeBUYFkrDPeoqQWoTLQ")
const votes = await getVotes(proposal.id)

// console.log(test)
const decryptedVotes = []

const provider = new ethers.providers.JsonRpcProvider(nodeUrl)
for (const vote of votes) {
let message
try {
message = await timelockDecryption(vote.cyphertext)
} catch (e) {}
decryptedVotes.push({
...vote,
message,
})
}

const governorContract = new ethers.Contract(addresses.governor, GovernorABI, provider)
const signedVotes = []

// const latestBlock = await governorContract.provider.getBlockNumber()
for (const vote of decryptedVotes) {
const recoveredAddress = ethers.utils.verifyMessage(vote.message, vote.signature)
if (recoveredAddress === vote.account) {
signedVotes.push(vote)
}
}

// const voteResolution = governorContract.filters.VoteResolutionRequested()
// const proposals = await governorContract.queryFilter(
// voteResolution,
// latestBlock - 1000,
// "latest"
// )
const provider = new ethers.providers.JsonRpcProvider(nodeUrl)

// const ids = proposals.map((p) => p.args.proposalId.toString())
// const uniqueIds = ids.filter((v, i, a) => a.indexOf(v) === i)
const governorContract = new ethers.Contract(addresses.governor, GovernorABI, provider)

// const jobIds = []
// for (const id of uniqueIds) {
// const proposal = await governorContract.proposals(id)
// jobIds.push(proposal.bridgeId.toString())
// }
const proposalStruct = await governorContract.proposals(proposalId)

const tokenContract = new ethers.Contract(addresses.token, TokenABI, provider)

const forVotes = (await tokenContract.totalSupply()).div(2).add(1)
const againstVotes = BigNumber.from("1")
const abstainVotes = BigNumber.from("1")
let forVotes = BigNumber.from(0)
let againstVotes = BigNumber.from(0)
let abstainVotes = BigNumber.from(0)
const voteMerkleRoot = "0x6173646173646173646173646461000000000000000000000000000000000000"
const data = JSON.stringify({
info: "arbitrary resolution data",
})

for (const vote of signedVotes) {
const balance = await tokenContract.balanceOfAt(
vote.account,
proposalStruct.snapshotId.toString()
)
const voteObj = JSON.parse(vote.message)
forVotes = forVotes.add(balance)
if (voteObj.vote === "for") {
forVotes.add(balance)
}
if (voteObj.vote === "against") {
againstVotes.add(balance)
}
}

abstainVotes = (await tokenContract.totalSupplyAt(proposalStruct.snapshotId.toString())).sub(
forVotes.add(againstVotes)
)

const calldata = ethers.utils.defaultAbiCoder.encode(
[
{
Expand Down
5 changes: 4 additions & 1 deletion bacalhau-container/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,7 @@ Cast commands:
Get bridge address (Lily)
```bash
cast call 0xF8BB525439b3C908a66430fbb436865C3Dc4ebDF "bridge()(address)" --rpc-url https://api.calibration.node.glif.io/rpc/v0
```
```


PROPOSAL_NAME="Aave" NODE_URL="https://api.calibration.node.glif.io/rpc/v0" node ./index.js
9 changes: 9 additions & 0 deletions bacalhau-container/tiles.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,12 @@ export async function getProposals() {
const proposals = await getTileContent("defikicks", "proposals")
return proposals.data
}

export async function getVotes(name) {
const votes = await getTileContent("defikicks-votes", name)
return votes.data
}

export async function storeVotes(name, votes) {
return await saveTileContent("defikicks-votes", name, { data: votes })
}
6 changes: 3 additions & 3 deletions web/hooks/useLibp2pPubSub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,9 +108,9 @@ export default function usePubSub() {
libp2pNode.addEventListener("self:peer:update", ({ detail: { peer } }) => {
const multiaddrs = peer.addresses.map(({ multiaddr }) => multiaddr)

console.log(
`changed multiaddrs: peer ${peer.id.toString()} multiaddrs: ${multiaddrs}`
)
// console.log(
// `changed multiaddrs: peer ${peer.id.toString()} multiaddrs: ${multiaddrs}`
// )
})

libp2pNode.services.pubsub.addEventListener("message", async (message) => {
Expand Down
2 changes: 0 additions & 2 deletions web/hooks/useProposals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,6 @@ export default function useProposals() {
const latestBlock = await contract.provider.getBlockNumber()
const proposalsEvents = await contract.queryFilter(filter, latestBlock - 1000, "latest")

console.log(proposalsEvents)

const distinctProposalsEvents = proposalsEvents.filter(
(event, index, self) =>
index === self.findIndex((e) => e.args.proposalId === event.args.proposalId)
Expand Down
2 changes: 1 addition & 1 deletion web/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ function Home() {

const { data } = useTVLData()

console.log("tvlData", JSON.stringify(data, null, 2))
// console.log("tvlData", JSON.stringify(data, null, 2))

const isConnected = typeof account === "string" && !!library

Expand Down
59 changes: 48 additions & 11 deletions web/pages/vote.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { CeramicClient } from "@ceramicnetwork/http-client"
import { loadDocumentByController } from "../hooks/useTVLData"

import { TileDocument } from "@ceramicnetwork/stream-tile"
import { getTileContent, saveTileContent } from "../utils/tiles"
import { getTileContent, getVotes, saveTileContent, storeVotes } from "../utils/tiles"

function Home() {
const [messageInput, setMessageInput] = useState("")
Expand Down Expand Up @@ -66,14 +66,51 @@ function Home() {
})
}

const voteFor = (id: string) => {
// Implementar lógica de votación a favor
console.log(`Voted for proposal with ID: ${id}`)
const vote = async (proposal: any, voteString: string) => {
const votes = await getVotes(proposal.id)
const newVotes = [...(votes && votes.length ? votes : [])]

if (newVotes.find((v) => v.account === account)) {
alert("You already voted")
return
}

const votePhase = 5 * 60

const message = {
proposalId: proposal.id,
proposalName: proposal.name,
proposalDescription: proposal.description,
proposalAdapter: proposal.ipfsHash,
vote: voteString,
}

const messageString = JSON.stringify(message)

const signature = await library?.getSigner().signMessage(messageString)

const cyphertext = await timelockEncryption(messageString, 30)

const vote = {
proposalId: proposal.id,
cyphertext,
account,
signature,
}

newVotes.push(vote)

console.log("Your vote", JSON.stringify(vote, null, 2))

await storeVotes(proposal.id, newVotes)
}

const voteFor = async (proposal: any) => {
await vote(proposal, "for")
}

const voteAgainst = (id: string) => {
// Implementar lógica de votación en contra
console.log(`Voted against proposal with ID: ${id}`)
const voteAgainst = async (proposal: any) => {
await vote(proposal, "against")
}

const requestResolution = async (id: string) => {
Expand Down Expand Up @@ -161,14 +198,14 @@ function Home() {
<Button
variant="contained"
color="primary"
onClick={() => voteFor(proposal.id)}
onClick={() => voteFor(proposal)}
>
Vote For
</Button>
<Button
variant="contained"
color="secondary"
onClick={() => voteAgainst(proposal.id)}
onClick={() => voteAgainst(proposal)}
>
Vote Against
</Button>
Expand All @@ -179,10 +216,10 @@ function Home() {
</Grid>
))}
</Grid>
<Button variant="contained" color="secondary" onClick={() => sendMessage()}>
{/* <Button variant="contained" color="secondary" onClick={() => voteFor(proposals[0])}>
{" "}
Send Message{" "}
</Button>
</Button> */}
</div>
)
}
Expand Down
9 changes: 9 additions & 0 deletions web/utils/tiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,12 @@ export async function getProposals() {
export async function storeProposals(proposals: any[]) {
return await saveTileContent("defikicks", "proposals", { data: proposals })
}

export async function getVotes(name) {
const votes: any = await getTileContent("defikicks-votes", name)
return votes.data
}

export async function storeVotes(name, votes: any[]) {
return await saveTileContent("defikicks-votes", name, { data: votes })
}
2 changes: 1 addition & 1 deletion web/utils/tlock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export const timelockEncryption = async (message: string, duration: number) => {
const roundNumber = latestRound.round + Math.floor(duration / period)

const result = await timelockEncrypt(
latestRound.round + roundNumber,
latestRound.round + 1,
Buffer.from(message),
fastestNodeClient
)
Expand Down

0 comments on commit 92f1509

Please sign in to comment.