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: add my delegatee to Delegates page #1110

Merged
merged 16 commits into from
Jan 27, 2025
Merged
Show file tree
Hide file tree
Changes from 14 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
233 changes: 227 additions & 6 deletions apps/ui/src/components/SpaceDelegates.vue
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
<script setup lang="ts">
import { sanitizeUrl } from '@braintree/sanitize-url';
import { useInfiniteQuery } from '@tanstack/vue-query';
import { getAddress } from '@ethersproject/address';
import {
useInfiniteQuery,
useQuery,
useQueryClient
} from '@tanstack/vue-query';
import removeMarkdown from 'remove-markdown';
import { getDelegationNetwork } from '@/helpers/delegation';
import { getGenericExplorerUrl } from '@/helpers/explorer';
import { getNames } from '@/helpers/stamp';
import { _n, _p, _vp, shorten } from '@/helpers/utils';
import { getNetwork, supportsNullCurrent } from '@/networks';
import { SNAPSHOT_URLS } from '@/networks/offchain';
import { DelegationType, Space, SpaceMetadataDelegation } from '@/types';
import { RequiredProperty, Space, SpaceMetadataDelegation } from '@/types';

const props = defineProps<{
space: Space;
Expand All @@ -14,6 +22,8 @@ const props = defineProps<{

const delegateModalOpen = ref(false);
const delegateModalState = ref<{ delegatee: string } | null>(null);
const isUndelegating = ref(false);
const undelegateFn = ref(undelegate);
const sortBy = ref(
'delegatedVotes-desc' as
| 'delegatedVotes-desc'
Expand All @@ -22,15 +32,22 @@ const sortBy = ref(
| 'tokenHoldersRepresentedAmount-asc'
);
const { setTitle } = useTitle();
const { getDelegates } = useDelegates(
props.delegation.apiType as DelegationType,
props.delegation.apiUrl as string,
props.delegation.contractAddress as string,
const { getDelegates, getDelegation } = useDelegates(
props.delegation as RequiredProperty<typeof props.delegation>,
props.space
);
const { getDelegatee } = useActions();
const { getCurrent } = useMetaStore();
const { web3 } = useWeb3();
const actions = useActions();
const queryClient = useQueryClient();

const spaceKey = computed(() => `${props.space.network}:${props.space.id}`);
const delegationNetworkId = computed(() => {
if (!props.delegation.chainId) return null;

return getDelegationNetwork(props.delegation.chainId);
});

const {
data,
Expand Down Expand Up @@ -65,6 +82,107 @@ const {
}
});

const { data: delegatee } = useQuery({
queryKey: [
'delegatees',
props.delegation.contractAddress,
() => web3.value.account
],
queryFn: () => getCurrentDelegatee(),
enabled: !!web3.value.account && !web3.value.authLoading
});

async function fetchDelegateRegistryDelegatee() {
const delegation = await getDelegation(web3.value.account);

if (!delegation) return null;

const [names, votingPowers, [apiDelegate]] = await Promise.all([
getNames([delegation.delegate]),
getNetwork(props.space.network).actions.getVotingPower(
props.space.id,
props.space.strategies,
props.space.strategies_params,
props.space.strategies_parsed_metadata,
web3.value.account,
{
at: supportsNullCurrent(props.space.network)
? null
: getCurrent(props.space.network) || 0,
chainId: props.space.snapshot_chain_id
}
),
getDelegates({
first: 1,
skip: 0,
orderBy: 'delegatedVotes',
orderDirection: 'desc',
where: {
// NOTE: this is delegate registry, needs to be checksummed
user: getAddress(delegation.delegate)
}
})
]);

const balance = votingPowers.reduce(
(acc, b) => acc + Number(b.value) / 10 ** b.cumulativeDecimals,
0
);

return {
id: delegation.delegate,
balance,
share: apiDelegate ? balance / Number(apiDelegate.delegatedVotes) : 1,
name: names[delegation.delegate]
};
}

async function fetchGovernorSubgraphDelegatee() {
const delegateeData = await getDelegatee(
props.delegation,
web3.value.account
);

if (!delegateeData) return null;

const [names, [apiDelegate]] = await Promise.all([
getNames([delegateeData.address]),
getDelegates({
first: 1,
skip: 0,
orderBy: 'delegatedVotes',
orderDirection: 'desc',
where: {
// NOTE: This is subgraph, needs to be lowercase
user: delegateeData.address.toLocaleLowerCase()
}
})
]);

return {
id: delegateeData.address,
balance: Number(delegateeData.balance) / 10 ** delegateeData.decimals,
share: apiDelegate
? Number(delegateeData.balance) / Number(apiDelegate.delegatedVotesRaw)
: 1,
name: names[delegateeData.address]
};
}

async function getCurrentDelegatee() {
if (!props.delegation.apiType || !props.delegation.chainId) return null;

if (!web3.value.account) {
return null;
}

if (props.delegation.apiType === 'governor-subgraph') {
return fetchGovernorSubgraphDelegatee();
} else if (props.delegation.apiType === 'delegate-registry') {
return fetchDelegateRegistryDelegatee();
}
}

function getExplorerUrl(address: string, type: 'address' | 'token') {
let url: string | null = null;
if (props.delegation.chainId) {
Expand Down Expand Up @@ -95,6 +213,38 @@ function handleDelegateClick(delegatee?: string) {
delegateModalOpen.value = true;
}

async function undelegate() {
if (
!props.delegation.apiType ||
!props.delegation.chainId ||
!props.delegation.contractAddress
) {
return null;
}

return actions.delegate(
props.space,
props.delegation.apiType,
null,
props.delegation.contractAddress,
props.delegation.chainId
);
}

function handleUndelegateConfirmed() {
queryClient.invalidateQueries({
queryKey: ['delegates', props.delegation.contractAddress]
});

queryClient.invalidateQueries({
queryKey: [
'delegatees',
props.delegation.contractAddress,
web3.value.account
]
});
}

watchEffect(() => setTitle(`Delegates - ${props.space.name}`));
</script>

Expand Down Expand Up @@ -143,6 +293,69 @@ watchEffect(() => setTitle(`Delegates - ${props.space.name}`));
</UiButton>
</UiTooltip>
</div>

<div v-if="delegatee" class="mb-3">
<UiLabel label="Delegating to" />
<div class="w-full truncate px-4">
<div class="flex w-full space-x-3 truncate border-b py-3">
<AppLink
:to="{
name: 'space-user-statement',
params: {
space: spaceKey,
user: delegatee.id
}
}"
class="w-full flex justify-between items-center"
>
<UiStamp :id="delegatee.id" type="avatar" :size="32" class="mr-3" />
<div class="flex-1 leading-[22px]">
<h4
class="text-skin-link"
v-text="delegatee.name || shorten(delegatee.id)"
/>
<div
class="text-skin-text text-[17px]"
v-text="shorten(delegatee.id)"
/>
</div>
<div
v-if="delegatee.balance"
class="w-[150px] flex flex-col sm:shrink-0 text-right justify-center leading-[22px] truncate"
>
<h4 class="text-skin-link truncate">
{{ _vp(delegatee.balance) }}
{{ space.voting_power_symbol }}
</h4>
<div class="text-[17px]" v-text="_p(delegatee.share)" />
</div>
</AppLink>
<div class="flex items-center justify-center">
<UiDropdown>
<template #button>
<UiButton class="!p-0 !border-0 !h-[auto] !bg-transparent">
<IH-dots-horizontal class="text-skin-link" />
</UiButton>
</template>
<template #items>
<UiDropdownItem v-slot="{ active }">
<button
type="button"
class="flex items-center gap-2"
:class="{ 'opacity-80': active }"
@click="isUndelegating = true"
>
<IH-user-remove />
Undelegate
</button>
</UiDropdownItem>
</template>
</UiDropdown>
</div>
</div>
</div>
</div>

<UiLabel label="Delegates" sticky />
<div class="text-left table-fixed w-full">
<div
Expand Down Expand Up @@ -338,6 +551,14 @@ watchEffect(() => setTitle(`Delegates - ${props.space.name}`));
:initial-state="delegateModalState"
@close="delegateModalOpen = false"
/>
<ModalTransactionProgress
v-if="delegationNetworkId"
:open="isUndelegating"
:network-id="delegationNetworkId"
:execute="undelegateFn"
@confirmed="handleUndelegateConfirmed"
@close="isUndelegating = false"
/>
</teleport>
</template>
</template>
34 changes: 22 additions & 12 deletions apps/ui/src/composables/useActions.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { getInstance } from '@snapshot-labs/lock/plugins/vue3';
import { getDelegationNetwork } from '@/helpers/delegation';
import { registerTransaction } from '@/helpers/mana';
import { getNetwork, getReadWriteNetwork, metadataNetwork } from '@/networks';
import { STARKNET_CONNECTORS } from '@/networks/common/constants';
import { METADATA } from '@/networks/starknet';
import { Connector, ExecutionInfo, StrategyConfig } from '@/networks/types';
import {
ChainId,
Expand All @@ -13,6 +13,7 @@ import {
Proposal,
Space,
SpaceMetadata,
SpaceMetadataDelegation,
SpaceSettings,
Statement,
User,
Expand Down Expand Up @@ -539,23 +540,19 @@ export function useActions() {
async function delegate(
space: Space,
delegationType: DelegationType,
delegatee: string,
delegatee: string | null,
delegationContract: string,
chainId: ChainId
) {
if (!web3.value.account) return await forceLogin();

const isEvmNetwork = typeof chainId === 'number';
const actionNetwork = isEvmNetwork
? 'eth'
: (Object.entries(METADATA).find(
([, metadata]) => metadata.chainId === chainId
)?.[0] as NetworkID);
if (!actionNetwork) throw new Error('Failed to detect action network');
if (!web3.value.account) {
await forceLogin();
return null;
}

const actionNetwork = getDelegationNetwork(chainId);
const network = getReadWriteNetwork(actionNetwork);

await wrapPromise(
return wrapPromise(
actionNetwork,
network.actions.delegate(
auth.web3,
Expand All @@ -569,6 +566,18 @@ export function useActions() {
);
}

async function getDelegatee(
delegation: SpaceMetadataDelegation,
delegator: string
) {
if (!delegation.chainId) throw new Error('Chain ID is missing');

const actionNetwork = getDelegationNetwork(delegation.chainId);
const network = getReadWriteNetwork(actionNetwork);

return network.actions.getDelegatee(auth.web3, delegation, delegator);
}

async function followSpace(networkId: NetworkID, spaceId: string) {
if (!web3.value.account) {
await forceLogin();
Expand Down Expand Up @@ -669,6 +678,7 @@ export function useActions() {
updateSettingsRaw: wrapWithErrors(updateSettingsRaw),
deleteSpace: wrapWithErrors(deleteSpace),
delegate: wrapWithErrors(delegate),
getDelegatee: wrapWithErrors(getDelegatee),
followSpace: wrapWithErrors(followSpace),
unfollowSpace: wrapWithErrors(unfollowSpace),
updateUser: wrapWithErrors(updateUser),
Expand Down
Loading