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

feat: shows oshhhnap in voting modal #4242

Closed
Closed
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
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
"@ethersproject/wallet": "^5.7.0",
"@headlessui-float/vue": "^0.11.2",
"@headlessui/vue": "^1.7.13",
"@openzeppelin/merkle-tree": "^1.0.5",
"@pusher/push-notifications-web": "^1.1.0",
"@sentry/vite-plugin": "^2.5.0",
"@sentry/vue": "^7.55.2",
Expand All @@ -54,6 +55,7 @@
"ajv-formats": "^2.1.1",
"autolinker": "^4.0.0",
"bluebird": "^3.7.2",
"drand-client": "^1.2.1",
"graphql": "^16.6.0",
"graphql-tag": "^2.12.6",
"js-sha256": "^0.9.0",
Expand All @@ -62,6 +64,7 @@
"readable-stream": "3.6.0",
"remarkable": "^2.0.1",
"remove-markdown": "^0.5.0",
"tlock-js": "^0.7.0",
"typescript": "^5.0.4",
"v-viewer": "^3.0.11",
"vue": "^3.3.4",
Expand Down
44 changes: 37 additions & 7 deletions src/components/ModalVote.vue
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { shorten, getChoiceString, explorerUrl } from '@/helpers/utils';
import { getPower, voteValidation } from '@/helpers/snapshot';
import { ExtendedSpace, Proposal } from '@/helpers/interfaces';
import shutterEncryptChoice from '@/helpers/shutter';
import { timelockEncryptionForOshhhnap } from '@/helpers/oshhhnap';

const { web3Account } = useWeb3();

Expand Down Expand Up @@ -33,6 +34,7 @@ const { addVotedProposalId } = useProposals();
const { isGnosisAndNotSpaceNetwork } = useGnosis(props.space);

const isLoadingShutter = ref(false);
const isLoadingOshhnap = ref(false);

const symbols = computed(() =>
props.strategies.map(strategy => strategy.params.symbol || '')
Expand Down Expand Up @@ -69,19 +71,47 @@ async function voteShutter() {
});
}

async function voteOshhhnap() {
// TODO: Implement Oshhhnap
isLoadingOshhnap.value = true;
const timelockEncryptedChoice = await timelockEncryptionForOshhhnap(
JSON.stringify(props.selectedChoices),
props.proposal.id,
props.proposal.end
);

if (!timelockEncryptedChoice) return null;
const resultantVote = vote({
proposal: props.proposal,
choice: timelockEncryptedChoice,
privacy: 'oshhhnap',
reason: reason.value
});
isLoadingOshhnap.value = false;
return resultantVote;
}

async function vote(payload) {
return send(props.space, 'vote', payload);
}

