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

Delegation options & status updates #628

Merged
merged 3 commits into from
Aug 9, 2023
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
3 changes: 2 additions & 1 deletion src/modules/explorer/pages/DAOList/components/DAOItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ const Container = styled(Grid)(({ theme }: { theme: Theme }) => ({
},

["@media (max-width:1155px)"]: {
minHeight: 123
minHeight: 123,
maxWidth: 480
},

["@media (max-width:1030px)"]: {},
Expand Down
53 changes: 33 additions & 20 deletions src/modules/explorer/pages/User/components/DelegationBanner.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/* eslint-disable react-hooks/exhaustive-deps */
import React, { Fragment, useEffect, useState } from "react"
import { Grid, Theme, Typography, styled } from "@material-ui/core"
import { CircularProgress, Grid, Theme, Typography, styled } from "@material-ui/core"
import { useDAO } from "services/services/dao/hooks/useDAO"
import { Edit } from "@material-ui/icons"
import { DelegationDialog } from "./DelegationModal"
Expand All @@ -10,8 +11,7 @@ import BigNumber from "bignumber.js"
import { parseUnits } from "services/contracts/utils"

export enum DelegationsType {
ACCEPTING_DELEGATION = "ACCEPTING_DELEGATION",
NOT_ACCEPTING_DELEGATION = "NOT_ACCEPTING_DELEGATION",
NOT_DELEGATING = "NOT_DELEGATING",
DELEGATING = "DELEGATING"
}

Expand All @@ -38,9 +38,7 @@ const Balance = styled(Typography)({

export const matchTextToStatus = (value: DelegationsType | undefined) => {
switch (value) {
case DelegationsType.ACCEPTING_DELEGATION:
return "Accepting delegations"
case DelegationsType.NOT_ACCEPTING_DELEGATION:
case DelegationsType.NOT_DELEGATING:
return "Not currently accepting delegations or delegating"
case DelegationsType.DELEGATING:
return "Delegating to "
Expand All @@ -53,26 +51,35 @@ export const Delegation: React.FC<{ daoId: string }> = ({ daoId }) => {
const { data: dao } = useDAO(daoId)
const { network, tezos, account, connect } = useTezos()

const { data: delegatedTo } = useDelegationStatus(dao?.data.token.contract)
const [delegationStatus, setDelegationStatus] = useState<DelegationsType>(DelegationsType.NOT_ACCEPTING_DELEGATION)
const { data: delegatedTo, isLoading, refetch } = useDelegationStatus(dao?.data.token.contract)
const [delegationStatus, setDelegationStatus] = useState<DelegationsType>(DelegationsType.NOT_DELEGATING)
const [openModal, setOpenModal] = useState(false)
const { data: delegateVoteBalances } = useDelegationVoteWeight(dao?.data.token.contract)
const { data: delegateVoteBalances } = useDelegationVoteWeight(dao?.data.token.contract, dao?.data.address)
const [voteWeight, setVoteWeight] = useState(new BigNumber(0))
console.log("voteWeight: ", voteWeight.toString())
// console.log("voteWeight: ", voteWeight.toString())

useEffect(() => {
refetch()

setTimeout(() => {
if (delegatedTo === account) {
setDelegationStatus(DelegationsType.DELEGATING)
} else if (delegatedTo && delegatedTo !== account) {
setDelegationStatus(DelegationsType.DELEGATING)
} else {
setDelegationStatus(DelegationsType.NOT_DELEGATING)
}
}, 2000)
}, [])

const onCloseAction = () => {
setOpenModal(false)
}

useEffect(() => {
if (delegatedTo === account) {
setDelegationStatus(DelegationsType.ACCEPTING_DELEGATION)
} else if (delegatedTo && delegatedTo !== account) {
setDelegationStatus(DelegationsType.DELEGATING)
} else {
setDelegationStatus(DelegationsType.NOT_ACCEPTING_DELEGATION)
}
}, [delegatedTo, account])
refetch()
console.log(delegatedTo)
}, [delegationStatus, setDelegationStatus])

useEffect(() => {
let totalVoteWeight = new BigNumber(0)
Expand Down Expand Up @@ -124,8 +131,14 @@ export const Delegation: React.FC<{ daoId: string }> = ({ daoId }) => {
</Grid>
</Grid>
<Subtitle variant="body1">
{matchTextToStatus(delegationStatus)}
{delegationStatus === DelegationsType.DELEGATING ? delegatedTo : null}
{isLoading ? (
<CircularProgress color="secondary" />
) : (
<>
{matchTextToStatus(delegationStatus)}
{delegationStatus === DelegationsType.DELEGATING ? delegatedTo : null}
</>
)}
</Subtitle>
</Grid>
<DelegationDialog
Expand Down
72 changes: 33 additions & 39 deletions src/modules/explorer/pages/User/components/DelegationModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,25 +26,16 @@ const AddressTextField = styled(TextField)({
})

export enum ActionTypes {
ACCEPT_DELEGATIONS = "ACCEPT_DELEGATIONS",
DELEGATE = "DELEGATE",
CHANGE_DELEGATE = "CHANGE_DELEGATE",
STOP_ACCEPTING_DELEGATIONS = "STOP_ACCEPTING_DELEGATIONS",
STOP_DELEGATING = "STOP_DELEGATING"
SET_DELEGATE = "SET_DELEGATE",
NOT_DELEGATING = "NOT_DELEGATING"
}

const matchTextToAction = (value: ActionTypes) => {
switch (value) {
case ActionTypes.ACCEPT_DELEGATIONS:
return "Accept Delegations"
case ActionTypes.DELEGATE:
return "Delegate"
case ActionTypes.CHANGE_DELEGATE:
return "Change Delegate"
case ActionTypes.STOP_ACCEPTING_DELEGATIONS:
return "Stop Accepting Delegations"
case ActionTypes.STOP_DELEGATING:
return "Stop Delegating"
case ActionTypes.SET_DELEGATE:
return "Enter delegate address"
case ActionTypes.NOT_DELEGATING:
return "I want to own my voting power"
default:
return
}
Expand All @@ -58,9 +49,9 @@ export const DelegationDialog: React.FC<{
delegationStatus: DelegationsType
delegatedTo: string | null | undefined
}> = ({ status, onClose, open, setDelegationStatus, delegationStatus, delegatedTo }) => {
const [options, setOptions] = useState<ActionTypes[]>([])
const [options, setOptions] = useState<ActionTypes[]>([ActionTypes.NOT_DELEGATING, ActionTypes.SET_DELEGATE])
const [selectedOption, setSelectedOption] = useState()
const { mutate: delegateToken } = useTokenDelegate()
const { mutate: delegateToken, data: tokenData } = useTokenDelegate()
const daoId = useDAOID()
const { data, cycleInfo } = useDAO(daoId)
const { tezos, connect, network, account } = useTezos()
Expand All @@ -81,37 +72,39 @@ export const DelegationDialog: React.FC<{
}

const updateStatus = () => {
if (selectedOption === ActionTypes.DELEGATE || selectedOption === ActionTypes.CHANGE_DELEGATE) {
if (selectedOption === ActionTypes.SET_DELEGATE) {
if (newDelegate && data?.data.token.contract) {
delegateToken({ tokenAddress: data?.data.token.contract, delegateAddress: newDelegate })
delegateToken(
{ tokenAddress: data?.data.token.contract, delegateAddress: newDelegate },
{ onSuccess: () => setDelegationStatus(DelegationsType.DELEGATING) }
)
return
}
} else if (
selectedOption === ActionTypes.STOP_ACCEPTING_DELEGATIONS ||
selectedOption === ActionTypes.STOP_DELEGATING
) {
} else if (selectedOption === ActionTypes.NOT_DELEGATING) {
if (data?.data.token.contract) {
delegateToken({ tokenAddress: data?.data.token.contract, delegateAddress: null })
}
} else if (selectedOption === ActionTypes.ACCEPT_DELEGATIONS) {
if (data?.data.token.contract && account) {
delegateToken({ tokenAddress: data?.data.token.contract, delegateAddress: account })
delegateToken(
{ tokenAddress: data?.data.token.contract, delegateAddress: null },
{
onSuccess: () => {
setDelegationStatus(DelegationsType.NOT_DELEGATING)
return
}
}
)
}
return
}
}

const getOptionsByStatus = (status: DelegationsType | undefined) => {
switch (status) {
case DelegationsType.NOT_ACCEPTING_DELEGATION:
const optionsOne = [ActionTypes.ACCEPT_DELEGATIONS, ActionTypes.DELEGATE]
case DelegationsType.NOT_DELEGATING:
const optionsOne = [ActionTypes.SET_DELEGATE]
setOptions(optionsOne)
break
case DelegationsType.ACCEPTING_DELEGATION:
const optionsTwo = [ActionTypes.STOP_ACCEPTING_DELEGATIONS]
setOptions(optionsTwo)
break
case DelegationsType.DELEGATING:
const optionsThree = [ActionTypes.CHANGE_DELEGATE, ActionTypes.STOP_DELEGATING, ActionTypes.ACCEPT_DELEGATIONS]
setOptions(optionsThree)
const optionsTwo = [ActionTypes.NOT_DELEGATING]
setOptions(optionsTwo)
break
}
}
Expand Down Expand Up @@ -146,8 +139,7 @@ export const DelegationDialog: React.FC<{
name="radio-buttons"
inputProps={{ "aria-label": "A" }}
/>
{item === selectedOption &&
(selectedOption === ActionTypes.DELEGATE || selectedOption === ActionTypes.CHANGE_DELEGATE) ? (
{item === selectedOption && selectedOption === ActionTypes.SET_DELEGATE ? (
<AddressTextField
onChange={e => {
setNewDelegate(e.target.value)
Expand All @@ -163,7 +155,9 @@ export const DelegationDialog: React.FC<{
})}

<Grid container direction="row" justifyContent="flex-end">
<SmallButton onClick={saveInfo}>Submit</SmallButton>
<SmallButton disabled={selectedOption === undefined} onClick={saveInfo}>
Submit
</SmallButton>
</Grid>
</Grid>
</ResponsiveDialog>
Expand Down
109 changes: 83 additions & 26 deletions src/services/bakingBad/delegations/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Network } from "services/beacon"
import { networkNameMap } from ".."
import { DelegationDTO, TokenDelegationDTO, UserDelegateBalance } from "./types"
import { getUserTokenBalance } from "../tokenBalances"
import BigNumber from "bignumber.js"

export const getLatestDelegation = async (daoAddress: string, network: Network) => {
const url = `https://api.${networkNameMap[network]}.tzkt.io/v1/operations/delegations?sender=${daoAddress}&status=applied`
Expand All @@ -21,6 +22,7 @@ export const getLatestDelegation = async (daoAddress: string, network: Network)

export const getTokenDelegation = async (tokenAddress: string, account: string, network: Network) => {
const url = `https://api.${networkNameMap[network]}.tzkt.io/v1/contracts/${tokenAddress}/bigmaps/delegates/keys?key.eq=${account}&active=true`
console.log("urlssdasd: ", url)
const response = await fetch(url)

if (!response.ok) {
Expand All @@ -38,44 +40,99 @@ export const getTokenDelegation = async (tokenAddress: string, account: string,
return delegatedTo
}

export const getTokenDelegationVoteWeight = async (tokenAddress: string, account: string, network: Network) => {
const selfBalance = await getUserTokenBalance(account, network, tokenAddress)
export const getUserDAODepositBalance = async (account: string, network: Network, daoAddress: string) => {
const url = `https://api.${network}.tzkt.io/v1/contracts/${daoAddress}/bigmaps/freeze_history/keys?key.eq=${account}`

if (!selfBalance) {
throw new Error("Could not fetch delegate token balance from the TZKT API")
}

const url = `https://api.${networkNameMap[network]}.tzkt.io/v1/contracts/${tokenAddress}/bigmaps/delegates/keys?value.eq=${account}&active=true`
const response = await fetch(url)

if (!response.ok) {
throw new Error("Failed to fetch token delegations from TZKT API")
}

const resultingDelegations: TokenDelegationDTO[] = await response.json()
const userStakedBalances = await response.json()

const delegateBalance: UserDelegateBalance = {
address: account,
balance: selfBalance
}
let userDAODepositBalance = new BigNumber(0)

if (resultingDelegations.length === 0) {
return [delegateBalance]
if (userStakedBalances && userStakedBalances[0]) {
const userStakedBalance = new BigNumber(userStakedBalances[0].value.staked)
const userCurrentUnstakedBalance = new BigNumber(userStakedBalances[0].value.current_unstaked)
const userPastUnstakedBalance = new BigNumber(userStakedBalances[0].value.past_unstaked)

userDAODepositBalance = userStakedBalance.plus(userCurrentUnstakedBalance).plus(userPastUnstakedBalance)
}

const delegatedAddressBalances: UserDelegateBalance[] = []
return userDAODepositBalance.toString()
}

await Promise.all(
resultingDelegations.map(async del => {
const balance = await getUserTokenBalance(del.key, network, tokenAddress)
if (balance) {
delegatedAddressBalances.push({
address: del.key,
balance: balance
})
export const getTokenDelegationVoteWeight = async (
tokenAddress: string,
account: string,
network: Network,
daoContract?: string
) => {
const tokenDelegationStatus = await getTokenDelegation(tokenAddress, account, network)
console.log("tokenDelegationStatus: ", tokenDelegationStatus)
if (tokenDelegationStatus && tokenDelegationStatus !== account) {
return []
} else {
const selfBalance = await getUserTokenBalance(account, network, tokenAddress)
if (!selfBalance) {
throw new Error("Could not fetch delegate token balance from the TZKT API")
}
console.log("selfBalance: ", selfBalance)

let selfDAOBalance

console.log("daoContract: ", daoContract)
if (daoContract) {
selfDAOBalance = await getUserDAODepositBalance(account, network, daoContract)
console.log("selfDAOBalance: ", selfDAOBalance)
if (!selfDAOBalance) {
throw new Error("Could not fetch delegate dao balance from the TZKT API")
}

const url = `https://api.${networkNameMap[network]}.tzkt.io/v1/contracts/${tokenAddress}/bigmaps/delegates/keys?value.eq=${account}&active=true`
console.log("ursssssl: ", url)
const response = await fetch(url)

if (!response.ok) {
throw new Error("Failed to fetch token delegations from TZKT API")
}

const resultingDelegations: TokenDelegationDTO[] = await response.json()

const delegateBalance: UserDelegateBalance = {
address: account,
balance: selfDAOBalance
? new BigNumber(selfBalance).plus(new BigNumber(selfDAOBalance)).toString()
: selfBalance
}

if (resultingDelegations.length === 0) {
return [delegateBalance]
}
})
)

return delegatedAddressBalances
const delegatedAddressBalances: UserDelegateBalance[] = [delegateBalance]

await Promise.all(
resultingDelegations.map(async del => {
if (del.key === del.value) {
return
}
const balance = await getUserTokenBalance(del.key, network, tokenAddress)
const userDAOBalance = await getUserDAODepositBalance(del.key, network, daoContract)
if (balance) {
delegatedAddressBalances.push({
address: del.key,
balance: userDAOBalance ? new BigNumber(userDAOBalance).plus(new BigNumber(balance)).toString() : balance
})
}
})
)

console.log("delegatedAddressBalances: ", delegatedAddressBalances)

return delegatedAddressBalances
}
}
}
4 changes: 2 additions & 2 deletions src/services/contracts/token/hooks/useDelegationVoteWeight.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ import { getTokenDelegationVoteWeight } from "services/bakingBad/delegations"
import { UserDelegateBalance } from "services/bakingBad/delegations/types"
import { useTezos } from "services/beacon/hooks/useTezos"

export const useDelegationVoteWeight = (tokenAddress: string | undefined) => {
export const useDelegationVoteWeight = (tokenAddress: string | undefined, daoContract?: string | undefined) => {
const { network, account } = useTezos()

const { data, ...rest } = useQuery<UserDelegateBalance[] | undefined, Error>(
["delegationVoteWeight", tokenAddress],
async () => {
if (tokenAddress) {
return await getTokenDelegationVoteWeight(tokenAddress, account, network)
return await getTokenDelegationVoteWeight(tokenAddress, account, network, daoContract)
}
},
{
Expand Down
Loading