Skip to content

Commit

Permalink
Does some refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
jagracar committed Oct 8, 2023
1 parent d57aa10 commit e0a2463
Show file tree
Hide file tree
Showing 13 changed files with 145 additions and 168 deletions.
39 changes: 13 additions & 26 deletions src/pages/dao/links.jsx → src/atoms/link/index.jsx
Original file line number Diff line number Diff line change
@@ -1,36 +1,29 @@
import React from 'react'
import { CIDToURL } from '@utils/index'
import { walletPreview } from '@utils/string'
import { TOKENS } from '@constants'
import styles from '@style'

export function TeiaUserLink({ address, alias, shorten, className, children }) {
return (
<a href={`/tz/${address}`} className={className ? className : ''}>
<a href={`/tz/${address}`} className={className ?? ''}>
{children}
{alias ? alias : shorten ? walletPreview(address) : address}
{alias ?? (shorten ? walletPreview(address) : address)}
</a>
)
}

export function DefaultLink({ href, className, children }) {
return (
<a
href={href}
target="_blank"
rel="noreferrer"
className={className ? className : ''}
>
<a href={href} target="_blank" rel="noreferrer" className={className ?? ''}>
{children}
</a>
)
}

export function TzktLink({ link, className, children }) {
return (
<DefaultLink
href={`https://tzkt.io/${link}`}
className={className ? className : ''}
>
<DefaultLink href={`https://tzkt.io/${link}`} className={className}>
{children}
</DefaultLink>
)
Expand All @@ -44,9 +37,9 @@ export function TezosAddressLink({
children,
}) {
return (
<TzktLink link={address} className={className ? className : ''}>
<TzktLink link={address} className={className}>
{children}
{alias ? alias : shorten ? walletPreview(address) : address}
{alias ?? (shorten ? walletPreview(address) : address)}
</TzktLink>
)
}
Expand All @@ -56,32 +49,26 @@ export function TokenLink({ fa2, id, className, children }) {

if (token?.website) {
return (
<DefaultLink
href={token.website + id}
className={className ? className : ''}
>
<DefaultLink href={token.website + id} className={className}>
{children}
</DefaultLink>
)
} else {
return (
<TzktLink
link={`${fa2}/tokens/${id}`}
className={className ? className : ''}
>
<TzktLink link={`${fa2}/tokens/${id}`} className={className}>
{children}
</TzktLink>
)
}
}

export function IpfsLink({ cid, className, children }) {
export function IpfsLink({ cid, type, className, children }) {
return (
<DefaultLink
href={`https://ipfs.io/ipfs/${cid}`}
className={styles.ipfs_link + ' ' + (className ? className : '')}
href={CIDToURL(cid, type ?? 'IPFS')}
className={`${styles.ipfs_link} ${className ?? ''}`}
>
{children ? children : cid}
{children ?? cid}
</DefaultLink>
)
}
3 changes: 3 additions & 0 deletions src/atoms/link/index.module.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.ipfs_link {
word-break: break-word;
}
37 changes: 17 additions & 20 deletions src/context/daoStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,27 +24,27 @@ type OperationReturn = Promise<string | undefined>

interface DaoState {
/** Uploads a file to ipfs */
uploadFileToIpfs: (file: any, displayUploadInformation: boolean) => OperationReturn
uploadFileToIpfs: (file: any, displayUploadInformation?: boolean) => OperationReturn
/** Votes a DAO proposal using the user TEIA tokens */
voteProposal: (proposalId: string, vote: string, maxCheckpoints: number | null, callback: any) => OperationReturn
voteProposal: (proposalId: string, vote: string, maxCheckpoints: number | null, callback?: any) => OperationReturn
/** Votes a DAO proposal as community representaive */
voteProposalAsRepresentative: (proposalId: string, vote: string, callback: any) => OperationReturn
voteProposalAsRepresentative: (proposalId: string, vote: string, callback?: any) => OperationReturn
/** Cancels a DAO proposal */
cancelProposal: (proposalId: string, returnEscrow: boolean, callback: any) => OperationReturn
cancelProposal: (proposalId: string, returnEscrow: boolean, callback?: any) => OperationReturn
/** Evaluates a DAO proposal voting result */
evaluateVotingResult: (proposalId: string, callback: any) => OperationReturn
evaluateVotingResult: (proposalId: string, callback?: any) => OperationReturn
/** Executes a DAO proposal */
executeProposal: (proposalId: string, callback: any) => OperationReturn
executeProposal: (proposalId: string, callback?: any) => OperationReturn
/** Creates a DAO proposal */
createProposal: (title: string, descriptionIpfsPath: string, kind: any, callback: any) => OperationReturn
createProposal: (title: string, descriptionIpfsPath: string, kind: any, callback?: any) => OperationReturn
/** Creates a DAO text proposal */
createTextProposal: (title: string, descriptionIpfsPath: string, callback: any) => OperationReturn
createTextProposal: (title: string, descriptionIpfsPath: string, callback?: any) => OperationReturn
/** Creates a DAO transfer mutez proposal */
createTransferMutezProposal: (title: string, descriptionIpfsPath: string, transfers: any, callback: any) => OperationReturn
createTransferMutezProposal: (title: string, descriptionIpfsPath: string, transfers: any, callback?: any) => OperationReturn
/** Creates a DAO transfer token proposal */
createTransferTokenProposal: (title: string, descriptionIpfsPath: string, tokenAddress: string, tokenId: string, transfers: any, callback: any) => OperationReturn
createTransferTokenProposal: (title: string, descriptionIpfsPath: string, tokenAddress: string, tokenId: string, transfers: any, callback?: any) => OperationReturn
/** Creates a DAO lambda function proposal */
createLambdaFunctionProposal: (title: string, descriptionIpfsPath: string, michelineCode: string, callback: any) => OperationReturn
createLambdaFunctionProposal: (title: string, descriptionIpfsPath: string, michelineCode: string, callback?: any) => OperationReturn
/** Claim DAO tokens */
claimTokens: () => OperationReturn
}
Expand Down Expand Up @@ -73,14 +73,15 @@ export const useDaoStore = create<DaoState>()(
}

const added = await uploadFileToIPFSProxy(file)
const cid = added?.data.cid

if (displayUploadInformation) {
close()
}

console.log(`File IPFS cid: ${added?.data.cid}`)
console.log(`File IPFS cid: ${cid}`)

return added?.data.cid
return cid
},
voteProposal: async (proposalId, vote, maxCheckpoints, callback) => {
const handleOp = useUserStore.getState().handleOp
Expand Down Expand Up @@ -263,9 +264,7 @@ export const useDaoStore = create<DaoState>()(
createTransferMutezProposal: async (title, descriptionIpfsPath, transfers, callback) => {
const show = useModalStore.getState().show

for (const transfer of transfers) {
const destination = transfer.destination

for (const { destination } of transfers) {
if (!(destination && validateAddress(destination) === 3)) {
show(
'Submit DAO proposal',
Expand All @@ -289,9 +288,7 @@ export const useDaoStore = create<DaoState>()(
return
}

for (const transfer of transfers) {
const destination = transfer.destination

for (const { destination } of transfers) {
if (!(destination && validateAddress(destination) === 3)) {
show(
'Submit DAO proposal',
Expand Down Expand Up @@ -381,7 +378,7 @@ export const useDaoStore = create<DaoState>()(
// Calculate the tokens that the user still can claim
const userMerkleData = merkleData[userAddress]
const totalTokensToClaim = parseInt(userMerkleData.tokens) / DAO_TOKEN_DECIMALS
const alreadyClaimedTokens = (await getClaimedDaoTokens(userAddress)) / DAO_TOKEN_DECIMALS
const alreadyClaimedTokens = await getClaimedDaoTokens(userAddress)
const unclaimedTokens = totalTokensToClaim - (alreadyClaimedTokens ? alreadyClaimedTokens : 0)

if (unclaimedTokens === 0) {
Expand Down
30 changes: 12 additions & 18 deletions src/data/api.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {
HEN_CONTRACT_FA2,
DAO_TOKEN_CONTRACT,
DAO_TOKEN_DECIMALS,
CLAIMED_DAO_TOKENS_BIGMAP_ID,
} from '@constants'
import axios from 'axios'
Expand Down Expand Up @@ -327,34 +327,28 @@ export const GetUserMetadata = async (walletAddr: string) => {
}

/**
* Get user DAO token balance
* Get some data from the TzKT API
*/
export async function getDaoTokenBalance(walletAddr: string) {
const parameters = {
'token.contract': DAO_TOKEN_CONTRACT,
'token.tokenId': '0',
account: walletAddr,
select: 'balance',
}
export async function getTzktData(query: string, parameters = {}, debug = true) {
const url = import.meta.env.VITE_TZKT_API + query
const response = await axios
.get(import.meta.env.VITE_TZKT_API + '/v1/tokens/balances', {
params: parameters,
})
.get(url, { params: parameters })
.catch((error) =>
console.log('Error while querying the account token balance:', error)
console.log(`The following TzKT query returned an error: ${url}`, error)
)

return response?.data[0] ? parseInt(response.data[0]) / 1e6 : 0
if (debug) console.log(`Executed TzKT query: ${url}`)

return response?.data
}

/**
* Get user claimed tokens
*/
export async function getClaimedDaoTokens(walletAddr: string) {
const response = await axios.get(
import.meta.env.VITE_TZKT_API +
`/v1/bigmaps/${CLAIMED_DAO_TOKENS_BIGMAP_ID}/keys/${walletAddr}`
const data = await getTzktData(
`/v1/bigmaps/${CLAIMED_DAO_TOKENS_BIGMAP_ID}/keys/${walletAddr}`
)

return response ? parseInt(response.data.value) : 0
return data?.value ? parseInt(data.value) / DAO_TOKEN_DECIMALS : 0
}
61 changes: 27 additions & 34 deletions src/pages/dao/hooks.js → src/data/swr.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,9 @@
import useSWR from 'swr'
import axios from 'axios'
import { DAO_TOKEN_CONTRACT, DAO_TOKEN_DECIMALS } from '@constants'
import { getTzktData } from '@data/api'
import { hexToString } from '@utils/string'

async function getTzktData(query, parameters = {}, debug = true) {
const url = import.meta.env.VITE_TZKT_API + query
const response = await axios
.get(url, { params: parameters })
.catch((error) =>
console.log(`The following TzKT query returned an error: ${url}`, error)
)

if (debug) console.log(`Executed TzKT query: ${url}`)

return response?.data
}

function reorderBigmapData(data, subKey = undefined, decode = false) {
function reorderBigmapData(data, subKey, decode = false) {
const bigmapData = data ? {} : undefined
data?.forEach(
(item) =>
Expand All @@ -37,7 +24,7 @@ export function useBalance(address) {
return [data ? data / 1000000 : 0, mutate]
}

export function useTokenBalance(address) {
export function useDaoTokenBalance(address) {
const parameters = {
'token.contract': DAO_TOKEN_CONTRACT,
'token.tokenId': '0',
Expand All @@ -61,7 +48,7 @@ export function useStorage(contractAddress) {
return [data, mutate]
}

export function useGovernanceParameters(daoStorage) {
export function useDaoGovernanceParameters(daoStorage) {
const parameters = {
limit: 10000,
active: true,
Expand All @@ -77,7 +64,7 @@ export function useGovernanceParameters(daoStorage) {
return [reorderBigmapData(data), mutate]
}

export function useProposals(daoStorage) {
export function useDaoProposals(daoStorage) {
const parameters = {
limit: 10000,
active: true,
Expand All @@ -93,7 +80,7 @@ export function useProposals(daoStorage) {
return [reorderBigmapData(data), mutate]
}

export function useRepresentatives(daoStorage) {
export function useDaoRepresentatives(daoStorage) {
const { data, mutate } = useSWR(
daoStorage?.representatives
? `/v1/contracts/${daoStorage.representatives}/storage`
Expand All @@ -104,7 +91,7 @@ export function useRepresentatives(daoStorage) {
return [data?.representatives, mutate]
}

export function useUserVotes(address, daoStorage) {
export function useDaoUserVotes(address, daoStorage) {
const parameters = {
'key.address': address,
limit: 10000,
Expand All @@ -121,7 +108,7 @@ export function useUserVotes(address, daoStorage) {
return [reorderBigmapData(data, 'nat'), mutate]
}

export function useCommunityVotes(community, daoStorage) {
export function useDaoCommunityVotes(community, daoStorage) {
const parameters = {
'key.string': community,
limit: 10000,
Expand All @@ -138,35 +125,41 @@ export function useCommunityVotes(community, daoStorage) {
return [reorderBigmapData(data, 'nat'), mutate]
}

export function useUsersAliases(userAddress, representatives, proposals) {
const addresses = []
if (userAddress) addresses.push(userAddress)
if (representatives)
Object.keys(representatives).forEach((address) => addresses.push(address))
if (proposals)
Object.values(proposals).forEach((proposal) =>
addresses.push(proposal.issuer)
)
export function useAliases(addresses) {
if (addresses?.length === 1) addresses.push(addresses[0])

const parameters = {
'key.in': addresses.join(','),
'key.in': addresses?.join(','),
limit: 10000,
active: true,
select: 'key,value',
}
const { data, mutate } = useSWR(
representatives && proposals ? [`/v1/bigmaps/3919/keys`, parameters] : null,
addresses?.length > 0 ? [`/v1/bigmaps/3919/keys`, parameters] : null,
getTzktData
)

return [reorderBigmapData(data, undefined, true), mutate]
}

export function useDaoMemberCount() {
export function useDaoUsersAliases(userAddress, representatives, proposals) {
const addresses = []
if (userAddress) addresses.push(userAddress)
if (representatives)
Object.keys(representatives).forEach((address) => addresses.push(address))
if (proposals)
Object.values(proposals).forEach((proposal) =>
addresses.push(proposal.issuer)
)

return useAliases(addresses)
}

export function useDaoMemberCount(minTokens) {
const parameters = {
'token.contract': DAO_TOKEN_CONTRACT,
'token.tokenId': '0',
'balance.gt': 0 * DAO_TOKEN_DECIMALS,
'balance.gt': minTokens * DAO_TOKEN_DECIMALS,
}
const { data, mutate } = useSWR(
['/v1/tokens/balances/count', parameters],
Expand Down
2 changes: 1 addition & 1 deletion src/pages/dao/claim.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import { Page } from '@atoms/layout'
import { Button } from '@atoms/button'
import { Checkbox } from '@atoms/input'
import { Line } from '@atoms/line'
import { DefaultLink } from '@atoms/link'
import { DAOIcon } from '@icons'
import styles from '@style'
import { DefaultLink } from './links'

export const Claim = () => {
const claimTokens = useDaoStore((st) => st.claimTokens)
Expand Down
Loading

0 comments on commit e0a2463

Please sign in to comment.