async function handleSubmit() {
let result: { id: string; ipfs?: string } | null = null;
if (props.proposal.privacy === 'shutter') result = await voteShutter();
else
result = await vote({
proposal: props.proposal,
choice: props.selectedChoices,
reason: reason.value
});
switch (props.proposal.privacy) {
case 'shutter':
result = await voteShutter();
break;
case 'oshhhnap':
result = await voteOshhhnap();
break;
default:
result = await vote({
proposal: props.proposal,
choice: props.selectedChoices,
reason: reason.value
});
break;
}

console.log('Result', result);

Expand Down
2 changes: 1 addition & 1 deletion src/components/ModalVotingPrivacy.vue
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ defineProps<{

const emit = defineEmits(['close', 'update:selected']);

const types = ['shutter'];
const types = ['shutter', 'oshhhnap'];

function select(id) {
emit('update:selected', id);
Expand Down
4 changes: 3 additions & 1 deletion src/composables/useSharing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@ export function useSharing() {
const isSingleChoice =
payload.proposal.type === 'single-choice' ||
payload.proposal.type === 'basic';
const isPrivate = payload.proposal.privacy === 'shutter';
const isPrivate = ['shutter', 'oshhhnap'].includes(
payload.proposal.privacy
);
const votedText =
payload.choices && isSingleChoice && !isPrivate
? `I just voted "${payload.choices}" on`
Expand Down
64 changes: 64 additions & 0 deletions src/helpers/oshhhnap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { timelockDecrypt, timelockEncrypt } from 'tlock-js';
import { HttpChainClient, HttpCachingChain } from 'drand-client';

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

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

return client;
};

export async function timelockEncryption(message: string, duration: number) {
if (duration < 30)
throw new Error(
'Duration must be positive and greater or equal to 30 seconds'
);
const fastestNodeClient = await getFastestNode();
const latestRound = await fastestNodeClient.latest();
const chain = new HttpCachingChain(testnetUnchainedUrl);

const { period } = await chain.info();

const roundNumber = latestRound.round + Math.floor(duration / period);

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

return result;
}

export async function timelockEncryptionForOshhhnap(
message: string,
proposalId: string,
duration: number
) {
let result = await timelockEncryption(message, duration);

// We need to append the ID to the ciphertext, so we can decrypt it later
// and know which proposal it belongs to.
result = `${result}__ID__${proposalId}`;

return result;
}

export async function timelockDecryption(ciphertext: string) {
const fastestNodeClient = await getFastestNode();
const result = await timelockDecrypt(ciphertext, fastestNodeClient);
return result;
}

export async function timelockDecryptionForOshhhnap(ciphertext: string) {
// We need to remove the ID from the ciphertext, so we can decrypt it.
const [ciphertextWithoutId, proposalId] = ciphertext.split('__ID__');
const result = await timelockDecryption(ciphertextWithoutId);
return {
result,
proposalId
};
}
6 changes: 6 additions & 0 deletions src/locales/default.json
Original file line number Diff line number Diff line change
Expand Up @@ -713,6 +713,12 @@
"description": "Choices are encrypted and only visible once the voting period is over",
"tooltip": "This proposal has Shutter privacy enabled. All votes will be encrypted until the voting period has ended and the final score is calculated",
"url": "https://blog.shutter.network/announcing-shutter-governance-shielded-voting-for-daos/"
},
"oshhhnap": {
"label": "Oshhhnap",
"description": "Choices are encrypted and secured by the OSnap! protocol",
"tooltip": "This proposal has Oshhhnap privacy enabled. All votes will be encrypted and secured by the OSnap! protocol",
"url": "https://uma.xyz"
}
},
"proposalValidation": {
Expand Down
20 changes: 17 additions & 3 deletions src/plugins/safeSnap/components/HandleOutcomeUma.vue
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
<script setup lang="ts">
import { ExtendedSpace, Proposal, Results } from '@/helpers/interfaces';
import { ExtendedSpace, Proposal, Results, Vote } from '@/helpers/interfaces';
import { formatUnits } from '@ethersproject/units';
import { getInstance } from '@snapshot-labs/lock/plugins/vue3';
import networks from '@snapshot-labs/snapshot.js/src/networks.json';
import { sleep } from '@snapshot-labs/snapshot.js/src/utils';
import Plugin from '../index';
import type { Network } from '../types';
import { ensureRightNetwork } from './SafeTransactions.vue';
import { formatVotesResolutions } from '@/plugins/safeSnap/utils';

type Transaction = {
to: string;
Expand Down Expand Up @@ -41,6 +42,15 @@ const {
} = useTxStatus();
const { notify } = useFlashNotification();
const { quorum } = useQuorum(props);
const {
votes,
loadingVotes,
loadingMoreVotes,
profiles,
loadVotes,
loadMoreVotes,
loadSingleVote
} = useProposalVotes(props.proposal, 20);

const plugin = new Plugin();

Expand Down Expand Up @@ -78,11 +88,12 @@ function showProposeModal() {
voteResultsConfirmed.value = true;
}

const getTransactionsUma = () =>
const getTransactionsUma = () => {
props.batches.map(batch => {
const mainTx = batch.mainTransaction;
return [mainTx.to, Number(mainTx.operation), mainTx.value, mainTx.data];
});
};

const updateDetails = async () => {
loading.value = true;
Expand Down Expand Up @@ -143,11 +154,14 @@ const submitProposalUma = async () => {
const txPendingId = createPendingTransaction();
try {
await ensureRightNetwork(props.network);
await loadVotes({});
const voteResolution = formatVotesResolutions(votes.value);
const proposalSubmission = plugin.submitProposalUma(
getInstance().web3,
props.umaAddress,
props.proposal.ipfs,
getTransactionsUma()
getTransactionsUma(),
voteResolution
);
const step = await proposalSubmission.next();
if (step.value)
Expand Down
2 changes: 1 addition & 1 deletion src/plugins/safeSnap/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ export const UMA_MODULE_ABI = [
'function optimisticOracleV3() view returns (address)',
'function owner() view returns (address)',
'function proposalHashes(bytes32) view returns (bytes32)',
'function proposeTransactions(tuple(address to, uint8 operation, uint256 value, bytes data)[] transactions, bytes explanation)',
'function proposeTransactions(tuple(address to, uint8 operation, uint256 value, bytes data)[] transactions, bytes explanation, bytes encodedResolution)',
'function renounceOwnership()',
'function rules() view returns (string)',
'function setAvatar(address _avatar)',
Expand Down
5 changes: 3 additions & 2 deletions src/plugins/safeSnap/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -263,15 +263,16 @@ export default class Plugin {
web3: any,
moduleAddress: string,
explanation: string,
transactions: any
transactions: any,
encodedVoteResolutions: string
) {
const explanationBytes = toUtf8Bytes(explanation);
const tx = await sendTransaction(
web3,
moduleAddress,
UMA_MODULE_ABI,
'proposeTransactions',
[transactions, explanationBytes]
[transactions || [], explanationBytes, encodedVoteResolutions]
// [[["0xB8034521BB1a343D556e5005680B3F17FFc74BeD", 0, "0", "0x"]], '0x']
);
yield tx;
Expand Down
84 changes: 83 additions & 1 deletion src/plugins/safeSnap/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ import { isAddress } from '@ethersproject/address';
import { JsonRpcProvider } from '@ethersproject/providers';
import { keccak256 } from '@ethersproject/solidity';
import memoize from 'lodash/memoize';
import { Vote } from '@/helpers/interfaces';
import { StandardMerkleTree } from '@openzeppelin/merkle-tree';
import { ethers } from 'ethers';

import { SafeExecutionData, SafeTransaction } from '@/helpers/interfaces';
import getProvider from '@snapshot-labs/snapshot.js/src/utils/provider';
import SafeSnapPlugin, { MULTI_SEND_VERSION } from '../index';
import { createMultiSendTx, getMultiSend } from './multiSend';

export const mustBeEthereumAddress = memoize((address: string) => {
const startsWith0x = address?.startsWith('0x');
const isValidAddress = isAddress(address);
Expand Down Expand Up @@ -171,3 +173,83 @@ export async function fetchTextSignatures(
const { results } = await response.json();
return results.map(signature => signature.text_signature);
}

export const formatVotesResolutions = (votes: Vote[]) => {
let forVotes = new ethers.utils.BigNumber(0);
let againstVotes = new ethers.utils.BigNumber(0);
let abstainVotes = new ethers.utils.BigNumber(0);

const formattedVotes = votes.map(vote => {
const { vp, vp_by_strategy, choice } = vote;
if (choice === 1) {
forVotes = forVotes.add(ethers.utils.parseEther(String(vote.vp)));
}
if (choice === 2) {
againstVotes = againstVotes.add(ethers.utils.parseEther(String(vote.vp)));
}
if (choice === 3) {
abstainVotes = abstainVotes.add(ethers.utils.parseEther(String(vote.vp)));
}
return [
vote.voter,
vote.choice == 1
? ethers.utils.parseEther(String(vote.vp)).toString()
: 0,
vote.choice == 2
? ethers.utils.parseEther(String(vote.vp)).toString()
: 0,
vote.choice == 3 ? ethers.utils.parseEther(String(vote.vp)).toString() : 0
];
});

// (2)
const tree = StandardMerkleTree.of(formattedVotes, [
'address',
'uint256',
'uint256',
'uint256'
]);

// (3)
console.log('Merkle Root:', tree.root);

const proofData = {};
for (const [i, v] of tree.entries()) {
// (3)
const proof = tree.getProof(i);

proofData[v[0]] = {
voteFor: v[1],
voteAgainst: v[2],
voteAbstain: v[3],
proof
};
}
const votesAndProofs = JSON.stringify(proofData);

const calldata: string = ethers.utils.defaultAbiCoder.encode(
[
{
type: 'tuple',
components: [
{ name: 'forVotes', type: 'uint256' },
{ name: 'againstVotes', type: 'uint256' },
{ name: 'abstainVotes', type: 'uint256' },
{ name: 'voteMerkleRoot', type: 'bytes32' },
{ name: 'votesAndProofs', type: 'string' }
]
}
],
[
{
forVotes,
againstVotes,
abstainVotes,
voteMerkleRoot: tree.root,
votesAndProofs
}
]
);

return calldata;
};
2 changes: 1 addition & 1 deletion src/plugins/safeSnap/utils/umaModule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,7 @@ export const getModuleDetailsUmaGql = async (
symbol: bondDetails.symbol,
userBalance: bondDetails.currentUserBalance,
needsBondApproval: needsApproval,
noTransactions: true,
noTransactions: false,
activeProposal: false,
assertionEvent: undefined,
proposalExecuted: false,
Expand Down
Loading