refactor (away) useWalletStore and others (#1643)

This commit is contained in:
agrippa 2023-05-30 20:26:24 -04:00 committed by GitHub
parent 5339a43ffa
commit 02ba934558
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
301 changed files with 4340 additions and 3833 deletions

View File

@ -1,6 +1,6 @@
{
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint"],
"plugins": ["@typescript-eslint", "unused-imports"],
"extends": [
"eslint:recommended",
"plugin:react/recommended",
@ -25,13 +25,14 @@
"react/react-in-jsx-scope": 0,
"react/display-name": 0,
"react/prop-types": 0,
"unused-imports/no-unused-imports": "error",
"@typescript-eslint/explicit-function-return-type": 0,
"@typescript-eslint/explicit-module-boundary-types": 0,
"@typescript-eslint/explicit-member-accessibility": 0,
"@typescript-eslint/indent": 0,
"@typescript-eslint/member-delimiter-style": 0,
"@typescript-eslint/ban-ts-comment": 0,
"@typescript-eslint/no-non-null-assertion": 0,
"@typescript-eslint/no-non-null-assertion": 0, // days are numbered
"@typescript-eslint/no-explicit-any": 0,
"@typescript-eslint/no-var-requires": 0,
"@typescript-eslint/no-use-before-define": 0,

View File

@ -1,6 +1,4 @@
import React, { useEffect, useState } from 'react'
import useRealm from '@hooks/useRealm'
import useWalletStore from 'stores/useWalletStore'
import { useEffect, useState } from 'react'
import { TransactionInstruction } from '@solana/web3.js'
import { SecondaryButton } from '@components/Button'
import useVotePluginsClientStore from 'stores/useVotePluginsClientStore'
@ -18,7 +16,10 @@ import {
} from '@utils/sendTransactions'
import { ProposalState } from '@solana/spl-governance'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useAddressQuery_CommunityTokenOwner } from '@hooks/queries/addresses/tokenOwner'
import { useAddressQuery_CommunityTokenOwner } from '@hooks/queries/addresses/tokenOwnerRecord'
import { useConnection } from '@solana/wallet-adapter-react'
import { useRealmQuery } from '@hooks/queries/realm'
import { useRealmProposalsQuery } from '@hooks/queries/proposal'
const NFT_SOL_BALANCE = 0.0014616
@ -29,15 +30,14 @@ const ClaimUnreleasedPositions = ({
}) => {
const wallet = useWalletOnePointOh()
const [isLoading, setIsLoading] = useState(false)
const { current: connection } = useWalletStore((s) => s.connection)
const { connection } = useConnection()
const [ownVoteRecords, setOwnVoteRecords] = useState<any[]>([])
const [solToBeClaimed, setSolToBeClaimed] = useState(0)
const { realm } = useWalletStore((s) => s.selectedRealm)
const realm = useRealmQuery().data?.result
const votingPlugin = useVotePluginsClientStore(
(s) => s.state.currentRealmVotingClient
)
const { proposals } = useRealm()
const { data: proposalsArray } = useRealmProposalsQuery()
const { data: tokenOwnerRecord } = useAddressQuery_CommunityTokenOwner()
const isHeliumVsr = votingPlugin.client instanceof HeliumVsrClient
@ -62,12 +62,17 @@ const ClaimUnreleasedPositions = ({
const voteRecords = ownVoteRecords
for (const i of voteRecords) {
const proposal = proposals[i.account.proposal.toBase58()]
const proposal = proposalsArray?.find((x) =>
x.pubkey.equals(i.account.proposal)
)
const [posKey] = positionKey(
i.account.nftMint,
votingPlugin.client!.program.programId
)
if (proposal.account.state === ProposalState.Voting) {
if (
proposal === undefined ||
proposal.account.state === ProposalState.Voting
) {
// ignore this one as it's still in voting
continue
}
@ -126,16 +131,18 @@ const ClaimUnreleasedPositions = ({
},
])) || []
const voteRecordsFiltered = voteRecords.filter(
(x) =>
proposals[x.account.proposal.toBase58()] &&
proposals[
x.account.proposal.toBase58()
].account.governingTokenMint.toBase58() ===
const voteRecordsFiltered = voteRecords.filter((x) => {
const proposal = proposalsArray?.find((p) =>
p.pubkey.equals(x.account.proposal)
)
return (
proposal &&
proposal.account.governingTokenMint.toBase58() ===
realm?.account.communityMint.toBase58() &&
proposals[x.account.proposal.toBase58()].account.state !==
ProposalState.Voting
)
proposal.account.state !== ProposalState.Voting
)
})
setOwnVoteRecords(voteRecordsFiltered)
setSolToBeClaimed(voteRecordsFiltered.length * NFT_SOL_BALANCE)
}

View File

@ -13,7 +13,6 @@ import {
getMintDecimalAmountFromNatural,
getMintNaturalAmountFromDecimalAsBN,
} from '@tools/sdk/units'
import useWalletStore from 'stores/useWalletStore'
import PreviousRouteBtn from '@components/PreviousRouteBtn'
import { TokenDeposit } from '@components/TokenBalance/TokenBalanceCard'
import { GoverningTokenRole } from '@solana/spl-governance'
@ -35,37 +34,44 @@ import { PublicKey } from '@solana/web3.js'
import { notify } from '@utils/notifications'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useSubDaos } from 'HeliumVotePlugin/hooks/useSubDaos'
import { useAddressQuery_CommunityTokenOwner } from '@hooks/queries/addresses/tokenOwner'
import { useAddressQuery_CommunityTokenOwner } from '@hooks/queries/addresses/tokenOwnerRecord'
import { useUserCommunityTokenOwnerRecord } from '@hooks/queries/tokenOwnerRecord'
import { useRealmQuery } from '@hooks/queries/realm'
import { useSelectedDelegatorStore } from 'stores/useSelectedDelegatorStore'
import { useRealmConfigQuery } from '@hooks/queries/realmConfig'
import {
useRealmCommunityMintInfoQuery,
useRealmCouncilMintInfoQuery,
} from '@hooks/queries/mintInfo'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
export const LockTokensAccount: React.FC<{
tokenOwnerRecordPk: string | string[] | undefined
// tokenOwnerRecordPk: string | string[] | undefined // @asktree: this was unused
children: React.ReactNode
}> = (props) => {
const { error, createPosition } = useCreatePosition()
const [isLockModalOpen, setIsLockModalOpen] = useState(false)
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const wallet = useWalletOnePointOh()
const { data: tokenOwnerRecordPk } = useAddressQuery_CommunityTokenOwner()
const { fetchRealm, fetchWalletTokenAccounts } = useWalletStore(
(s) => s.actions
)
const connected = !!wallet?.connected
const ownTokenRecord = useUserCommunityTokenOwnerRecord().data?.result
const realm = useRealmQuery().data?.result
const config = useRealmConfigQuery().data?.result
const mint = useRealmCommunityMintInfoQuery().data?.result
const councilMint = useRealmCouncilMintInfoQuery().data?.result
const { realmTokenAccount, realmInfo } = useRealm()
const {
mint,
realm,
realmTokenAccount,
realmInfo,
tokenRecords,
ownTokenRecord,
councilMint,
config,
} = useRealm()
const tokenOwnerRecordWalletPk = Object.keys(tokenRecords)?.find(
(key) =>
tokenRecords[key]?.pubkey?.toBase58() === tokenOwnerRecordPk?.toBase58()
const selectedCommunityDelegator = useSelectedDelegatorStore(
(s) => s.communityDelegator
)
// if we have a community token delegator selected (this is rare), use that. otherwise use user wallet.
const tokenOwnerRecordWalletPk =
selectedCommunityDelegator !== undefined
? selectedCommunityDelegator
: // I wanted to eliminate `null` as a possible type
wallet?.publicKey ?? undefined
const [
currentClient,
@ -145,7 +151,7 @@ export const LockTokensAccount: React.FC<{
message: 'Unable to fetch positions',
})
}
}, [props.tokenOwnerRecordPk, tokenOwnerRecordWalletPk, vsrClient])
}, [tokenOwnerRecordWalletPk, vsrClient])
const hasTokensInWallet =
realmTokenAccount && realmTokenAccount.account.amount.gt(new BN(0))
@ -212,13 +218,10 @@ export const LockTokensAccount: React.FC<{
amount: amountToLock,
lockupPeriodsInDays: lockupPeriodInDays,
lockupKind: lockupKind.value,
tokenOwnerRecordPk:
tokenRecords[wallet!.publicKey!.toBase58()]?.pubkey || null,
tokenOwnerRecordPk: tokenOwnerRecordPk ?? null, //@asktree: using `null` in 2023 huh.. discusting...
})
if (!error) {
fetchWalletTokenAccounts()
fetchRealm(realmInfo!.programId, realmInfo!.realmId)
await getPositions({
votingClient: currentClient,
realmPk: realm!.pubkey,
@ -340,10 +343,7 @@ export const LockTokensAccount: React.FC<{
key={idx}
position={pos}
subDaos={subDaos}
tokenOwnerRecordPk={
tokenRecords[wallet!.publicKey!.toBase58()]?.pubkey ||
null
}
tokenOwnerRecordPk={tokenOwnerRecordPk ?? null}
isOwner={isSameWallet}
/>
))}

View File

@ -1,6 +1,5 @@
import React, { useEffect, useState } from 'react'
import Modal from '@components/Modal'
import useRealm from '@hooks/useRealm'
import { useForm } from 'react-hook-form'
import Button, { LinkButton, SecondaryButton } from '@components/Button'
import ButtonGroup from '@components/ButtonGroup'
@ -11,6 +10,7 @@ import { getFormattedStringFromDays, yearsToDays } from '@utils/dateTools'
import Tooltip from '@components/Tooltip'
import { QuestionMarkCircleIcon } from '@heroicons/react/solid'
import { notify } from '@utils/notifications'
import { useRealmCommunityMintInfoQuery } from '@hooks/queries/mintInfo'
export const defaultLockupPeriods = [
{
@ -80,7 +80,8 @@ export const LockTokensModal: React.FC<{
onClose,
onSubmit,
}) => {
const { mint } = useRealm()
const mint = useRealmCommunityMintInfoQuery().data?.result
const [isSubmitting, setIsSubmitting] = useState(false)
const [showCustomDuration, setShowCustomDuration] = useState(false)
const [showLockupKindInfo, setShowLockupKindInfo] = useState<boolean>(false)

View File

@ -1,7 +1,5 @@
import React, { useCallback, useState, useMemo } from 'react'
import useRealm from '@hooks/useRealm'
import useVotePluginsClientStore from 'stores/useVotePluginsClientStore'
import useWalletStore from 'stores/useWalletStore'
import { fmtMintAmount, getMintDecimalAmount } from '@tools/sdk/units'
import tokenPriceService from '@utils/services/tokenPrice'
import { abbreviateAddress } from '@utils/formatting'
@ -36,6 +34,11 @@ import { useClaimDelegatedPositionRewards } from '../hooks/useClaimDelegatedPosi
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { PublicKey } from '@solana/web3.js'
import { PromptModal } from './PromptModal'
import { useRealmQuery } from '@hooks/queries/realm'
import { useRealmCommunityMintInfoQuery } from '@hooks/queries/mintInfo'
import queryClient from '@hooks/queries/queryClient'
import { tokenAccountQueryKeys } from '@hooks/queries/tokenAccount'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
interface PositionCardProps {
subDaos?: SubDaoWithMeta[]
@ -55,7 +58,8 @@ export const PositionCard: React.FC<PositionCardProps> = ({
const [isExtendModalOpen, setIsExtendModalOpen] = useState(false)
const [isSplitModalOpen, setIsSplitModalOpen] = useState(false)
const [isDelegateModalOpen, setIsDelegateModalOpen] = useState(false)
const { mint, realm, realmInfo } = useRealm()
const realm = useRealmQuery().data?.result
const mint = useRealmCommunityMintInfoQuery().data?.result
const [isLoading, positions, getPositions] = useHeliumVsrStore((s) => [
s.state.isLoading,
s.state.positions,
@ -153,10 +157,7 @@ export const PositionCard: React.FC<PositionCardProps> = ({
claimDelegatedPositionRewards,
} = useClaimDelegatedPositionRewards()
const { fetchRealm, fetchWalletTokenAccounts } = useWalletStore(
(s) => s.actions
)
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const wallet = useWalletOnePointOh()
const { lockup, hasGenesisMultiplier, votingMint } = position
@ -195,8 +196,9 @@ export const PositionCard: React.FC<PositionCardProps> = ({
)
const refetchState = async () => {
fetchWalletTokenAccounts()
fetchRealm(realmInfo!.programId, realmInfo!.realmId)
queryClient.invalidateQueries({
queryKey: tokenAccountQueryKeys.all(connection.endpoint),
})
await getPositions({
votingClient: currentClient,
realmPk: realm!.pubkey,

View File

@ -6,11 +6,11 @@ import { getMinDurationFmt, getTimeLeftFromNowFmt } from '@utils/dateTools'
import { notify } from '@utils/notifications'
import { PositionWithMeta } from '../sdk/types'
import { getMintMinAmountAsDecimal } from '@tools/sdk/units'
import useRealm from '@hooks/useRealm'
import { precision } from '@utils/formatting'
import Input from '@components/inputs/Input'
import { useSolanaUnixNow } from '@hooks/useSolanaUnixNow'
import { BN } from '@coral-xyz/anchor'
import { useRealmCommunityMintInfoQuery } from '@hooks/queries/mintInfo'
interface TransferTokensModalProps {
isOpen: boolean
@ -28,7 +28,7 @@ export const TransferTokensModal: React.FC<TransferTokensModalProps> = ({
onSubmit,
}) => {
const { unixNow = 0 } = useSolanaUnixNow()
const { mint } = useRealm()
const mint = useRealmCommunityMintInfoQuery().data?.result
const [isSubmitting, setIsSubmitting] = useState(false)
const [amount, setAmount] = useState<number | null>(null)
const [selectedPosPk, setSelectedPosPk] = useState<PublicKey | null>(null)

View File

@ -11,13 +11,21 @@ import useHeliumVsrStore from 'HeliumVotePlugin/hooks/useHeliumVsrStore'
import { MintInfo } from '@solana/spl-token'
import { VotingPowerBox } from './VotingPowerBox'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useUserCommunityTokenOwnerRecord } from '@hooks/queries/tokenOwnerRecord'
import { useRealmQuery } from '@hooks/queries/realm'
import {
useRealmCommunityMintInfoQuery,
useRealmCouncilMintInfoQuery,
} from '@hooks/queries/mintInfo'
export const VotingPowerCard: React.FC<{
inAccountDetails?: boolean
}> = ({ inAccountDetails }) => {
const loading = useHeliumVsrStore((s) => s.state.isLoading)
const [hasGovPower, setHasGovPower] = useState(false)
const { councilMint, ownTokenRecord, mint } = useRealm()
const ownTokenRecord = useUserCommunityTokenOwnerRecord().data?.result
const mint = useRealmCommunityMintInfoQuery().data?.result
const councilMint = useRealmCouncilMintInfoQuery().data?.result
const wallet = useWalletOnePointOh()
const connected = !!wallet?.connected
@ -82,7 +90,8 @@ const TokenDepositLock = ({
setHasGovPower: (hasGovPower: boolean) => void
isSameWallet: boolean
}) => {
const { realm, realmTokenAccount } = useRealm()
const realm = useRealmQuery().data?.result
const { realmTokenAccount } = useRealm()
const wallet = useWalletOnePointOh()
const connected = !!wallet?.connected
const [amountLocked, votingPower] = useHeliumVsrStore((s) => [

View File

@ -19,11 +19,13 @@ import {
import { notify } from '@utils/notifications'
import { withCreateTokenOwnerRecord } from '@solana/spl-governance'
import useRealm from '@hooks/useRealm'
import { useRealmQuery } from '@hooks/queries/realm'
export const useClaimDelegatedPositionRewards = () => {
const { connection, wallet, anchorProvider: provider } = useWalletDeprecated()
const { unixNow } = useSolanaUnixNow()
const { realm, realmInfo } = useRealm()
const realm = useRealmQuery().data?.result
const { realmInfo } = useRealm()
const { error, loading, execute } = useAsyncCallback(
async ({
position,

View File

@ -14,11 +14,13 @@ import {
txBatchesToInstructionSetWithSigners,
} from '@utils/sendTransactions'
import { withCreateTokenOwnerRecord } from '@solana/spl-governance'
import { useRealmQuery } from '@hooks/queries/realm'
export const useClosePosition = () => {
const { unixNow } = useSolanaUnixNow()
const { connection, wallet } = useWalletDeprecated()
const { realm, realmInfo } = useRealm()
const realm = useRealmQuery().data?.result
const { realmInfo } = useRealm()
const [{ client }] = useVotePluginsClientStore((s) => [
s.state.currentRealmVotingClient,
])

View File

@ -20,10 +20,12 @@ import {
SequenceType,
txBatchesToInstructionSetWithSigners,
} from '@utils/sendTransactions'
import { useRealmQuery } from '@hooks/queries/realm'
export const useCreatePosition = () => {
const { connection, wallet } = useWalletDeprecated()
const { realm, realmInfo } = useRealm()
const realm = useRealmQuery().data?.result
const { realmInfo } = useRealm()
const [{ client }, registrarPk] = useVotePluginsClientStore((s) => [
s.state.currentRealmVotingClient,
s.state.voteStakeRegistryRegistrarPk,

View File

@ -12,10 +12,12 @@ import {
import { notify } from '@utils/notifications'
import useRealm from '@hooks/useRealm'
import { withCreateTokenOwnerRecord } from '@solana/spl-governance'
import { useRealmQuery } from '@hooks/queries/realm'
export const useDelegatePosition = () => {
const { connection, wallet, anchorProvider: provider } = useWalletDeprecated()
const { realm, realmInfo } = useRealm()
const realm = useRealmQuery().data?.result
const { realmInfo } = useRealm()
const { error, loading, execute } = useAsyncCallback(
async ({
position,

View File

@ -14,10 +14,12 @@ import {
import { HeliumVsrClient } from 'HeliumVotePlugin/sdk/client'
import useVotePluginsClientStore from 'stores/useVotePluginsClientStore'
import { withCreateTokenOwnerRecord } from '@solana/spl-governance'
import { useRealmQuery } from '@hooks/queries/realm'
export const useExtendPosition = () => {
const { connection, wallet, anchorProvider: provider } = useWalletDeprecated()
const { realm, realmInfo } = useRealm()
const realm = useRealmQuery().data?.result
const { realmInfo } = useRealm()
const [{ client }] = useVotePluginsClientStore((s) => [
s.state.currentRealmVotingClient,
])

View File

@ -16,11 +16,13 @@ import useVotePluginsClientStore from 'stores/useVotePluginsClientStore'
import { HeliumVsrClient } from 'HeliumVotePlugin/sdk/client'
import { useSolanaUnixNow } from '@hooks/useSolanaUnixNow'
import { withCreateTokenOwnerRecord } from '@solana/spl-governance'
import { useRealmQuery } from '@hooks/queries/realm'
export const useFlipPositionLockupKind = () => {
const { unixNow } = useSolanaUnixNow()
const { connection, wallet, anchorProvider: provider } = useWalletDeprecated()
const { realm, realmInfo } = useRealm()
const realm = useRealmQuery().data?.result
const { realmInfo } = useRealm()
const [{ client }] = useVotePluginsClientStore((s) => [
s.state.currentRealmVotingClient,
])

View File

@ -24,10 +24,14 @@ import {
txBatchesToInstructionSetWithSigners,
} from '@utils/sendTransactions'
import { chunks } from '@utils/helpers'
import { useRealmQuery } from '@hooks/queries/realm'
import { useRealmCommunityMintInfoQuery } from '@hooks/queries/mintInfo'
export const useSplitPosition = () => {
const { connection, wallet, anchorProvider: provider } = useWalletDeprecated()
const { mint, realm, realmInfo } = useRealm()
const realm = useRealmQuery().data?.result
const mint = useRealmCommunityMintInfoQuery().data?.result
const { realmInfo } = useRealm()
const [{ client }, registrarPk] = useVotePluginsClientStore((s) => [
s.state.currentRealmVotingClient,
s.state.voteStakeRegistryRegistrarPk,

View File

@ -4,7 +4,6 @@ import { PublicKey, TransactionInstruction } from '@solana/web3.js'
import { useAsyncCallback } from 'react-async-hook'
import { PositionWithMeta } from '../sdk/types'
import { PROGRAM_ID, init, daoKey } from '@helium/helium-sub-daos-sdk'
import useRealm from '@hooks/useRealm'
import useVotePluginsClientStore from 'stores/useVotePluginsClientStore'
import { HeliumVsrClient } from 'HeliumVotePlugin/sdk/client'
import { getMintNaturalAmountFromDecimalAsBN } from '@tools/sdk/units'
@ -14,10 +13,13 @@ import {
sendTransactionsV3,
txBatchesToInstructionSetWithSigners,
} from '@utils/sendTransactions'
import { useRealmQuery } from '@hooks/queries/realm'
import { useRealmCommunityMintInfoQuery } from '@hooks/queries/mintInfo'
export const useTransferPosition = () => {
const { connection, wallet, anchorProvider: provider } = useWalletDeprecated()
const { mint, realm } = useRealm()
const realm = useRealmQuery().data?.result
const mint = useRealmCommunityMintInfoQuery().data?.result
const [{ client }] = useVotePluginsClientStore((s) => [
s.state.currentRealmVotingClient,
s.state.voteStakeRegistryRegistrarPk,

View File

@ -16,10 +16,13 @@ import {
} from '@utils/sendTransactions'
import { withCreateTokenOwnerRecord } from '@solana/spl-governance'
import useRealm from '@hooks/useRealm'
import { useRealmQuery } from '@hooks/queries/realm'
export const useUndelegatePosition = () => {
const { connection, wallet, anchorProvider: provider } = useWalletDeprecated()
const { realm, realmInfo } = useRealm()
const realm = useRealmQuery().data?.result
const { realmInfo } = useRealm()
const { error, loading, execute } = useAsyncCallback(
async ({
position,

View File

@ -1,20 +1,20 @@
import useRealm from '@hooks/useRealm'
import { nftPluginsPks } from '@hooks/useVotingPlugins'
import { NFT_PLUGINS_PKS } from '@constants/plugins'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { ProgramAccount, Proposal, ProposalState } from '@solana/spl-governance'
import { useEffect } from 'react'
import useVotePluginsClientStore from 'stores/useVotePluginsClientStore'
import useWalletStore from 'stores/useWalletStore'
import useNftProposalStore from './NftProposalStore'
import useNftPluginStore from './store/nftPluginStore'
import { useRealmConfigQuery } from '@hooks/queries/realmConfig'
import { useProposalVoteRecordQuery } from '@hooks/queries/voteRecord'
const NftProposalVoteState = ({
proposal,
}: {
proposal?: ProgramAccount<Proposal>
}) => {
const { config, ownTokenRecord } = useRealm()
const { voteRecordsByVoter } = useWalletStore((s) => s.selectedProposal)
const config = useRealmConfigQuery().data?.result
const plugin = useVotePluginsClientStore((s) => s.state.nftClient)
const getCountedNfts = useNftProposalStore((s) => s.getCountedNfts)
const countedNfts = useNftProposalStore((s) => s.countedNftsForProposal)
@ -22,13 +22,12 @@ const NftProposalVoteState = ({
const votingPower = useNftPluginStore((s) => s.state.votingPower)
const isNftPlugin =
config?.account.communityTokenConfig.voterWeightAddin &&
nftPluginsPks.includes(
NFT_PLUGINS_PKS.includes(
config?.account.communityTokenConfig.voterWeightAddin?.toBase58()
)
const ownVoteRecord = ownTokenRecord
? voteRecordsByVoter[ownTokenRecord.account.governingTokenOwner.toBase58()]
: wallet?.publicKey && voteRecordsByVoter[wallet.publicKey.toBase58()]
const ownVoteRecord = useProposalVoteRecordQuery('electoral').data?.result
const showVoteRecords =
countedNfts.length > 0 &&
countedNfts.length < votingPower.toNumber() &&

View File

@ -11,7 +11,7 @@ import EverlendDeposit from './everlend/EverlendDeposit'
import EverlendWithdraw from './everlend/EverlendWithdraw'
import { findAssociatedTokenAccount } from '@everlend/common'
import { PublicKey } from '@solana/web3.js'
import useWalletStore from 'stores/useWalletStore'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
enum Tabs {
DEPOSIT = 'Deposit',
@ -40,7 +40,7 @@ const EverlendModalContent = ({
const [depositedAmount, setDepositedAmount] = useState(0)
const [maxDepositAmount, setMaxDepositAmount] = useState(0)
const tabs = Object.values(Tabs)
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const isSol = governedTokenAccount.isSol
const owner = isSol

View File

@ -6,7 +6,6 @@ import { useRouter } from 'next/router'
import useQueryContext from '@hooks/useQueryContext'
import useRealm from '@hooks/useRealm'
import useVotePluginsClientStore from 'stores/useVotePluginsClientStore'
import useWalletStore from 'stores/useWalletStore'
import tokenPriceService from '@utils/services/tokenPrice'
import {
@ -25,6 +24,13 @@ import { validateInstruction } from '@utils/instructionTools'
import useGovernanceAssets from '@hooks/useGovernanceAssets'
import Loading from '@components/Loading'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useRealmQuery } from '@hooks/queries/realm'
import { useRealmConfigQuery } from '@hooks/queries/realmConfig'
import {
useRealmCommunityMintInfoQuery,
useRealmCouncilMintInfoQuery,
} from '@hooks/queries/mintInfo'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
interface IProps {
proposedInvestment
@ -59,20 +65,17 @@ const EverlendDeposit = ({
const [isDepositing, setIsDepositing] = useState(false)
const router = useRouter()
const { fmtUrlWithCluster } = useQueryContext()
const {
realmInfo,
realm,
mint,
councilMint,
ownVoterWeight,
symbol,
config,
} = useRealm()
const realm = useRealmQuery().data?.result
const config = useRealmConfigQuery().data?.result
const { symbol } = router.query
const mint = useRealmCommunityMintInfoQuery().data?.result
const councilMint = useRealmCouncilMintInfoQuery().data?.result
const { realmInfo, ownVoterWeight } = useRealm()
const [voteByCouncil, setVoteByCouncil] = useState(false)
const client = useVotePluginsClientStore(
(s) => s.state.currentRealmVotingClient
)
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const wallet = useWalletOnePointOh()
const { canUseTransferInstruction } = useGovernanceAssets()

View File

@ -12,7 +12,6 @@ import {
import { CreateEverlendProposal } from '../../protocols/everlend/tools'
import { AssetAccount } from '@utils/uiTypes/assets'
import useRealm from '@hooks/useRealm'
import useWalletStore from 'stores/useWalletStore'
import useVotePluginsClientStore from 'stores/useVotePluginsClientStore'
import useQueryContext from '@hooks/useQueryContext'
import { useRouter } from 'next/router'
@ -25,6 +24,13 @@ import useGovernanceAssets from '@hooks/useGovernanceAssets'
import Loading from '@components/Loading'
import { TreasuryStrategy } from '../../types/types'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useRealmQuery } from '@hooks/queries/realm'
import { useRealmConfigQuery } from '@hooks/queries/realmConfig'
import {
useRealmCommunityMintInfoQuery,
useRealmCouncilMintInfoQuery,
} from '@hooks/queries/mintInfo'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
interface IProps {
proposedInvestment: TreasuryStrategy & {
@ -52,25 +58,21 @@ const EverlendWithdraw = ({
description: '',
})
const [formErrors, setFormErrors] = useState({})
const {
realmInfo,
realm,
mint,
councilMint,
ownVoterWeight,
symbol,
config,
} = useRealm()
const realm = useRealmQuery().data?.result
const config = useRealmConfigQuery().data?.result
const mint = useRealmCommunityMintInfoQuery().data?.result
const councilMint = useRealmCouncilMintInfoQuery().data?.result
const { realmInfo, ownVoterWeight } = useRealm()
const { canUseTransferInstruction } = useGovernanceAssets()
const [voteByCouncil, setVoteByCouncil] = useState(false)
const client = useVotePluginsClientStore(
(s) => s.state.currentRealmVotingClient
)
const { fmtUrlWithCluster } = useQueryContext()
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const wallet = useWalletOnePointOh()
const router = useRouter()
const { symbol } = router.query
const tokenSymbol = tokenPriceService.getTokenInfo(
governedTokenAccount.extensions.mint!.publicKey.toBase58()

View File

@ -26,7 +26,6 @@ import { useRouter } from 'next/router'
import { pdas } from 'psyfi-euros-test'
import React, { useCallback, useEffect, useState } from 'react'
import useVotePluginsClientStore from 'stores/useVotePluginsClientStore'
import useWalletStore from 'stores/useWalletStore'
import {
Action,
CreatePsyFiStrategy,
@ -38,6 +37,13 @@ import { PsyFiStrategy } from 'Strategies/types/types'
import { usePsyFiProgram } from './hooks/usePsyFiProgram'
import { notify } from '@utils/notifications'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useRealmQuery } from '@hooks/queries/realm'
import { useRealmConfigQuery } from '@hooks/queries/realmConfig'
import {
useRealmCommunityMintInfoQuery,
useRealmCouncilMintInfoQuery,
} from '@hooks/queries/mintInfo'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
const SOL_BUFFER = 0.02
@ -54,15 +60,12 @@ export const Deposit: React.FC<{
}) => {
const router = useRouter()
const { fmtUrlWithCluster } = useQueryContext()
const {
realmInfo,
realm,
ownVoterWeight,
mint,
councilMint,
config,
symbol,
} = useRealm()
const realm = useRealmQuery().data?.result
const config = useRealmConfigQuery().data?.result
const { symbol } = router.query
const mint = useRealmCommunityMintInfoQuery().data?.result
const councilMint = useRealmCouncilMintInfoQuery().data?.result
const { realmInfo, ownVoterWeight } = useRealm()
const {
canUseTransferInstruction,
governedTokenAccountsWithoutNfts,
@ -70,7 +73,7 @@ export const Deposit: React.FC<{
const client = useVotePluginsClientStore(
(s) => s.state.currentRealmVotingClient
)
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const wallet = useWalletOnePointOh()
const [ownedStrategyTokenAccount, setOwnedStrategyTokenAccount] = useState<
AssetAccount | undefined

View File

@ -2,11 +2,11 @@ import { AnchorProvider, Program } from '@coral-xyz/anchor'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { PsyFiEuros, PsyFiIdl } from 'psyfi-euros-test'
import { useMemo } from 'react'
import useWalletStore from 'stores/useWalletStore'
import { MAINNET_PROGRAM_KEYS } from '../programIds'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
export const usePsyFiProgram = () => {
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const wallet = useWalletOnePointOh()
// construct the PsyFi program. This could be pulled into a hook

View File

@ -18,7 +18,6 @@ import tokenPriceService from '@utils/services/tokenPrice'
import BigNumber from 'bignumber.js'
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
import useWalletStore from 'stores/useWalletStore'
import { SolendStrategy } from 'Strategies/types/types'
import AdditionalProposalOptions from '@components/AdditionalProposalOptions'
import { validateInstruction } from '@utils/instructionTools'
@ -34,6 +33,14 @@ import {
import useVotePluginsClientStore from 'stores/useVotePluginsClientStore'
import { PublicKey } from '@solana/web3.js'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useRealmQuery } from '@hooks/queries/realm'
import { useRealmConfigQuery } from '@hooks/queries/realmConfig'
import {
useRealmCommunityMintInfoQuery,
useRealmCouncilMintInfoQuery,
} from '@hooks/queries/mintInfo'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
import { useRealmProposalsQuery } from '@hooks/queries/proposal'
const SOL_BUFFER = 0.02
@ -50,16 +57,13 @@ const SolendDeposit = ({
}) => {
const router = useRouter()
const { fmtUrlWithCluster } = useQueryContext()
const {
proposals,
realmInfo,
realm,
ownVoterWeight,
mint,
councilMint,
symbol,
config,
} = useRealm()
const realm = useRealmQuery().data?.result
const { symbol } = router.query
const config = useRealmConfigQuery().data?.result
const mint = useRealmCommunityMintInfoQuery().data?.result
const councilMint = useRealmCouncilMintInfoQuery().data?.result
const { realmInfo, ownVoterWeight } = useRealm()
const proposals = useRealmProposalsQuery().data
const [isDepositing, setIsDepositing] = useState(false)
const [deposits, setDeposits] = useState<{
[reserveAddress: string]: number
@ -68,7 +72,7 @@ const SolendDeposit = ({
const client = useVotePluginsClientStore(
(s) => s.state.currentRealmVotingClient
)
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const wallet = useWalletOnePointOh()
const tokenInfo = tokenPriceService.getTokenInfo(handledMint)
const {
@ -196,6 +200,7 @@ const SolendDeposit = ({
}, [])
const handleDeposit = async () => {
if (proposals === undefined) throw new Error()
const isValid = await validateInstruction({ schema, form, setFormErrors })
if (!isValid) {
return
@ -231,7 +236,7 @@ const SolendDeposit = ({
form.amount as number,
governedTokenAccount.extensions.mint!.account.decimals
),
proposalCount: Object.keys(proposals).length,
proposalCount: proposals.length,
action: 'Deposit',
},
realm!,

View File

@ -17,7 +17,6 @@ import tokenPriceService from '@utils/services/tokenPrice'
import BigNumber from 'bignumber.js'
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
import useWalletStore from 'stores/useWalletStore'
import { SolendStrategy } from 'Strategies/types/types'
import useVotePluginsClientStore from 'stores/useVotePluginsClientStore'
import AdditionalProposalOptions from '@components/AdditionalProposalOptions'
@ -33,6 +32,14 @@ import {
} from 'Strategies/protocols/solend'
import { PublicKey } from '@solana/web3.js'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useRealmQuery } from '@hooks/queries/realm'
import { useRealmConfigQuery } from '@hooks/queries/realmConfig'
import {
useRealmCommunityMintInfoQuery,
useRealmCouncilMintInfoQuery,
} from '@hooks/queries/mintInfo'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
import { useRealmProposalsQuery } from '@hooks/queries/proposal'
const SolendWithdraw = ({
proposedInvestment,
@ -52,16 +59,12 @@ const SolendWithdraw = ({
} = useGovernanceAssets()
const router = useRouter()
const { fmtUrlWithCluster } = useQueryContext()
const {
proposals,
realmInfo,
realm,
ownVoterWeight,
mint,
councilMint,
symbol,
config,
} = useRealm()
const realm = useRealmQuery().data?.result
const { symbol } = router.query
const config = useRealmConfigQuery().data?.result
const mint = useRealmCommunityMintInfoQuery().data?.result
const councilMint = useRealmCouncilMintInfoQuery().data?.result
const { realmInfo, ownVoterWeight } = useRealm()
const [isWithdrawing, setIsWithdrawing] = useState(false)
const [voteByCouncil, setVoteByCouncil] = useState(false)
const [deposits, setDeposits] = useState<{
@ -70,7 +73,8 @@ const SolendWithdraw = ({
const client = useVotePluginsClientStore(
(s) => s.state.currentRealmVotingClient
)
const connection = useWalletStore((s) => s.connection)
const proposals = useRealmProposalsQuery().data
const connection = useLegacyConnectionContext()
const wallet = useWalletOnePointOh()
const tokenInfo = tokenPriceService.getTokenInfo(handledMint)
const mintInfo = governedTokenAccount.extensions?.mint?.account
@ -195,6 +199,7 @@ const SolendWithdraw = ({
}
const handleWithdraw = async () => {
if (proposals === undefined) throw new Error()
const isValid = await validateInstruction({ schema, form, setFormErrors })
if (!isValid) {
return
@ -241,7 +246,7 @@ const SolendWithdraw = ({
amountFmt: (
(form.amount as number) / cTokenExchangeRate(reserveStat[0])
).toFixed(4),
proposalCount: Object.keys(proposals).length,
proposalCount: proposals.length,
action: 'Withdraw',
},
realm!,

View File

@ -3,7 +3,6 @@ import useRealm from '@hooks/useRealm'
import { getProgramVersionForRealm } from '@models/registry/api'
import { RpcContext } from '@solana/spl-governance'
import { fmtMintAmount, getMintDecimalAmount } from '@tools/sdk/units'
import useWalletStore from 'stores/useWalletStore'
import { voteRegistryWithdraw } from 'VoteStakeRegistry/actions/voteRegistryWithdraw'
import {
DepositWithMintAccount,
@ -27,6 +26,11 @@ import {
import { BN } from '@coral-xyz/anchor'
import { VsrClient } from 'VoteStakeRegistry/sdk/client'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useUserCommunityTokenOwnerRecord } from '@hooks/queries/tokenOwnerRecord'
import { useRealmQuery } from '@hooks/queries/realm'
import { useConnection } from '@solana/wallet-adapter-react'
import queryClient from '@hooks/queries/queryClient'
import { tokenAccountQueryKeys } from '@hooks/queries/tokenAccount'
const DepositCard = ({
deposit,
@ -36,18 +40,16 @@ const DepositCard = ({
vsrClient?: VsrClient | undefined
}) => {
const { getOwnedDeposits } = useDepositStore()
const { realm, realmInfo, tokenRecords, ownTokenRecord } = useRealm()
const ownTokenRecord = useUserCommunityTokenOwnerRecord().data?.result
const realm = useRealmQuery().data?.result
const { realmInfo } = useRealm()
const client = useVotePluginsClientStore((s) => s.state.vsrClient)
const actualClient = vsrClient || client
const wallet = useWalletOnePointOh()
const connection = useWalletStore((s) => s.connection.current)
const endpoint = useWalletStore((s) => s.connection.endpoint)
const { connection } = useConnection()
const endpoint = connection.rpcEndpoint
const [isUnlockModalOpen, setIsUnlockModalOpen] = useState(false)
const {
fetchRealm,
fetchWalletTokenAccounts,
fetchOwnVoteRecords,
} = useWalletStore((s) => s.actions)
const handleWithDrawFromDeposit = async (
depositEntry: DepositWithMintAccount
) => {
@ -77,8 +79,7 @@ const DepositCard = ({
amount: depositEntry.available,
communityMintPk: realm!.account.communityMint,
closeDepositAfterOperation: depositEntry.currentlyLocked.isZero(),
tokenOwnerRecordPubKey:
tokenRecords[wallet!.publicKey!.toBase58()]?.pubkey,
tokenOwnerRecordPubKey: ownTokenRecord?.pubkey,
depositIndex: depositEntry.index,
client: actualClient,
splProgramId: realm!.owner!,
@ -91,9 +92,10 @@ const DepositCard = ({
client: actualClient!,
connection,
})
await fetchWalletTokenAccounts()
await fetchOwnVoteRecords()
await fetchRealm(realmInfo!.programId, realmInfo!.realmId)
queryClient.invalidateQueries(
tokenAccountQueryKeys.byOwner(connection.rpcEndpoint, wallet!.publicKey!)
)
queryClient.invalidateQueries(['VoteRecord'])
}
const handleStartUnlock = () => {
setIsUnlockModalOpen(true)

View File

@ -16,7 +16,6 @@ import { PublicKey } from '@solana/web3.js'
import { MintInfo } from '@solana/spl-token'
import { BN } from '@coral-xyz/anchor'
import tokenPriceService from '@utils/services/tokenPrice'
import useWalletStore from 'stores/useWalletStore'
import { getDeposits } from 'VoteStakeRegistry/tools/deposits'
import { DepositWithMintAccount } from 'VoteStakeRegistry/sdk/accounts'
import useDepositStore from 'VoteStakeRegistry/stores/useDepositStore'
@ -36,6 +35,14 @@ import { getMintMetadata } from '@components/instructions/programs/splToken'
import { abbreviateAddress } from '@utils/formatting'
import { TokenDeposit } from '@components/TokenBalance/TokenBalanceCard'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useRealmQuery } from '@hooks/queries/realm'
import { useTokenOwnerRecordByPubkeyQuery } from '@hooks/queries/tokenOwnerRecord'
import { useRealmConfigQuery } from '@hooks/queries/realmConfig'
import {
useRealmCommunityMintInfoQuery,
useRealmCouncilMintInfoQuery,
} from '@hooks/queries/mintInfo'
import { useConnection } from '@solana/wallet-adapter-react'
interface DepositBox {
mintPk: PublicKey
@ -49,14 +56,11 @@ const LockTokensAccount: React.FC<{
tokenOwnerRecordPk: string | string[] | undefined
children: React.ReactNode
}> = ({ tokenOwnerRecordPk, children }) => {
const {
realm,
realmInfo,
mint,
tokenRecords,
councilMint,
config,
} = useRealm()
const realm = useRealmQuery().data?.result
const config = useRealmConfigQuery().data?.result
const mint = useRealmCommunityMintInfoQuery().data?.result
const councilMint = useRealmCouncilMintInfoQuery().data?.result
const { realmInfo } = useRealm()
const [isLockModalOpen, setIsLockModalOpen] = useState(false)
const client = useVotePluginsClientStore((s) => s.state.vsrClient)
const [reducedDeposits, setReducedDeposits] = useState<DepositBox[]>([])
@ -68,13 +72,18 @@ const LockTokensAccount: React.FC<{
)
const [isOwnerOfDeposits, setIsOwnerOfDeposits] = useState(true)
const tokenOwnerRecordWalletPk = Object.keys(tokenRecords)?.find(
(key) => tokenRecords[key]?.pubkey?.toBase58() === tokenOwnerRecordPk
)
const lol = useMemo(() => new PublicKey(tokenOwnerRecordPk as string), [
tokenOwnerRecordPk,
])
const { data: tokenOwnerRecord } = useTokenOwnerRecordByPubkeyQuery(lol)
const tokenOwnerRecordWalletPk =
tokenOwnerRecord?.result?.account.governingTokenOwner
const [isLoading, setIsLoading] = useState(false)
const connection = useWalletStore((s) => s.connection.current)
const { connection } = useConnection()
const wallet = useWalletOnePointOh()
const connected = !!wallet?.connected
const publicKey = wallet?.publicKey ?? null
const connected = wallet?.connected
const mainBoxesClasses = 'bg-bkg-1 col-span-1 p-4 rounded-md'
const isNextSameRecord = (x, next) => {
const nextType = Object.keys(next.lockup.kind)[0]
@ -91,8 +100,8 @@ const LockTokensAccount: React.FC<{
try {
if (
config?.account.communityTokenConfig.voterWeightAddin &&
realm!.pubkey &&
wallet?.publicKey &&
realm?.pubkey &&
publicKey &&
client
) {
const {
@ -100,12 +109,12 @@ const LockTokensAccount: React.FC<{
votingPower,
votingPowerFromDeposits,
} = await getDeposits({
realmPk: realm!.pubkey,
communityMintPk: realm!.account.communityMint,
realmPk: realm.pubkey,
communityMintPk: realm.account.communityMint,
walletPk: tokenOwnerRecordWalletPk
? new PublicKey(tokenOwnerRecordWalletPk)
: wallet.publicKey,
client: client!,
: publicKey,
client: client,
connection: connection,
})
const reducedDeposits = deposits.reduce((curr, next) => {
@ -159,22 +168,21 @@ const LockTokensAccount: React.FC<{
client,
config?.account.communityTokenConfig.voterWeightAddin,
connection,
realm,
publicKey,
realm?.account.communityMint,
realm?.pubkey,
tokenOwnerRecordWalletPk,
wallet,
wallet?.connected,
])
const areLoadedDepositsSameAsOwned =
JSON.stringify(ownDeposits) === JSON.stringify(deposits)
useEffect(() => {
if (!areLoadedDepositsSameAsOwned && isOwnerOfDeposits) {
handleGetDeposits()
}
}, [areLoadedDepositsSameAsOwned, isOwnerOfDeposits, handleGetDeposits])
useEffect(() => {
handleGetDeposits()
}, [isOwnerOfDeposits, client, handleGetDeposits])
}, [
isOwnerOfDeposits,
client,
handleGetDeposits,
ownDeposits, //side effect
])
const depositMint =
!mint?.supply.isZero() ||
@ -185,21 +193,21 @@ const LockTokensAccount: React.FC<{
: undefined
useEffect(() => {
const getTokenOwnerRecord = async () => {
const tokenOwnerRecordAddress = await getTokenOwnerRecordAddress(
realm!.owner,
realm!.pubkey,
depositMint!,
wallet!.publicKey!
)
setIsOwnerOfDeposits(
tokenOwnerRecordAddress.toBase58() === tokenOwnerRecordPk
)
}
if (realm?.owner && realm.pubkey && wallet?.connected && depositMint) {
if (realm?.owner && realm.pubkey && publicKey !== null && depositMint) {
const getTokenOwnerRecord = async () => {
const tokenOwnerRecordAddress = await getTokenOwnerRecordAddress(
realm.owner,
realm.pubkey,
depositMint,
publicKey
)
setIsOwnerOfDeposits(
tokenOwnerRecordAddress.toBase58() === tokenOwnerRecordPk
)
}
getTokenOwnerRecord()
}
}, [tokenOwnerRecordPk, depositMint, realm, wallet])
}, [tokenOwnerRecordPk, depositMint, realm, publicKey])
const hasLockedTokens = useMemo(() => {
return reducedDeposits.find((d) => d.lockUpKind !== 'none')

View File

@ -13,7 +13,6 @@ import { PublicKey } from '@solana/web3.js'
import { MintInfo } from '@solana/spl-token'
import { AnchorProvider, BN, Wallet } from '@coral-xyz/anchor'
import tokenPriceService from '@utils/services/tokenPrice'
import useWalletStore from 'stores/useWalletStore'
import { getDeposits } from 'VoteStakeRegistry/tools/deposits'
import { DepositWithMintAccount } from 'VoteStakeRegistry/sdk/accounts'
import { notify } from '@utils/notifications'
@ -33,6 +32,15 @@ import { abbreviateAddress } from '@utils/formatting'
import { TokenDeposit } from '@components/TokenBalance/TokenBalanceCard'
import { VsrClient } from 'VoteStakeRegistry/sdk/client'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useRealmQuery } from '@hooks/queries/realm'
import { useTokenOwnerRecordByPubkeyQuery } from '@hooks/queries/tokenOwnerRecord'
import { useRealmConfigQuery } from '@hooks/queries/realmConfig'
import {
useRealmCommunityMintInfoQuery,
useRealmCouncilMintInfoQuery,
} from '@hooks/queries/mintInfo'
import { useConnection } from '@solana/wallet-adapter-react'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
interface DepositBox {
mintPk: PublicKey
@ -43,14 +51,11 @@ interface DepositBox {
const unlockedTypes: string[] = []
const LockTokensAccount = ({ tokenOwnerRecordPk }) => {
const {
realm,
realmInfo,
mint,
tokenRecords,
councilMint,
config,
} = useRealm()
const realm = useRealmQuery().data?.result
const config = useRealmConfigQuery().data?.result
const mint = useRealmCommunityMintInfoQuery().data?.result
const councilMint = useRealmCouncilMintInfoQuery().data?.result
const { realmInfo } = useRealm()
const [isLockModalOpen, setIsLockModalOpen] = useState(false)
const [client, setClient] = useState<VsrClient | undefined>(undefined)
const [reducedDeposits, setReducedDeposits] = useState<DepositBox[]>([])
@ -61,12 +66,17 @@ const LockTokensAccount = ({ tokenOwnerRecordPk }) => {
new BN(0)
)
const [isOwnerOfDeposits, setIsOwnerOfDeposits] = useState(true)
const tokenOwnerRecordWalletPk = Object.keys(tokenRecords)?.find(
(key) => tokenRecords[key]?.pubkey?.toBase58() === tokenOwnerRecordPk
)
const lol = useMemo(() => new PublicKey(tokenOwnerRecordPk), [
tokenOwnerRecordPk,
])
const { data: tokenOwnerRecord } = useTokenOwnerRecordByPubkeyQuery(lol)
const tokenOwnerRecordWalletPk =
tokenOwnerRecord?.result?.account.governingTokenOwner
const [isLoading, setIsLoading] = useState(false)
const connection = useWalletStore((s) => s.connection.current)
const connnectionContext = useWalletStore((s) => s.connection)
const { connection } = useConnection()
const connnectionContext = useLegacyConnectionContext()
const wallet = useWalletOnePointOh()
const connected = !!wallet?.connected
const mainBoxesClasses = 'bg-bkg-1 col-span-1 p-4 rounded-md'
@ -232,31 +242,33 @@ const LockTokensAccount = ({ tokenOwnerRecordPk }) => {
: undefined
useEffect(() => {
const getTokenOwnerRecord = async () => {
const tokenOwnerRecordAddress = await getTokenOwnerRecordAddress(
realm!.owner,
realm!.pubkey,
defaultMintOwnerRecordMint!,
wallet!.publicKey!
)
setIsOwnerOfDeposits(
tokenOwnerRecordAddress.toBase58() === tokenOwnerRecordPk
)
}
const walletPubkey = wallet?.publicKey
if (
realm?.owner &&
wallet?.connected &&
walletPubkey &&
walletPubkey !== null &&
realm.pubkey &&
defaultMintOwnerRecordMint
) {
const getTokenOwnerRecord = async () => {
const tokenOwnerRecordAddress = await getTokenOwnerRecordAddress(
realm.owner,
realm.pubkey,
defaultMintOwnerRecordMint,
walletPubkey
)
setIsOwnerOfDeposits(
tokenOwnerRecordAddress.toBase58() === tokenOwnerRecordPk
)
}
getTokenOwnerRecord()
}
}, [
wallet?.connected,
tokenOwnerRecordPk,
defaultMintOwnerRecordMint,
realm,
wallet,
realm?.owner,
realm?.pubkey,
tokenOwnerRecordPk,
wallet?.publicKey,
])
const hasLockedTokens = useMemo(() => {

View File

@ -16,7 +16,6 @@ import {
} from '@tools/sdk/units'
import { precision } from '@utils/formatting'
import { useCallback, useEffect, useMemo, useState } from 'react'
import useWalletStore from 'stores/useWalletStore'
import { voteRegistryLockDeposit } from 'VoteStakeRegistry/actions/voteRegistryLockDeposit'
import { DepositWithMintAccount } from 'VoteStakeRegistry/sdk/accounts'
import {
@ -48,6 +47,12 @@ import InlineNotification from '@components/InlineNotification'
import Tooltip from '@components/Tooltip'
import { notify } from '@utils/notifications'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useRealmQuery } from '@hooks/queries/realm'
import { useAddressQuery_CommunityTokenOwner } from '@hooks/queries/addresses/tokenOwnerRecord'
import { useRealmCommunityMintInfoQuery } from '@hooks/queries/mintInfo'
import { useConnection } from '@solana/wallet-adapter-react'
import { tokenAccountQueryKeys } from '@hooks/queries/tokenAccount'
import queryClient from '@hooks/queries/queryClient'
const YES = 'Yes'
const NO = 'No'
@ -62,18 +67,19 @@ const LockTokensModal = ({
depositToUnlock?: DepositWithMintAccount | null
}) => {
const { getOwnedDeposits } = useDepositStore()
const { mint, realm, realmTokenAccount, realmInfo, tokenRecords } = useRealm()
const realm = useRealmQuery().data?.result
const mint = useRealmCommunityMintInfoQuery().data?.result
const { realmTokenAccount, realmInfo } = useRealm()
const { data: tokenOwnerRecordPk } = useAddressQuery_CommunityTokenOwner()
const client = useVotePluginsClientStore((s) => s.state.vsrClient)
const voteStakeRegistryRegistrar = useVotePluginsClientStore(
(s) => s.state.voteStakeRegistryRegistrar
)
const connection = useWalletStore((s) => s.connection.current)
const endpoint = useWalletStore((s) => s.connection.endpoint)
const { connection } = useConnection()
const endpoint = connection.rpcEndpoint
const wallet = useWalletOnePointOh()
const deposits = useDepositStore((s) => s.state.deposits)
const { fetchRealm, fetchWalletTokenAccounts } = useWalletStore(
(s) => s.actions
)
const fiveYearsSecs = yearsToSecs(5)
const maxLockupSecs =
(realm &&
@ -133,7 +139,7 @@ const LockTokensModal = ({
const depositRecord = deposits.find(
(x) =>
x.mint.publicKey.toBase58() === realm!.account.communityMint.toBase58() &&
x.mint.publicKey.toBase58() === realm?.account.communityMint.toBase58() &&
x.lockup.kind.none
)
const [lockupPeriodDays, setLockupPeriodDays] = useState<number>(0)
@ -225,6 +231,8 @@ const LockTokensModal = ({
}, [amount, currentPrecision, maxAmount, mintMinAmount])
const handleSaveLock = async () => {
if (!tokenOwnerRecordPk) throw new Error()
const rpcContext = new RpcContext(
realm!.owner,
getProgramVersionForRealm(realmInfo!),
@ -266,8 +274,7 @@ const LockTokensModal = ({
sourceDepositIdx: depositRecord!.index,
sourceTokenAccount: realmTokenAccount!.publicKey,
allowClawback: allowClawback,
tokenOwnerRecordPk:
tokenRecords[wallet!.publicKey!.toBase58()]?.pubkey || null,
tokenOwnerRecordPk,
client: client,
})
await getOwnedDeposits({
@ -277,8 +284,9 @@ const LockTokensModal = ({
client: client!,
connection,
})
fetchWalletTokenAccounts()
fetchRealm(realmInfo!.programId, realmInfo!.realmId)
queryClient.invalidateQueries(
tokenAccountQueryKeys.byOwner(connection.rpcEndpoint, wallet!.publicKey!)
)
onClose()
}
@ -286,6 +294,7 @@ const LockTokensModal = ({
if (!depositToUnlock) {
throw 'No deposit to unlock selected'
}
if (!tokenOwnerRecordPk) throw new Error()
const rpcContext = new RpcContext(
realm!.owner,
@ -316,8 +325,7 @@ const LockTokensModal = ({
lockUpPeriodInDays: lockupPeriodDays,
sourceDepositIdx: depositToUnlock!.index,
communityMintPk: realm!.account.communityMint,
tokenOwnerRecordPk:
tokenRecords[wallet!.publicKey!.toBase58()]?.pubkey || null,
tokenOwnerRecordPk,
client: client,
})
await getOwnedDeposits({

View File

@ -1,26 +1,26 @@
import Tooltip from '@components/Tooltip'
import { InformationCircleIcon } from '@heroicons/react/outline'
import useRealm from '@hooks/useRealm'
import { useRealmCommunityMintInfoQuery } from '@hooks/queries/mintInfo'
import { useRealmQuery } from '@hooks/queries/realm'
import { getMintDecimalAmount } from '@tools/sdk/units'
import tokenPriceService from '@utils/services/tokenPrice'
const InfoBox = ({ title, val, tooltip = '', className = '' }) => {
const { mint, realm } = useRealm()
const realm = useRealmQuery().data?.result
const mint = useRealmCommunityMintInfoQuery().data?.result
const formatter = Intl.NumberFormat('en', {
notation: 'compact',
})
const fmtAmount = (val) => {
return mint
? formatter.format(getMintDecimalAmount(mint!, val).toNumber())
? formatter.format(getMintDecimalAmount(mint, val).toNumber())
: '0'
}
const price = realm
? tokenPriceService.getUSDTokenPrice(
realm!.account.communityMint.toBase58()
)
? tokenPriceService.getUSDTokenPrice(realm.account.communityMint.toBase58())
: 0
const totalPrice = mint
? formatter.format(getMintDecimalAmount(mint!, val).toNumber() * price)
? formatter.format(getMintDecimalAmount(mint, val).toNumber() * price)
: ''
return (
<div

View File

@ -7,31 +7,35 @@ import { BN } from '@coral-xyz/anchor'
import { RpcContext } from '@solana/spl-governance'
import { notify } from '@utils/notifications'
import { useState } from 'react'
import useWalletStore from 'stores/useWalletStore'
import { voteRegistryDepositWithoutLockup } from 'VoteStakeRegistry/actions/voteRegistryDepositWithoutLockup'
import useDepositStore from 'VoteStakeRegistry/stores/useDepositStore'
import useVotePluginsClientStore from 'stores/useVotePluginsClientStore'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useRealmQuery } from '@hooks/queries/realm'
import { useUserCommunityTokenOwnerRecord } from '@hooks/queries/tokenOwnerRecord'
import { useConnection } from '@solana/wallet-adapter-react'
import queryClient from '@hooks/queries/queryClient'
import { tokenAccountQueryKeys } from '@hooks/queries/tokenAccount'
const DepositCommunityTokensBtn = ({ className = '', inAccountDetails }) => {
const { getOwnedDeposits } = useDepositStore()
const { realm, realmInfo, realmTokenAccount, tokenRecords } = useRealm()
const realm = useRealmQuery().data?.result
const { realmInfo, realmTokenAccount } = useRealm()
const client = useVotePluginsClientStore((s) => s.state.vsrClient)
const [isLoading, setIsLoading] = useState(false)
const wallet = useWalletOnePointOh()
const connected = !!wallet?.connected
const connection = useWalletStore((s) => s.connection.current)
const endpoint = useWalletStore((s) => s.connection.endpoint)
const { fetchRealm, fetchWalletTokenAccounts } = useWalletStore(
(s) => s.actions
)
const { connection } = useConnection()
const endpoint = connection.rpcEndpoint
const currentTokenOwnerRecord = useUserCommunityTokenOwnerRecord().data
?.result
const depositAllTokens = async function () {
if (!realm) {
throw 'No realm selected'
}
setIsLoading(true)
const currentTokenOwnerRecord = tokenRecords[wallet!.publicKey!.toBase58()]
const tokenOwnerRecordPk =
typeof currentTokenOwnerRecord !== 'undefined'
? currentTokenOwnerRecord.pubkey
@ -63,8 +67,12 @@ const DepositCommunityTokensBtn = ({ className = '', inAccountDetails }) => {
client: client!,
connection,
})
await fetchWalletTokenAccounts()
await fetchRealm(realmInfo!.programId, realmInfo!.realmId)
queryClient.invalidateQueries(
tokenAccountQueryKeys.byOwner(
connection.rpcEndpoint,
wallet!.publicKey!
)
)
} catch (e) {
console.log(e)
notify({ message: `Something went wrong ${e}`, type: 'error' })

View File

@ -19,6 +19,13 @@ import Link from 'next/link'
import DelegateTokenBalanceCard from '@components/TokenBalance/DelegateTokenBalanceCard'
import { TokenDeposit } from '@components/TokenBalance/TokenBalanceCard'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useRealmQuery } from '@hooks/queries/realm'
import { useRouter } from 'next/router'
import { useRealmConfigQuery } from '@hooks/queries/realmConfig'
import {
useRealmCommunityMintInfoQuery,
useRealmCouncilMintInfoQuery,
} from '@hooks/queries/mintInfo'
const LockPluginTokenBalanceCard = ({
proposal,
@ -29,7 +36,11 @@ const LockPluginTokenBalanceCard = ({
}) => {
const [hasGovPower, setHasGovPower] = useState<boolean>(false)
const { fmtUrlWithCluster } = useQueryContext()
const { councilMint, mint, realm, symbol, config } = useRealm()
const realm = useRealmQuery().data?.result
const { symbol } = useRouter().query
const config = useRealmConfigQuery().data?.result
const mint = useRealmCommunityMintInfoQuery().data?.result
const councilMint = useRealmCouncilMintInfoQuery().data?.result
const [tokenOwnerRecordPk, setTokenOwnerRecordPk] = useState('')
const wallet = useWalletOnePointOh()
const connected = !!wallet?.connected
@ -63,19 +74,19 @@ const LockPluginTokenBalanceCard = ({
: undefined
useEffect(() => {
const getTokenOwnerRecord = async () => {
const tokenOwnerRecordAddress = await getTokenOwnerRecordAddress(
realm!.owner,
realm!.pubkey,
defaultMint!,
walletPublicKey!
)
setTokenOwnerRecordPk(tokenOwnerRecordAddress.toBase58())
}
if (realm?.owner && connected && defaultMint) {
if (realm?.owner && walletPublicKey && defaultMint) {
const getTokenOwnerRecord = async () => {
const tokenOwnerRecordAddress = await getTokenOwnerRecordAddress(
realm.owner,
realm.pubkey,
defaultMint,
walletPublicKey
)
setTokenOwnerRecordPk(tokenOwnerRecordAddress.toBase58())
}
getTokenOwnerRecord()
}
}, [defaultMint, realm, connected, walletPublicKey])
}, [defaultMint, realm, walletPublicKey])
const hasLoaded = mint || councilMint
return (
@ -154,7 +165,9 @@ const TokenDepositLock = ({
inAccountDetails?: boolean
setHasGovPower: (hasGovPower: boolean) => void
}) => {
const { realm, realmTokenAccount, councilTokenAccount } = useRealm()
const realm = useRealmQuery().data?.result
const { realmTokenAccount, councilTokenAccount } = useRealm()
const wallet = useWalletOnePointOh()
const connected = !!wallet?.connected
const deposits = useDepositStore((s) => s.state.deposits)
@ -172,7 +185,7 @@ const TokenDepositLock = ({
const depositRecord = deposits.find(
(x) =>
x.mint.publicKey.toBase58() === realm!.account.communityMint.toBase58() &&
x.mint.publicKey.toBase58() === realm?.account.communityMint.toBase58() &&
x.lockup.kind.none
)

View File

@ -11,7 +11,6 @@ import {
import { Transaction, TransactionInstruction } from '@solana/web3.js'
import { chunks } from '@utils/helpers'
import { sendTransaction } from '@utils/send'
import useWalletStore from 'stores/useWalletStore'
import { withVoteRegistryWithdraw } from 'VoteStakeRegistry/sdk/withVoteRegistryWithdraw'
import useDepositStore from 'VoteStakeRegistry/stores/useDepositStore'
import { getProgramVersionForRealm } from '@models/registry/api'
@ -21,32 +20,36 @@ import { useState } from 'react'
import Loading from '@components/Loading'
import { useMaxVoteRecord } from '@hooks/useMaxVoteRecord'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useUserCommunityTokenOwnerRecord } from '@hooks/queries/tokenOwnerRecord'
import { useRealmQuery } from '@hooks/queries/realm'
import { fetchGovernanceByPubkey } from '@hooks/queries/governance'
import { useConnection } from '@solana/wallet-adapter-react'
import { proposalQueryKeys } from '@hooks/queries/proposal'
import queryClient from '@hooks/queries/queryClient'
import asFindable from '@utils/queries/asFindable'
import { tokenAccountQueryKeys } from '@hooks/queries/tokenAccount'
const WithDrawCommunityTokens = () => {
const { getOwnedDeposits } = useDepositStore()
const client = useVotePluginsClientStore((s) => s.state.vsrClient)
const ownTokenRecord = useUserCommunityTokenOwnerRecord().data?.result
const realm = useRealmQuery().data?.result
const {
realm,
realmInfo,
ownTokenRecord,
proposals,
governances,
tokenRecords,
toManyCommunityOutstandingProposalsForUser,
toManyCouncilOutstandingProposalsForUse,
} = useRealm()
const [isLoading, setIsLoading] = useState(false)
const wallet = useWalletOnePointOh()
const connected = !!wallet?.connected
const connection = useWalletStore((s) => s.connection.current)
const { connection } = useConnection()
const deposits = useDepositStore((s) => s.state.deposits)
const { fetchRealm, fetchWalletTokenAccounts } = useWalletStore(
(s) => s.actions
)
const maxVoterWeight = useMaxVoteRecord()?.pubkey || undefined
const depositRecord = deposits.find(
(x) =>
x.mint.publicKey.toBase58() === realm!.account.communityMint.toBase58() &&
x.mint.publicKey.toBase58() === realm?.account.communityMint.toBase58() &&
x.lockup.kind.none
)
const withdrawAllTokens = async function () {
@ -61,17 +64,33 @@ const WithDrawCommunityTokens = () => {
)
for (const voteRecord of Object.values(voteRecords)) {
let proposal = proposals[voteRecord.account.proposal.toBase58()]
const proposalQuery = await queryClient.fetchQuery({
queryKey: proposalQueryKeys.byPubkey(
connection.rpcEndpoint,
voteRecord.account.proposal
),
staleTime: 0,
queryFn: () =>
asFindable(() =>
getProposal(connection, voteRecord.account.proposal)
)(),
})
const proposal = proposalQuery.result
if (!proposal) {
continue
}
if (proposal.account.state === ProposalState.Voting) {
// If the Proposal is in Voting state refetch it to make sure we have the latest state to avoid false positives
proposal = await getProposal(connection, proposal.pubkey)
if (proposal.account.state === ProposalState.Voting) {
const governance =
governances[proposal.account.governance.toBase58()]
const governance = (
await fetchGovernanceByPubkey(
connection,
proposal.account.governance
)
).result
if (!governance) throw new Error('failed to fetch governance')
if (proposal.account.getTimeToVoteEnd(governance.account) > 0) {
setIsLoading(false)
// Note: It's technically possible to withdraw the vote here but I think it would be confusing and people would end up unconsciously withdrawing their votes
@ -125,13 +144,12 @@ const WithDrawCommunityTokens = () => {
realmPk: realm!.pubkey!,
amount: depositRecord!.amountDepositedNative,
communityMintPk: realm!.account.communityMint,
tokenOwnerRecordPubKey: tokenRecords[wallet!.publicKey!.toBase58()]
.pubkey!,
tokenOwnerRecordPubKey: ownTokenRecord!.pubkey,
depositIndex: depositRecord!.index,
connection,
client: client,
splProgramId: realm!.owner,
splProgramVersion: getProgramVersionForRealm(realmInfo!),
splProgramVersion: realmInfo!.programVersion,
})
try {
@ -154,8 +172,6 @@ const WithDrawCommunityTokens = () => {
: `Released tokens (${index}/${ixChunks.length - 2})`,
})
}
await fetchRealm(realmInfo!.programId, realmInfo!.realmId)
await fetchWalletTokenAccounts()
await getOwnedDeposits({
realmPk: realm!.pubkey,
communityMintPk: realm!.account.communityMint,
@ -163,6 +179,12 @@ const WithDrawCommunityTokens = () => {
client: client!,
connection,
})
queryClient.invalidateQueries(
tokenAccountQueryKeys.byOwner(
connection.rpcEndpoint,
wallet!.publicKey!
)
)
} catch (ex) {
console.error(
"Can't withdraw tokens, go to my proposals in account view to check outstanding proposals",

View File

@ -5,9 +5,7 @@ import React, {
useMemo,
useState,
} from 'react'
import useRealm from '@hooks/useRealm'
import { TransactionInstruction } from '@solana/web3.js'
import useWalletStore from 'stores/useWalletStore'
import { tryGetMint } from '@utils/tokens'
import {
ClawbackForm,
@ -38,6 +36,8 @@ import { getClawbackInstruction } from 'VoteStakeRegistry/actions/getClawbackIns
import { abbreviateAddress } from '@utils/formatting'
import useVotePluginsClientStore from 'stores/useVotePluginsClientStore'
import { AssetAccount } from '@utils/uiTypes/assets'
import { useRealmQuery } from '@hooks/queries/realm'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
const Clawback = ({
index,
@ -47,8 +47,9 @@ const Clawback = ({
governance: ProgramAccount<Governance> | null
}) => {
const client = useVotePluginsClientStore((s) => s.state.vsrClient)
const connection = useWalletStore((s) => s.connection)
const { realm } = useRealm()
const connection = useLegacyConnectionContext()
const realm = useRealmQuery().data?.result
const {
governedTokenAccountsWithoutNfts,
governancesArray,
@ -131,7 +132,7 @@ const Clawback = ({
useEffect(() => {
setGovernedAccount(
governancesArray.find(
governancesArray?.find(
(x) => x.pubkey.toBase58() === realm?.account.authority?.toBase58()
)
)

View File

@ -16,7 +16,6 @@ import {
import { PublicKey, TransactionInstruction } from '@solana/web3.js'
import { precision } from '@utils/formatting'
import { tryParseKey } from '@tools/validators/pubkey'
import useWalletStore from 'stores/useWalletStore'
import { TokenProgramAccount, tryGetTokenAccount } from '@utils/tokens'
import { GrantForm, UiInstruction } from '@utils/uiTypes/proposalCreationTypes'
import { getAccountName } from '@components/instructions/tools'
@ -25,6 +24,8 @@ import { getTokenTransferSchema } from '@utils/validations'
import useGovernanceAssets from '@hooks/useGovernanceAssets'
import {
Governance,
getTokenOwnerRecord,
getTokenOwnerRecordAddress,
serializeInstructionToBase64,
withCreateTokenOwnerRecord,
} from '@solana/spl-governance'
@ -44,6 +45,11 @@ import useVotePluginsClientStore from 'stores/useVotePluginsClientStore'
import dayjs from 'dayjs'
import { AssetAccount } from '@utils/uiTypes/assets'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useRealmQuery } from '@hooks/queries/realm'
import queryClient from '@hooks/queries/queryClient'
import asFindable from '@utils/queries/asFindable'
import { tokenOwnerRecordQueryKeys } from '@hooks/queries/tokenOwnerRecord'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
const Grant = ({
index,
@ -54,9 +60,11 @@ const Grant = ({
}) => {
const client = useVotePluginsClientStore((s) => s.state.vsrClient)
const dateNow = dayjs().unix()
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const wallet = useWalletOnePointOh()
const { realm, tokenRecords, realmInfo } = useRealm()
const realm = useRealmQuery().data?.result
const { realmInfo } = useRealm()
const { governedTokenAccountsWithoutNfts } = useGovernanceAssets()
const shouldBeGoverned = !!(index !== 0 && governance)
const [startDate, setStartDate] = useState(dayjs().format('DD-MM-YYYY'))
@ -134,6 +142,8 @@ const Grant = ({
})
}
const getInstruction = useCallback(async () => {
if (!realm) throw new Error()
const isValid = await validateInstruction({ schema, form, setFormErrors })
let serializedInstruction = ''
const prerequisiteInstructions: TransactionInstruction[] = []
@ -150,7 +160,26 @@ const Grant = ({
form.amount!,
form.governedTokenAccount.extensions.mint.account.decimals
)
const currentTokenOwnerRecord = tokenRecords[form.destinationAccount]
//const currentTokenOwnerRecord = tokenRecords[form.destinationAccount]
const destinationTokenOwnerRecordPk = await getTokenOwnerRecordAddress(
realm.owner,
realm.pubkey,
realm.account.communityMint,
destinationAccount
)
const currentTokenOwnerRecord = queryClient.fetchQuery({
queryKey: tokenOwnerRecordQueryKeys.byPubkey(
connection.cluster,
destinationTokenOwnerRecordPk
),
queryFn: () =>
asFindable(getTokenOwnerRecord)(
connection.current,
destinationTokenOwnerRecordPk
),
})
if (!currentTokenOwnerRecord) {
await withCreateTokenOwnerRecord(
prerequisiteInstructions,
@ -190,11 +219,11 @@ const Grant = ({
return obj
}, [
client,
connection,
form,
realm,
realmInfo?.programVersion,
schema,
tokenRecords,
wallet,
])

View File

@ -407,18 +407,18 @@ export const getLockTokensVotingPowerPerWallet = async (
mintsUsedInRealm: TokenProgramAccount<MintInfo>[]
) => {
const { registrar } = await getRegistrarPDA(
realm!.pubkey,
realm!.account.communityMint,
client!.program.programId
realm.pubkey,
realm.account.communityMint,
client.program.programId
)
const existingRegistrar = await tryGetRegistrar(registrar, client!)
const existingRegistrar = await tryGetRegistrar(registrar, client)
const latestBlockhash = await connection.current.getLatestBlockhash()
const votingPowers = await getVotingPowersForWallets({
client: client!,
client: client,
registrarPk: registrar,
existingRegistrar: existingRegistrar!,
walletPks: walletsPks,
communityMint: realm!.account.communityMint,
communityMint: realm.account.communityMint,
connection: connection.current,
mintsUsedInRealm,
latestBlockhash,

View File

@ -7,7 +7,7 @@ export const sbRefreshWeight = async (
wallet
) => {
/*const voterWeightInstructions = useSwitchboardPluginStore((s) => s.state.instructions);
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const wallet = useWalletOnePointOh()*/
const transaction = new Transaction().add(voterWeightInstructions)

View File

@ -2,13 +2,13 @@ import React from 'react'
import useRealm from 'hooks/useRealm'
const AboutRealm = () => {
const { realmInfo, realmDisplayName, symbol } = useRealm()
const { realmInfo, symbol } = useRealm()
return (
<div className="pb-4 space-y-3">
<div>
<p className="text-xs text-fgd-3">Name</p>
<p className="text-fgd-1">{realmDisplayName || symbol}</p>
<p className="text-fgd-1">{realmInfo?.displayName || symbol}</p>
</div>
{realmInfo?.isCertified ? (
<div>

View File

@ -1,16 +1,16 @@
import { ThemeProvider } from 'next-themes'
import { WalletIdentityProvider } from '@cardinal/namespaces-components'
import dynamic from 'next/dynamic'
import React, { useEffect } from 'react'
import React, { useEffect, useMemo } from 'react'
import Head from 'next/head'
import Script from 'next/script'
import { QueryClientProvider } from '@tanstack/react-query'
import { useRouter } from 'next/router'
import { GatewayProvider } from '@components/Gateway/GatewayProvider'
import { usePrevious } from '@hooks/usePrevious'
import { useVotingPlugins, vsrPluginsPks } from '@hooks/useVotingPlugins'
import { useVotingPlugins } from '@hooks/useVotingPlugins'
import { VSR_PLUGIN_PKS } from '@constants/plugins'
import ErrorBoundary from '@components/ErrorBoundary'
import handleGovernanceAssetsStore from '@hooks/handleGovernanceAssetsStore'
import useHandleGovernanceAssetsStore from '@hooks/handleGovernanceAssetsStore'
import handleRouterHistory from '@hooks/handleRouterHistory'
import NavBar from '@components/NavBar'
import PageBodyContainer from '@components/PageBodyContainer'
@ -18,18 +18,28 @@ import tokenPriceService from '@utils/services/tokenPrice'
import TransactionLoader from '@components/TransactionLoader'
import useDepositStore from 'VoteStakeRegistry/stores/useDepositStore'
import useGovernanceAssets from '@hooks/useGovernanceAssets'
import useHydrateStore from '@hooks/useHydrateStore'
import useMembers from '@components/Members/useMembers'
import useRealm from '@hooks/useRealm'
import useTreasuryAccountStore from 'stores/useTreasuryAccountStore'
import useVotePluginsClientStore from 'stores/useVotePluginsClientStore'
import useWalletStore from 'stores/useWalletStore'
import NftVotingCountingModal from '@components/NftVotingCountingModal'
import { getResourcePathPart } from '@tools/core/resources'
import queryClient from '@hooks/queries/queryClient'
import useSerumGovStore from 'stores/useSerumGovStore'
import { WalletProvider } from '@hub/providers/Wallet'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useUserCommunityTokenOwnerRecord } from '@hooks/queries/tokenOwnerRecord'
import { useRealmQuery } from '@hooks/queries/realm'
import { useRealmConfigQuery } from '@hooks/queries/realmConfig'
import {
ConnectionProvider,
WalletProvider,
} from '@solana/wallet-adapter-react'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
import { DEVNET_RPC, MAINNET_RPC } from 'constants/endpoints'
import {
SquadsEmbeddedWalletAdapter,
detectEmbeddedInSquadsIframe,
} from '@sqds/iframe-adapter'
import { WALLET_PROVIDERS } from '@utils/wallet-adapters'
const Notifications = dynamic(() => import('../components/Notification'), {
ssr: false,
@ -59,47 +69,65 @@ interface Props {
children: React.ReactNode
}
/** AppContents depends on providers itself, sadly, so this is where providers go. */
export function App(props: Props) {
useHydrateStore()
const router = useRouter()
const { cluster } = router.query
const endpoint = useMemo(
() => (cluster === 'devnet' ? DEVNET_RPC : MAINNET_RPC),
[cluster]
)
const supportedWallets = useMemo(
() =>
detectEmbeddedInSquadsIframe()
? [new SquadsEmbeddedWalletAdapter()]
: WALLET_PROVIDERS.map((provider) => provider.adapter),
[]
)
return (
<ConnectionProvider endpoint={endpoint}>
<WalletProvider wallets={supportedWallets}>
<AppContents {...props} />{' '}
</WalletProvider>
</ConnectionProvider>
)
}
export function AppContents(props: Props) {
handleRouterHistory()
useVotingPlugins()
handleGovernanceAssetsStore()
useHandleGovernanceAssetsStore()
useMembers()
useEffect(() => {
tokenPriceService.fetchSolanaTokenList()
}, [])
const { governedTokenAccounts } = useGovernanceAssets()
const possibleNftsAccounts = governedTokenAccounts.filter(
(x) => x.isSol || x.isNft
const possibleNftsAccounts = useMemo(
() => governedTokenAccounts.filter((x) => x.isSol || x.isNft),
[governedTokenAccounts]
)
const { getNfts } = useTreasuryAccountStore()
const { getOwnedDeposits, resetDepositState } = useDepositStore()
const {
realm,
ownTokenRecord,
realmInfo,
symbol,
config,
ownDelegateTokenRecords,
ownDelegateCouncilTokenRecords,
} = useRealm()
const ownTokenRecord = useUserCommunityTokenOwnerRecord().data?.result
const realm = useRealmQuery().data?.result
const config = useRealmConfigQuery().data?.result
const { realmInfo } = useRealm()
const wallet = useWalletOnePointOh()
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const vsrClient = useVotePluginsClientStore((s) => s.state.vsrClient)
const prevStringifyPossibleNftsAccounts = usePrevious(
JSON.stringify(possibleNftsAccounts)
)
const walletId = wallet?.publicKey?.toBase58()
const router = useRouter()
const { cluster } = router.query
const { cluster, symbol } = router.query
const updateSerumGovAccounts = useSerumGovStore(
(s) => s.actions.updateSerumGovAccounts
)
const {
actions,
selectedCommunityDelegate,
selectedCouncilDelegate,
} = useWalletStore((s) => s)
const realmName = realmInfo?.displayName ?? realm?.account?.name
const title = realmName ? `${realmName}` : 'Realms'
@ -117,7 +145,7 @@ export function App(props: Props) {
if (
realm &&
config?.account.communityTokenConfig.voterWeightAddin &&
vsrPluginsPks.includes(
VSR_PLUGIN_PKS.includes(
config.account.communityTokenConfig.voterWeightAddin.toBase58()
) &&
realm.pubkey &&
@ -126,24 +154,24 @@ export function App(props: Props) {
vsrClient
) {
getOwnedDeposits({
realmPk: realm!.pubkey,
communityMintPk: realm!.account.communityMint,
realmPk: realm.pubkey,
communityMintPk: realm.account.communityMint,
walletPk: ownTokenRecord!.account!.governingTokenOwner,
client: vsrClient!,
client: vsrClient,
connection: connection.current,
})
} else if (!wallet?.connected || !ownTokenRecord) {
resetDepositState()
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
}, [
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
realm?.pubkey.toBase58(),
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
ownTokenRecord?.pubkey.toBase58(),
config?.account.communityTokenConfig.voterWeightAddin,
connection,
getOwnedDeposits,
ownTokenRecord,
realm,
resetDepositState,
vsrClient,
wallet?.connected,
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
vsrClient?.program.programId.toBase58(),
])
useEffect(() => {
@ -154,44 +182,17 @@ export function App(props: Props) {
) {
getNfts(possibleNftsAccounts, connection)
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
}, [JSON.stringify(possibleNftsAccounts), realm?.pubkey.toBase58()])
}, [
connection,
getNfts,
possibleNftsAccounts,
prevStringifyPossibleNftsAccounts,
realm?.pubkey,
])
useEffect(() => {
updateSerumGovAccounts(cluster as string | undefined)
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
}, [cluster])
useEffect(() => {
if (
ownDelegateCouncilTokenRecords &&
ownDelegateCouncilTokenRecords.length > 0
) {
actions.selectCouncilDelegate(
ownDelegateCouncilTokenRecords[0]?.account?.governingTokenOwner?.toBase58()
)
} else {
actions.selectCouncilDelegate(undefined)
}
if (ownDelegateTokenRecords && ownDelegateTokenRecords.length > 0) {
actions.selectCommunityDelegate(
ownDelegateTokenRecords[0]?.account?.governingTokenOwner?.toBase58()
)
} else {
actions.selectCommunityDelegate(undefined)
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
}, [
walletId,
ownDelegateTokenRecords?.map((x) => x.pubkey.toBase58()).toString(),
ownDelegateCouncilTokenRecords?.map((x) => x.pubkey.toBase58()).toString(),
])
// whenever we change delegate, get that delegates vote record so we can display it
useEffect(() => {
actions.fetchDelegateVoteRecords()
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
}, [selectedCommunityDelegate, selectedCouncilDelegate])
}, [cluster, updateSerumGovAccounts])
return (
<div className="relative bg-bkg-1 text-fgd-1">
@ -283,21 +284,17 @@ export function App(props: Props) {
</Head>
<GoogleTag />
<ErrorBoundary>
<QueryClientProvider client={queryClient}>
<ThemeProvider defaultTheme="Dark">
<WalletIdentityProvider appName={'Realms'}>
<WalletProvider>
<GatewayProvider>
<NavBar />
<Notifications />
<TransactionLoader></TransactionLoader>
<NftVotingCountingModal />
<PageBodyContainer>{props.children}</PageBodyContainer>
</GatewayProvider>
</WalletProvider>
</WalletIdentityProvider>
</ThemeProvider>
</QueryClientProvider>
<ThemeProvider defaultTheme="Dark">
<WalletIdentityProvider appName={'Realms'}>
<GatewayProvider>
<NavBar />
<Notifications />
<TransactionLoader></TransactionLoader>
<NftVotingCountingModal />
<PageBodyContainer>{props.children}</PageBodyContainer>
</GatewayProvider>
</WalletIdentityProvider>
</ThemeProvider>
</ErrorBoundary>
</div>
)

View File

@ -5,7 +5,6 @@ import { abbreviateAddress } from '@utils/formatting'
import { PublicKey } from '@solana/web3.js'
import Button, { SecondaryButton } from '@components/Button'
import Tooltip from '@components/Tooltip'
import useWalletStore from 'stores/useWalletStore'
import { getProgramData } from '@tools/sdk/bpfUpgradeableLoader/accounts'
import useGovernanceAssets from '@hooks/useGovernanceAssets'
import Modal from '@components/Modal'
@ -13,6 +12,7 @@ import UpgradeProgram from './UpgradeProgram'
import CloseBuffers from './CloseBuffers'
import { getExplorerUrl } from '@components/explorer/tools'
import TransferUpgradeAuthority from './TransferUpgradeAuthority'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
import { AssetAccount } from '@utils/uiTypes/assets'
const AssetItem = ({
@ -30,7 +30,7 @@ const AssetItem = ({
false
)
const [loadData, setLoadData] = useState(false)
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const name = item ? getProgramName(item.pubkey) : ''
const governedAccount = item
? abbreviateAddress(item.pubkey as PublicKey)

View File

@ -16,13 +16,14 @@ import { AccountType } from '@utils/uiTypes/assets'
import useGovernanceAssetsStore from 'stores/useGovernanceAssetsStore'
import Loading from '@components/Loading'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useRealmQuery } from '@hooks/queries/realm'
const AssetsCompactWrapper = () => {
const router = useRouter()
const { fmtUrlWithCluster } = useQueryContext()
const realm = useRealmQuery().data?.result
const {
symbol,
realm,
ownVoterWeight,
toManyCommunityOutstandingProposalsForUser,
toManyCouncilOutstandingProposalsForUse,

View File

@ -17,6 +17,7 @@ import BigNumber from 'bignumber.js'
import React, { useEffect, useState } from 'react'
import { BaseGovernanceFormFieldsV3 } from './BaseGovernanceForm-data'
import { BaseGovernanceFormV3 } from './BaseGovernanceFormV3'
import { useRealmCommunityMintInfoQuery } from '@hooks/queries/mintInfo'
export interface BaseGovernanceFormFieldsV2 {
_programVersion: 2
@ -38,7 +39,8 @@ const BaseGovernanceFormV2 = ({
setFormErrors: any
form: BaseGovernanceFormFieldsV2
}) => {
const { realmInfo, mint: realmMint } = useRealm()
const realmMint = useRealmCommunityMintInfoQuery().data?.result
const { realmInfo } = useRealm()
const [minTokensPercentage, setMinTokensPercentage] = useState<
number | undefined
>()

View File

@ -2,7 +2,6 @@ import Input from '@components/inputs/Input'
import Select from '@components/inputs/Select'
import AmountSlider from '@components/Slider'
import Switch from '@components/Switch'
import useRealm from '@hooks/useRealm'
import { VoteTipping } from '@solana/spl-governance'
import {
fmtPercentage,
@ -13,6 +12,10 @@ import {
} from '@tools/sdk/units'
import React, { useEffect, useMemo } from 'react'
import { BaseGovernanceFormFieldsV3 } from './BaseGovernanceForm-data'
import {
useRealmCommunityMintInfoQuery,
useRealmCouncilMintInfoQuery,
} from '@hooks/queries/mintInfo'
//TODO validate bricking via disabling both yes vote thresholds
@ -27,7 +30,8 @@ export const BaseGovernanceFormV3 = ({
setFormErrors: any
form: BaseGovernanceFormFieldsV3
}) => {
const { mint: realmMint, councilMint } = useRealm()
const realmMint = useRealmCommunityMintInfoQuery().data?.result
const councilMint = useRealmCouncilMintInfoQuery().data?.result
// @asktree: unclear that this should not just be an effect in the parent, I am just replicating the behavior of previous components
useEffect(() => {

View File

@ -6,7 +6,6 @@ import Input from 'components/inputs/Input'
import Button, { LinkButton } from '@components/Button'
import Textarea from 'components/inputs/Textarea'
import VoteBySwitch from 'pages/dao/[symbol]/proposal/components/VoteBySwitch'
import useWalletStore from 'stores/useWalletStore'
import { getValidatedPublickKey } from 'utils/validations'
import { useEffect, useState } from 'react'
import { UiInstruction } from 'utils/uiTypes/proposalCreationTypes'
@ -26,6 +25,8 @@ import { abbreviateAddress } from '@utils/formatting'
import useGovernanceAssets from '@hooks/useGovernanceAssets'
import { AssetAccount } from '@utils/uiTypes/assets'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useRealmQuery } from '@hooks/queries/realm'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
interface CloseBuffersForm {
governedAccount: AssetAccount | undefined
@ -39,11 +40,12 @@ const CloseBuffers = ({ program }: { program: AssetAccount }) => {
const { handleCreateProposal } = useCreateProposal()
const { governedTokenAccountsWithoutNfts } = useGovernanceAssets()
const router = useRouter()
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const wallet = useWalletOnePointOh()
const { fmtUrlWithCluster } = useQueryContext()
const { symbol } = router.query
const { realmInfo, canChooseWhoVote, realm } = useRealm()
const realm = useRealmQuery().data?.result
const { realmInfo, canChooseWhoVote } = useRealm()
const [isBuffersLoading, setIsBuffersLoading] = useState(false)
const programId: PublicKey | undefined = realmInfo?.programId
const [buffers, setBuffers] = useState<

View File

@ -10,8 +10,7 @@ import { tryParseKey } from 'tools/validators/pubkey'
import { isFormValid } from 'utils/formValidation'
import { notify } from 'utils/notifications'
import { useRouter } from 'next/router'
import React, { useCallback, useEffect, useMemo, useState } from 'react'
import useWalletStore from 'stores/useWalletStore'
import { useCallback, useEffect, useMemo, useState } from 'react'
import * as yup from 'yup'
import { debounce } from '@utils/debounce'
import { createSetUpgradeAuthority } from '@tools/sdk/bpfUpgradeableLoader/createSetUpgradeAuthority'
@ -20,6 +19,9 @@ import { sendTransaction } from '@utils/send'
import useGovernanceAssetsStore from 'stores/useGovernanceAssetsStore'
import GovernedAccountSelect from 'pages/dao/[symbol]/proposal/components/GovernedAccountSelect'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useRealmQuery } from '@hooks/queries/realm'
import { useRealmCommunityMintInfoQuery } from '@hooks/queries/mintInfo'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
import { usePrevious } from '@hooks/usePrevious'
interface NewProgramForm {
programId: string
@ -34,18 +36,16 @@ const defaultFormValues = {
const NewProgramForm = () => {
const router = useRouter()
const { fmtUrlWithCluster } = useQueryContext()
const realm = useRealmQuery().data?.result
const realmMint = useRealmCommunityMintInfoQuery().data?.result
const { symbol } = router.query
const { ownVoterWeight } = useRealm()
const { assetAccounts } = useGovernanceAssetsStore()
const {
realmInfo,
realm,
mint: realmMint,
symbol,
ownVoterWeight,
} = useRealm()
const wallet = useWalletOnePointOh()
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const connected = !!wallet?.connected
const { fetchRealm } = useWalletStore((s) => s.actions)
const [form, setForm] = useState<NewProgramForm>({
...defaultFormValues,
})
@ -95,7 +95,6 @@ const NewProgramForm = () => {
successMessage: 'Authority has been transferred',
})
setIsLoading(false)
fetchRealm(realmInfo!.programId, realmInfo!.realmId)
router.push(fmtUrlWithCluster(`/dao/${symbol}/`))
}
} catch (e) {

View File

@ -20,6 +20,7 @@ import { createSetUpgradeAuthority } from '@tools/sdk/bpfUpgradeableLoader/creat
import { abbreviateAddress } from '@utils/formatting'
import { AssetAccount } from '@utils/uiTypes/assets'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useRealmQuery } from '@hooks/queries/realm'
interface CloseBuffersForm {
governedAccount: AssetAccount | undefined
@ -35,7 +36,8 @@ const TransferUpgradeAuthority = ({ program }: { program: AssetAccount }) => {
const wallet = useWalletOnePointOh()
const { fmtUrlWithCluster } = useQueryContext()
const { symbol } = router.query
const { realmInfo, canChooseWhoVote, realm } = useRealm()
const realm = useRealmQuery().data?.result
const { realmInfo, canChooseWhoVote } = useRealm()
const programId: PublicKey | undefined = realmInfo?.programId
const [form, setForm] = useState<CloseBuffersForm>({

View File

@ -5,7 +5,6 @@ import Input from 'components/inputs/Input'
import Button, { LinkButton } from '@components/Button'
import Textarea from 'components/inputs/Textarea'
import VoteBySwitch from 'pages/dao/[symbol]/proposal/components/VoteBySwitch'
import useWalletStore from 'stores/useWalletStore'
import { validateBuffer } from 'utils/validations'
import { useEffect, useState } from 'react'
import {
@ -16,7 +15,6 @@ import {
getInstructionDataFromBase64,
serializeInstructionToBase64,
} from '@solana/spl-governance'
import { Governance, ProgramAccount } from '@solana/spl-governance'
import { useRouter } from 'next/router'
import { notify } from 'utils/notifications'
import useQueryContext from 'hooks/useQueryContext'
@ -29,6 +27,8 @@ import ProgramUpgradeInfo from 'pages/dao/[symbol]/proposal/components/instructi
import { getProgramName } from '@components/instructions/programs/names'
import useCreateProposal from '@hooks/useCreateProposal'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useRealmQuery } from '@hooks/queries/realm'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
import { AssetAccount } from '@utils/uiTypes/assets'
interface UpgradeProgramCompactForm extends ProgramUpgradeForm {
@ -38,13 +38,13 @@ interface UpgradeProgramCompactForm extends ProgramUpgradeForm {
const UpgradeProgram = ({ program }: { program: AssetAccount }) => {
const router = useRouter()
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const wallet = useWalletOnePointOh()
const { handleCreateProposal } = useCreateProposal()
const { fmtUrlWithCluster } = useQueryContext()
const { fetchRealmGovernance } = useWalletStore((s) => s.actions)
const { symbol } = router.query
const { realmInfo, canChooseWhoVote, realm } = useRealm()
const realm = useRealmQuery().data?.result
const { realmInfo, canChooseWhoVote } = useRealm()
const programId: PublicKey | undefined = realmInfo?.programId
const [form, setForm] = useState<UpgradeProgramCompactForm>({
governedAccount: program,
@ -135,15 +135,10 @@ const UpgradeProgram = ({ program }: { program: AssetAccount }) => {
prerequisiteInstructions: instruction.prerequisiteInstructions || [],
}
try {
// Fetch governance to get up to date proposalCount
const selectedGovernance = (await fetchRealmGovernance(
governance?.pubkey
)) as ProgramAccount<Governance>
proposalAddress = await handleCreateProposal({
title: form.title ? form.title : proposalTitle,
description: form.description ? form.description : '',
governance: selectedGovernance,
governance: governance!,
instructionsData: [instructionData],
voteByCouncil,
isDraft: false,

View File

@ -14,20 +14,18 @@ import {
ChevronDownIcon,
} from '@heroicons/react/solid'
import { abbreviateAddress } from '@utils/formatting'
import { useEffect, useMemo, useState } from 'react'
import useLocalStorageState from '../hooks/useLocalStorageState'
import useWalletStore from '../stores/useWalletStore'
import { getWalletProviderByName } from '../utils/wallet-adapters'
import { useCallback, useEffect, useState } from 'react'
import Switch from './Switch'
import { TwitterIcon } from './icons'
import { notify } from '@utils/notifications'
import { Profile } from '@components/Profile'
import Loading from './Loading'
import { WalletReadyState } from '@solana/wallet-adapter-base'
import { WalletName, WalletReadyState } from '@solana/wallet-adapter-base'
import { useWallet } from '@solana/wallet-adapter-react'
import useInitWallet from '@hooks/useInitWallet'
import { ExternalLinkIcon } from '@heroicons/react/outline'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
import { DEFAULT_PROVIDER } from '../utils/wallet-adapters'
import useViewAsWallet from '@hooks/useViewAsWallet'
const StyledWalletProviderLabel = styled.p`
font-size: 0.65rem;
@ -35,33 +33,48 @@ const StyledWalletProviderLabel = styled.p`
`
const ConnectWalletButton = (props) => {
useInitWallet()
const { pathname, query, replace } = useRouter()
const [isLoading, setIsLoading] = useState(false)
const [currentCluster, setCurrentCluster] = useLocalStorageState(
'cluster',
'mainnet'
)
const { wallets } = useWallet()
const debugAdapter = useViewAsWallet()
const { providerName, connection, set: setWalletStore } = useWalletStore(
(s) => s
)
const {
wallets,
select,
disconnect,
connect,
wallet,
publicKey: realPublicKey,
connected,
} = useWallet()
const connection = useLegacyConnectionContext()
const current = useWalletOnePointOh()
const connected = !!current?.connected
const provider = useMemo(
() => getWalletProviderByName(providerName, wallets),
[providerName, wallets]
)
const publicKey = debugAdapter?.publicKey ?? realPublicKey
useEffect(() => {
if (connection.cluster !== currentCluster) {
setCurrentCluster(connection.cluster)
if (wallet === null) select(DEFAULT_PROVIDER.name as WalletName)
}, [select, wallet])
const handleConnectDisconnect = useCallback(async () => {
setIsLoading(true)
try {
if (connected) {
await disconnect()
} else {
await connect()
}
} catch (e: any) {
if (e.name === 'WalletNotReadyError') {
notify({
type: 'error',
message: 'You must have a wallet installed to connect',
})
}
console.warn('handleConnectDisconnect', e)
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
}, [connection.cluster])
setIsLoading(false)
}, [connect, connected, disconnect])
const currentCluster = query.cluster
function updateClusterParam(cluster) {
const newQuery = {
@ -77,78 +90,17 @@ const ConnectWalletButton = (props) => {
}
function handleToggleDevnet() {
const isDevnet = !(currentCluster === 'devnet')
setCurrentCluster(isDevnet ? 'devnet' : 'mainnet')
updateClusterParam(isDevnet ? 'devnet' : null)
}
const handleConnectDisconnect = async () => {
setIsLoading(true)
try {
if (connected) {
setIsLoading(false)
await current?.disconnect()
} else {
await current?.connect()
}
} catch (e: any) {
if (e.name === 'WalletNotReadyError') {
notify({
type: 'error',
message: 'You must have a wallet installed to connect',
})
}
console.warn('handleConnectDisconnect', e)
}
setIsLoading(false)
updateClusterParam(currentCluster !== 'devnet' ? 'devnet' : null)
}
const { show } = useWalletIdentity()
const { displayName } = useAddressName(
connection.current,
current?.publicKey || undefined
publicKey ?? undefined
)
const walletAddressFormatted = current?.publicKey
? abbreviateAddress(current?.publicKey)
: ''
const displayAddressComponent = useMemo(() => {
return connected && current?.publicKey ? (
<DisplayAddress
connection={connection.current}
address={current.publicKey!}
width="100px"
height="20px"
dark={true}
/>
) : null
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
}, [current?.publicKey?.toBase58()])
const displayAddressImage = useMemo(() => {
return connected && current?.publicKey ? (
<div className="hidden w-12 pr-2 sm:block">
<AddressImage
dark={true}
connection={connection.current}
address={current?.publicKey}
height="40px"
width="40px"
placeholder={
<div className="flex items-center justify-center flex-shrink-0 w-10 h-10 mr-2 rounded-full bg-bkg-4">
<UserCircleIcon className="h-9 text-fgd-3 w-9" />
</div>
}
/>{' '}
</div>
) : (
<div className="hidden pl-2 pr-2 sm:block">
<img src={provider?.adapter.icon} className="w-5 h-5" />
</div>
)
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
}, [provider])
const walletAddressFormatted = publicKey ? abbreviateAddress(publicKey) : ''
return (
<div className="flex">
@ -163,16 +115,46 @@ const ConnectWalletButton = (props) => {
{...props}
>
<div className="relative flex items-center text-sm font-bold text-left text-fgd-1">
{(current as any)?.FAKE_DEBUG_WALLET ? (
{
// TODO bring back debug wallet
}
{debugAdapter ? (
<div className="absolute -left-4 h-full text-red-400 opacity-90 pointer-events-none text-2xl drop-shadow-[0_1.2px_1.2px_rgba(0,0,0,0.8)] -rotate-45">
DEBUG
</div>
) : null}
{displayAddressImage}
{connected && publicKey ? (
<div className="hidden w-12 pr-2 sm:block">
<AddressImage
dark={true}
connection={connection.current}
address={publicKey}
height="40px"
width="40px"
placeholder={
<div className="flex items-center justify-center flex-shrink-0 w-10 h-10 mr-2 rounded-full bg-bkg-4">
<UserCircleIcon className="h-9 text-fgd-3 w-9" />
</div>
}
/>{' '}
</div>
) : (
<div className="hidden pl-2 pr-2 sm:block">
<img src={wallet?.adapter.icon} className="w-5 h-5" />
</div>
)}
<div>
{connected && current?.publicKey ? (
{connected && publicKey ? (
<>
{displayAddressComponent}
{connected && publicKey ? (
<DisplayAddress
connection={connection.current}
address={publicKey!}
width="100px"
height="20px"
dark={true}
/>
) : null}
<StyledWalletProviderLabel className="font-normal text-fgd-3">
{walletAddressFormatted}
</StyledWalletProviderLabel>
@ -181,7 +163,7 @@ const ConnectWalletButton = (props) => {
<>
{isLoading ? <Loading></Loading> : 'Connect'}
<StyledWalletProviderLabel className="font-normal text-fgd-3">
{provider?.adapter?.name}
{wallet?.adapter.name}
</StyledWalletProviderLabel>
</>
)}
@ -213,16 +195,12 @@ const ConnectWalletButton = (props) => {
<Menu.Item key={name}>
<button
className="flex items-center w-full p-2 font-normal default-transition h-9 hover:bg-bkg-3 hover:cursor-pointer hover:rounded focus:outline-none"
onClick={() =>
setWalletStore((s) => {
s.providerName = name
})
}
onClick={() => select(name)}
>
<img src={icon} className="w-4 h-4 mr-2" />
<span className="text-sm">{name}</span>
{provider?.adapter?.name === name ? (
{wallet?.adapter.name === name ? (
<CheckCircleIcon className="w-5 h-5 ml-2 text-green" />
) : null}
</button>
@ -239,7 +217,7 @@ const ConnectWalletButton = (props) => {
/>
</div>
</Menu.Item>
{current && current.publicKey && (
{wallet && publicKey && (
<>
<hr
className={`border border-fgd-3 opacity-50 mt-2 mb-2`}
@ -257,8 +235,8 @@ const ConnectWalletButton = (props) => {
className="flex items-center w-full p-2 font-normal default-transition h-9 hover:bg-bkg-3 hover:cursor-pointer hover:rounded focus:outline-none"
onClick={() =>
show(
// @ts-ignore
current,
//@ts-expect-error cardinal uses the `Wallet` class from uhh saberhq, so, the types dont line up. nice!
wallet?.adapter,
connection.current,
connection.cluster
)

View File

@ -1,5 +1,3 @@
import useRealm from '../hooks/useRealm'
import useWalletStore from '../stores/useWalletStore'
import React, { useState, FunctionComponent } from 'react'
import {
Transaction,
@ -22,19 +20,21 @@ import { tryParseKey } from 'tools/validators/pubkey'
import { XCircleIcon } from '@heroicons/react/outline'
import Tooltip from './Tooltip'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import {
useUserCommunityTokenOwnerRecord,
useUserCouncilTokenOwnerRecord,
} from '@hooks/queries/tokenOwnerRecord'
import { useRealmQuery } from '@hooks/queries/realm'
import { useConnection } from '@solana/wallet-adapter-react'
const DelegateCard = () => {
const {
realm,
tokenRecords,
councilTokenOwnerRecords,
ownTokenRecord,
ownCouncilTokenRecord,
} = useRealm()
const ownTokenRecord = useUserCommunityTokenOwnerRecord().data?.result
const ownCouncilTokenRecord = useUserCouncilTokenOwnerRecord().data?.result
const realm = useRealmQuery().data?.result
const [isLoading, setLoading] = useState<boolean>(false)
const wallet = useWalletOnePointOh()
const connection = useWalletStore((s) => s.connection.current)
const { fetchRealm } = useWalletStore((s) => s.actions)
const { connection } = useConnection()
const [delegateKey, setDelegateKey] = useState('')
const [delegateCouncilToken, setDelegateCouncilToken] = useState(true)
@ -91,7 +91,6 @@ const DelegateCard = () => {
transaction.add(...instructions)
await sendTransaction({ transaction, wallet, connection, signers })
await fetchRealm(realm?.owner, realm?.pubkey)
setLoading(false)
} catch (error) {
console.log('error', error)
@ -133,8 +132,6 @@ const DelegateCard = () => {
transaction.add(...instructions)
await sendTransaction({ transaction, wallet, connection, signers })
await fetchRealm(realm?.owner, realm?.pubkey)
setLoading(false)
} catch (error) {
console.log('error', error)
@ -144,20 +141,12 @@ const DelegateCard = () => {
const parsedDelegateKey = tryParseKey(delegateKey)
const tokenRecord =
tokenRecords && wallet?.publicKey
? tokenRecords[wallet.publicKey.toBase58()]
: undefined
const councilRecord =
councilTokenOwnerRecords && wallet?.publicKey
? councilTokenOwnerRecords[wallet.publicKey.toBase58()]
: undefined
return (
<div className="bg-bkg-2 p-4 md:p-6 rounded-lg">
<h3 className="mb-4">Delegate tokens</h3>
{wallet && wallet.publicKey && (tokenRecord || councilRecord) ? (
{wallet &&
wallet.publicKey &&
(ownTokenRecord || ownCouncilTokenRecord) ? (
<>
<div className="text-sm text-th-fgd-1 flex flex-row items-center justify-between mt-4">
Allow any wallet to vote or create proposals with your deposited
@ -167,16 +156,16 @@ const DelegateCard = () => {
This will not allow the delegated wallet to withdraw or send tokens.
</div>
{councilRecord && (
{ownCouncilTokenRecord && (
<div className="flex justify-between items-center content-center mt-4 w-full">
<div className="mr-2 py-1 text-sm text-fgd-2 w-40 h-8 flex items-center">
Council Delegation
</div>
{councilRecord?.account.governanceDelegate && (
{ownCouncilTokenRecord?.account.governanceDelegate && (
<div className="flex items-center content-center">
<DisplayAddress
connection={connection}
address={councilRecord?.account.governanceDelegate}
address={ownCouncilTokenRecord?.account.governanceDelegate}
height="12px"
width="100px"
dark={true}
@ -191,17 +180,17 @@ const DelegateCard = () => {
)}
</div>
)}
{tokenRecord && (
{ownTokenRecord && (
<div className="flex justify-between items-center content-center mt-4 w-full">
<div className="mr-2 py-1 text-sm text-fgd-2 w-40 h-8 flex items-center">
Community Delegation
</div>
{tokenRecord?.account.governanceDelegate && (
{ownTokenRecord?.account.governanceDelegate && (
<div className="flex items-center content-center">
<DisplayAddress
connection={connection}
address={tokenRecord?.account.governanceDelegate}
address={ownTokenRecord?.account.governanceDelegate}
height="12px"
width="100px"
dark={true}
@ -223,26 +212,30 @@ const DelegateCard = () => {
label="Token Type"
icon={<CashIcon className="h-8 text-primary-light w-4 mr-2" />}
>
{councilRecord && (
{ownCouncilTokenRecord && (
<div className="form-check">
<Checkbox
checked={delegateCouncilToken}
label={'Council Token'}
// if user only has 1 type of token, then default it checked and disable unchecking
disabled={tokenRecord && councilRecord ? false : true}
disabled={
ownTokenRecord && ownCouncilTokenRecord ? false : true
}
onChange={() =>
setDelegateCouncilToken(!delegateCouncilToken)
}
/>
</div>
)}
{tokenRecord && (
{ownTokenRecord && (
<div className="form-check">
<Checkbox
checked={delegateCommunityToken}
label={'Community Token'}
// if user only has 1 type of token, then default it checked and disable unchecking
disabled={tokenRecord && councilRecord ? false : true}
disabled={
ownTokenRecord && ownCouncilTokenRecord ? false : true
}
onChange={() =>
setDelegateCommunityToken(!delegateCommunityToken)
}
@ -263,7 +256,7 @@ const DelegateCard = () => {
value={delegateKey}
onChange={(e) => setDelegateKey(e.target.value)}
placeholder="Public key"
disabled={!councilRecord && !tokenRecord}
disabled={!ownCouncilTokenRecord && !ownTokenRecord}
/>
</InputRow>
@ -273,7 +266,7 @@ const DelegateCard = () => {
isLoading={isLoading}
disabled={
!parsedDelegateKey ||
(!councilRecord && !tokenRecord) ||
(!ownCouncilTokenRecord && !ownTokenRecord) ||
(!delegateCouncilToken && !delegateCommunityToken)
}
>

View File

@ -14,8 +14,8 @@ import {
import { SignerWalletAdapter } from '@solana/wallet-adapter-base'
import { useTheme } from 'next-themes'
import { useEffect, useMemo, useState } from 'react'
import useWalletStore from 'stores/useWalletStore'
import { web3 } from '@coral-xyz/anchor'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
const REALMS_PUBLIC_KEY = new web3.PublicKey(
'BUxZD6aECR5B5MopyvvYqJxwSKDBhx2jSSo1U32en6mj'
@ -98,7 +98,7 @@ export default function DialectNotificationsModal(
props: DialectNotificationsModalProps
) {
const { theme } = useTheme()
const wallet = useWalletStore((store) => store.current)
const wallet = useWalletOnePointOh()
const [
dialectSolanaWalletAdapter,

View File

@ -12,12 +12,17 @@ import { Transaction, TransactionInstruction } from '@solana/web3.js'
import { sendTransaction } from '@utils/send'
import { useState, useEffect, useMemo } from 'react'
import useVotePluginsClientStore from 'stores/useVotePluginsClientStore'
import useWalletStore from 'stores/useWalletStore'
import useGatewayPluginStore from '../../GatewayPlugin/store/gatewayPluginStore'
import { GatewayButton } from '@components/Gateway/GatewayButton'
import { getRegistrarPDA, getVoterWeightRecord } from '@utils/plugin/accounts'
import { useRecords } from '@components/Gateway/useRecords'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useRealmQuery } from '@hooks/queries/realm'
import {
useRealmCommunityMintInfoQuery,
useRealmCouncilMintInfoQuery,
} from '@hooks/queries/mintInfo'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
// TODO lots of overlap with NftBalanceCard here - we need to separate the logic for creating the Token Owner Record
// from the rest of this logic
@ -31,10 +36,13 @@ const GatewayCard = () => {
(s) => s.state.gatekeeperNetwork
)
const isLoading = useGatewayPluginStore((s) => s.state.isLoadingGatewayToken)
const connection = useWalletStore((s) => s.connection)
const [, setTokenOwneRecordPk] = useState('')
const { realm, mint, councilMint, realmInfo } = useRealm()
const { fetchRealm } = useWalletStore((s) => s.actions)
const connection = useLegacyConnectionContext()
const [, setTokenOwneRecordPk] = useState('') //@asktree: ?????????????????????????????????????????
const realm = useRealmQuery().data?.result
const mint = useRealmCommunityMintInfoQuery().data?.result
const councilMint = useRealmCouncilMintInfoQuery().data?.result
const { realmInfo } = useRealm()
const records = useRecords()
// show the join button if any of the records required by the chain of plugins are not yet created
@ -107,7 +115,6 @@ const GatewayCard = () => {
sendingMessage: `Registering`,
successMessage: `Registered`,
})
await fetchRealm(realm?.owner, realm?.pubkey)
}
useEffect(() => {

View File

@ -1,9 +1,9 @@
import { FC } from 'react'
import { GatewayProvider as InternalGatewayProvider } from '@civic/solana-gateway-react'
import useWalletStore from '../../stores/useWalletStore'
import useVotePluginsClientStore from '../../stores/useVotePluginsClientStore'
import useGatewayPluginStore from '../../GatewayPlugin/store/gatewayPluginStore'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
/**
* Wrapper for the Civic Gateway Provider react component. This component is responsible for
@ -20,7 +20,7 @@ export const GatewayProvider: FC = ({ children }) => {
const gatekeeperNetwork = useGatewayPluginStore(
(s) => s.state.gatekeeperNetwork
)
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const cluster =
connection.cluster === 'mainnet' ? 'mainnet-beta' : connection.cluster

View File

@ -1,11 +1,12 @@
import useVotePluginsClientStore from '../../stores/useVotePluginsClientStore'
import { PublicKey } from '@solana/web3.js'
import { useCallback, useEffect, useState } from 'react'
import useWalletStore from '../../stores/useWalletStore'
import useRealm from '@hooks/useRealm'
import { getVoterWeightRecord as getPluginVoterWeightRecord } from '@utils/plugin/accounts'
import { Client } from '@utils/uiTypes/VotePlugin'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useUserCommunityTokenOwnerRecord } from '@hooks/queries/tokenOwnerRecord'
import { useRealmQuery } from '@hooks/queries/realm'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
// A data structure that indicates if a record that a plugin relies on (token owner record or voter weight recird)
// exists on chain or not - if not, it will trigger the "Join" button to create it.
@ -27,11 +28,9 @@ export const useRecords = (): AvailableRecordAccounts => {
(s) => s.state.currentRealmVotingClient
)
const wallet = useWalletOnePointOh()
const connection = useWalletStore((s) => s.connection)
const { tokenRecords, realm } = useRealm()
const ownTokenRecord = wallet?.publicKey
? tokenRecords[wallet.publicKey!.toBase58()]
: null
const connection = useLegacyConnectionContext()
const realm = useRealmQuery().data?.result
const ownTokenRecord = useUserCommunityTokenOwnerRecord().data?.result
// TODO replace these with useDispatch
const [tokenOwnerRecord, setTokenOwnerRecord] = useState<AvailableRecord>({

View File

@ -4,15 +4,12 @@ import Input from 'components/inputs/Input'
import Button, { SecondaryButton } from '@components/Button'
import VoteBySwitch from 'pages/dao/[symbol]/proposal/components/VoteBySwitch'
import { abbreviateAddress, precision } from 'utils/formatting'
import useWalletStore from 'stores/useWalletStore'
import { getMintSchema } from 'utils/validations'
import { FC, useMemo, useState } from 'react'
import { MintForm, UiInstruction } from 'utils/uiTypes/proposalCreationTypes'
import useGovernanceAssets from 'hooks/useGovernanceAssets'
import {
getInstructionDataFromBase64,
Governance,
ProgramAccount,
serializeInstructionToBase64,
withDepositGoverningTokens,
} from '@solana/spl-governance'
@ -32,6 +29,9 @@ import { useMintInfoByPubkeyQuery } from '@hooks/queries/mintInfo'
import BigNumber from 'bignumber.js'
import { getMintNaturalAmountFromDecimalAsBN } from '@tools/sdk/units'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useRealmQuery } from '@hooks/queries/realm'
import { DEFAULT_GOVERNANCE_PROGRAM_VERSION } from '@components/instructions/tools'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
interface AddMemberForm extends Omit<MintForm, 'mintAccount'> {
description: string
@ -49,14 +49,14 @@ const AddMemberForm: FC<{ close: () => void; mintAccount: AssetAccount }> = ({
const [formErrors, setFormErrors] = useState({})
const { handleCreateProposal } = useCreateProposal()
const router = useRouter()
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const wallet = useWalletOnePointOh()
const { fmtUrlWithCluster } = useQueryContext()
const { fetchRealmGovernance } = useWalletStore((s) => s.actions)
const { symbol } = router.query
const { realmInfo, canChooseWhoVote, realm } = useRealm()
const realm = useRealmQuery().data?.result
const { realmInfo, canChooseWhoVote } = useRealm()
const { data: mintInfo } = useMintInfoByPubkeyQuery(mintAccount.pubkey)
const programId: PublicKey | undefined = realmInfo?.programId
@ -123,7 +123,7 @@ const AddMemberForm: FC<{ close: () => void; mintAccount: AssetAccount }> = ({
}
const getInstruction = async (): Promise<UiInstruction | false> => {
if (programVersion >= 3) {
if ((programVersion ?? DEFAULT_GOVERNANCE_PROGRAM_VERSION) >= 3) {
const isValid = await validateInstruction({
schema,
form: { ...form, mintAccount },
@ -145,11 +145,10 @@ const AddMemberForm: FC<{ close: () => void; mintAccount: AssetAccount }> = ({
const goofySillyArrayForBuilderPattern = []
const tokenMint = mintAccount.pubkey
// eslint-disable-next-line
const tokenOwnerRecordPk = await withDepositGoverningTokens(
await withDepositGoverningTokens(
goofySillyArrayForBuilderPattern,
programId,
programVersion,
programVersion ?? DEFAULT_GOVERNANCE_PROGRAM_VERSION,
realm.pubkey,
tokenMint,
tokenMint,
@ -228,14 +227,10 @@ const AddMemberForm: FC<{ close: () => void; mintAccount: AssetAccount }> = ({
}
try {
const selectedGovernance = (await fetchRealmGovernance(
governance?.pubkey
)) as ProgramAccount<Governance>
proposalAddress = await handleCreateProposal({
title: form.title ? form.title : proposalTitle,
description: form.description ? form.description : '',
governance: selectedGovernance,
governance,
instructionsData: [instructionData],
voteByCouncil,
isDraft: false,
@ -381,7 +376,7 @@ const AddMemberForm: FC<{ close: () => void; mintAccount: AssetAccount }> = ({
}
const useCouncilMintAccount = () => {
const { realm } = useRealm()
const realm = useRealmQuery().data?.result
const { assetAccounts } = useGovernanceAssets()
const councilMintAccount = useMemo(
() =>

View File

@ -26,8 +26,7 @@ import { fmtMintAmount } from '@tools/sdk/units'
import { notify } from '@utils/notifications'
import tokenPriceService from '@utils/services/tokenPrice'
import { Member } from '@utils/uiTypes/members'
import React, { FC, useEffect, useMemo, useState } from 'react'
import useWalletStore from 'stores/useWalletStore'
import { FC, useCallback, useEffect, useMemo, useState } from 'react'
import { WalletTokenRecordWithProposal } from './types'
import PaginationComponent from '@components/Pagination'
import useMembersStore from 'stores/useMembersStore'
@ -39,12 +38,22 @@ import { abbreviateAddress } from '@utils/formatting'
import useGovernanceForGovernedAddress from '@hooks/useGovernanceForGovernedAddress'
import useProposalCreationButtonTooltip from '@hooks/useProposalCreationButtonTooltip'
import Tooltip from '@components/Tooltip'
import { useRealmQuery } from '@hooks/queries/realm'
import { DEFAULT_GOVERNANCE_PROGRAM_VERSION } from '@components/instructions/tools'
import { useRealmConfigQuery } from '@hooks/queries/realmConfig'
import {
useRealmCommunityMintInfoQuery,
useRealmCouncilMintInfoQuery,
} from '@hooks/queries/mintInfo'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
import { useRealmProposalsQuery } from '@hooks/queries/proposal'
const RevokeMembership: FC<{ member: PublicKey; mint: PublicKey }> = ({
member,
mint,
}) => {
const { symbol, realm } = useRealm()
const realm = useRealmQuery().data?.result
const { symbol } = useRealm()
const router = useRouter()
const { fmtUrlWithCluster } = useQueryContext()
@ -97,10 +106,22 @@ const RevokeMembership: FC<{ member: PublicKey; mint: PublicKey }> = ({
const MemberOverview = ({ member }: { member: Member }) => {
const programVersion = useProgramVersion()
const { realm, config } = useRealm()
const connection = useWalletStore((s) => s.connection)
const selectedRealm = useWalletStore((s) => s.selectedRealm)
const { mint, councilMint, proposals, symbol } = useRealm()
const realm = useRealmQuery().data?.result
const config = useRealmConfigQuery().data?.result
const connection = useLegacyConnectionContext()
const mint = useRealmCommunityMintInfoQuery().data?.result
const councilMint = useRealmCouncilMintInfoQuery().data?.result
const { symbol } = useRouter().query
const { data: proposalsArray } = useRealmProposalsQuery()
const proposalsByProposal = useMemo(
() =>
proposalsArray === undefined
? {}
: Object.fromEntries(
proposalsArray.map((x) => [x.pubkey.toString(), x])
),
[proposalsArray]
)
const { fmtUrlWithCluster } = useQueryContext()
const activeMembers = useMembersStore((s) => s.compact.activeMembers)
const [ownVoteRecords, setOwnVoteRecords] = useState<
@ -127,27 +148,25 @@ const MemberOverview = ({ member }: { member: Member }) => {
communityVotes && communityVotes && !communityVotes.isZero()
? fmtMintAmount(mint, communityVotes)
: '',
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
[walletAddress]
[communityVotes, mint]
)
const councilAmount = useMemo(
() =>
councilVotes && councilVotes && !councilVotes.isZero()
? fmtMintAmount(councilMint, councilVotes)
: '',
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
[walletAddress]
[councilMint, councilVotes]
)
const getVoteRecordsAndChatMsgs = async () => {
const getVoteRecordsAndChatMsgs = useCallback(async () => {
if (!realm) throw new Error()
let voteRecords: { [pubKey: string]: ProgramAccount<VoteRecord> } = {}
let chatMessages: { [pubKey: string]: ProgramAccount<ChatMessage> } = {}
try {
const results = await Promise.all([
getVoteRecordsByVoterMapByProposal(
connection.current,
selectedRealm!.programId!,
realm.owner,
new PublicKey(walletAddress)
),
getGovernanceChatMessagesByVoter(
@ -165,48 +184,49 @@ const MemberOverview = ({ member }: { member: Member }) => {
})
}
return { voteRecords, chat: chatMessages }
}
}, [connection, realm, walletAddress])
useEffect(() => {
//we get voteRecords sorted by proposal date and match it with proposal name and chat msgs leaved by token holder.
const handleSetVoteRecords = async () => {
const { voteRecords, chat } = await getVoteRecordsAndChatMsgs()
const voteRecordsArray: WalletTokenRecordWithProposal[] = Object.keys(
voteRecords
)
.sort((a, b) => {
const prevProposal = proposals[a]
const nextProposal = proposals[b]
return (
prevProposal?.account.getStateTimestamp() -
nextProposal?.account.getStateTimestamp()
)
})
.reverse()
.filter((x) => proposals[x])
.flatMap((x) => {
const currentProposal = proposals[x]
const currentChatsMsgPk = Object.keys(chat).filter(
(c) =>
chat[c]?.account.proposal.toBase58() ===
currentProposal?.pubkey.toBase58()
)
const currentChatMsgs = currentChatsMsgPk.map(
(c) => chat[c].account.body.value
)
return {
proposalPublicKey: x,
proposalName: currentProposal?.account.name,
chatMessages: currentChatMsgs,
...voteRecords[x],
}
})
if (realm) {
//we get voteRecords sorted by proposal date and match it with proposal name and chat msgs leaved by token holder.
const handleSetVoteRecords = async () => {
const { voteRecords, chat } = await getVoteRecordsAndChatMsgs()
const voteRecordsArray: WalletTokenRecordWithProposal[] = Object.keys(
voteRecords
)
.sort((a, b) => {
const prevProposal = proposalsByProposal[a]
const nextProposal = proposalsByProposal[b]
return (
prevProposal?.account.getStateTimestamp() -
nextProposal?.account.getStateTimestamp()
)
})
.reverse()
.filter((x) => proposalsByProposal[x])
.flatMap((x) => {
const currentProposal = proposalsByProposal[x]
const currentChatsMsgPk = Object.keys(chat).filter(
(c) =>
chat[c]?.account.proposal.toBase58() ===
currentProposal?.pubkey.toBase58()
)
const currentChatMsgs = currentChatsMsgPk.map(
(c) => chat[c].account.body.value
)
return {
proposalPublicKey: x,
proposalName: currentProposal?.account.name,
chatMessages: currentChatMsgs,
...voteRecords[x],
}
})
setOwnVoteRecords(voteRecordsArray)
setOwnVoteRecords(voteRecordsArray)
}
handleSetVoteRecords()
}
handleSetVoteRecords()
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
}, [walletAddress])
}, [getVoteRecordsAndChatMsgs, proposalsByProposal, realm, walletAddress])
const memberVotePowerRank = useMemo(() => {
const sortedMembers = activeMembers.sort((a, b) =>
@ -217,35 +237,23 @@ const MemberOverview = ({ member }: { member: Member }) => {
(m) => m.walletAddress === member?.walletAddress
) + 1
)
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
}, [JSON.stringify(activeMembers.length), member.walletAddress])
}, [activeMembers, member?.walletAddress])
const paginateVotes = useCallback(
(page) => {
return ownVoteRecords.slice(page * perPage, (page + 1) * perPage)
},
[ownVoteRecords]
)
useEffect(() => {
setRecentVotes(paginateVotes(0))
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
}, [JSON.stringify(ownVoteRecords)])
}, [paginateVotes])
const perPage = 8
const totalPages = Math.ceil(ownVoteRecords.length / perPage)
const onPageChange = (page) => {
setRecentVotes(paginateVotes(page))
}
const paginateVotes = (page) => {
return ownVoteRecords.slice(page * perPage, (page + 1) * perPage)
}
const Address = useMemo(() => {
return (
<DisplayAddress
connection={connection.current}
address={walletPublicKey}
height="12px"
width="100px"
dark={true}
/>
)
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
}, [walletPublicKey?.toBase58()])
const councilMintKey = realm?.account.config.councilMint
const communityMintKey = realm?.account.communityMint
@ -265,7 +273,15 @@ const MemberOverview = ({ member }: { member: Member }) => {
return (
<>
<div className="flex items-center justify-between mb-2 py-2">
<h2 className="mb-0">{Address}</h2>
<h2 className="mb-0">
<DisplayAddress
connection={connection.current}
address={walletPublicKey}
height="12px"
width="100px"
dark={true}
/>
</h2>
<div className="flex gap-6">
<a
className="default-transition flex items-center text-primary-light hover:text-primary-dark text-sm"
@ -281,7 +297,7 @@ const MemberOverview = ({ member }: { member: Member }) => {
Explorer
<ExternalLinkIcon className="flex-shrink-0 h-4 ml-1 w-4" />
</a>
{programVersion >= 3 &&
{(programVersion ?? DEFAULT_GOVERNANCE_PROGRAM_VERSION) >= 3 &&
realm !== undefined &&
(isRevokableCouncilMember || isRevokableCommunityMember) && (
<RevokeMembership

View File

@ -1,13 +1,17 @@
import { FunctionComponent, useMemo } from 'react'
import useWalletStore from 'stores/useWalletStore'
import { LogoutIcon, UserCircleIcon } from '@heroicons/react/outline'
import useRealm from '@hooks/useRealm'
import tokenPriceService from '@utils/services/tokenPrice'
import { fmtMintAmount } from '@tools/sdk/units'
import { PublicKey } from '@solana/web3.js'
import { AddressImage, DisplayAddress } from '@cardinal/namespaces-components'
import { Member } from '@utils/uiTypes/members'
import { MintInfo } from '@solana/spl-token'
import { useRealmQuery } from '@hooks/queries/realm'
import {
useRealmCommunityMintInfoQuery,
useRealmCouncilMintInfoQuery,
} from '@hooks/queries/mintInfo'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
interface MembersTabsProps {
activeTab: Member
@ -20,7 +24,9 @@ const MembersTabs: FunctionComponent<MembersTabsProps> = ({
onChange,
tabs,
}) => {
const { mint, councilMint, realm } = useRealm()
const realm = useRealmQuery().data?.result
const mint = useRealmCommunityMintInfoQuery().data?.result
const councilMint = useRealmCouncilMintInfoQuery().data?.result
const tokenName = realm
? tokenPriceService.getTokenInfo(realm?.account.communityMint.toBase58())
?.symbol
@ -91,7 +97,7 @@ const MemberItems = ({
councilVotes && !councilVotes.isZero()
? fmtMintAmount(councilMint, councilVotes)
: null
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const renderAddressName = useMemo(() => {
return (

View File

@ -1,4 +1,4 @@
import { useEffect, useMemo } from 'react'
import { useCallback, useEffect, useMemo } from 'react'
import {
AccountInfo,
ASSOCIATED_TOKEN_PROGRAM_ID,
@ -16,19 +16,50 @@ import {
import { capitalize } from '@utils/helpers'
import { TokenRecordsWithWalletAddress } from './types'
import { Member, Delegates } from 'utils/uiTypes/members'
import useRealm from '@hooks/useRealm'
import { usePrevious } from '@hooks/usePrevious'
import useMembersStore from 'stores/useMembersStore'
import useWalletStore from 'stores/useWalletStore'
import { useRealmQuery } from '@hooks/queries/realm'
import { useTokenRecordsByOwnersMap } from '@hooks/queries/tokenOwnerRecord'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
export default function useMembers() {
const { tokenRecords, councilTokenOwnerRecords, realm, config } = useRealm()
const connection = useWalletStore((s) => s.connection)
const previousRealmPubKey = usePrevious(realm?.pubkey.toBase58()) as string
const realm = useRealmQuery().data?.result
const {
communityTORsByOwner: tokenRecords,
councilTORsByOwner: councilTokenOwnerRecords,
} = useTokenRecordsByOwnersMap()
const connection = useLegacyConnectionContext()
const setMembers = useMembersStore((s) => s.setMembers)
const setDelegates = useMembersStore((s) => s.setDelegates)
const fetchCouncilMembersWithTokensOutsideRealm = async () => {
const tokenRecordArray: TokenRecordsWithWalletAddress[] = useMemo(
() =>
tokenRecords
? Object.keys(tokenRecords).flatMap((x) => {
return {
walletAddress: x,
community: { ...tokenRecords[x] },
}
})
: [],
[tokenRecords]
)
const councilRecordArray: TokenRecordsWithWalletAddress[] = useMemo(
() =>
councilTokenOwnerRecords
? Object.keys(councilTokenOwnerRecords).flatMap((x) => {
return {
walletAddress: x,
council: { ...councilTokenOwnerRecords[x] },
}
})
: [],
[councilTokenOwnerRecords]
)
const fetchCouncilMembersWithTokensOutsideRealm = useCallback(async () => {
if (realm?.account.config.councilMint) {
const tokenAccounts = await getTokenAccountsByMint(
connection.current,
@ -47,10 +78,10 @@ export default function useMembers() {
)
}
return []
}
}, [connection, realm?.account.config.councilMint, realm?.pubkey])
// This will need to be rewritten for better performance if some realm hits more then +-5k+ members
const fetchCommunityMembersATAS = async () => {
const fetchCommunityMembersATAS = useCallback(async () => {
if (realm?.account.communityMint) {
const ATAS: PublicKey[] = []
// we filter out people who never voted and has tokens inside realm
@ -63,7 +94,7 @@ export default function useMembers() {
const ata = await Token.getAssociatedTokenAddress(
ASSOCIATED_TOKEN_PROGRAM_ID, // always ASSOCIATED_TOKEN_PROGRAM_ID
TOKEN_PROGRAM_ID, // always TOKEN_PROGRAM_ID
realm!.account.communityMint, // mint
realm.account.communityMint, // mint
new PublicKey(walletAddress), // owner
true
)
@ -84,7 +115,7 @@ export default function useMembers() {
return ownersAtasParsed
}
return []
}
}, [connection, realm, tokenRecordArray])
const matchMembers = (
membersArray,
@ -121,39 +152,11 @@ export default function useMembers() {
return members
}
const tokenRecordArray: TokenRecordsWithWalletAddress[] = useMemo(
() =>
tokenRecords
? Object.keys(tokenRecords).flatMap((x) => {
return {
walletAddress: x,
community: { ...tokenRecords[x] },
}
})
: [],
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
[JSON.stringify(tokenRecords)]
)
const councilRecordArray: TokenRecordsWithWalletAddress[] = useMemo(
() =>
councilTokenOwnerRecords
? Object.keys(councilTokenOwnerRecords).flatMap((x) => {
return {
walletAddress: x,
council: { ...councilTokenOwnerRecords[x] },
}
})
: [],
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
[JSON.stringify(councilTokenOwnerRecords)]
)
// for community we exclude people who never vote
const communityAndCouncilTokenRecords = [
...tokenRecordArray,
...councilRecordArray,
]
const communityAndCouncilTokenRecords = useMemo(
() => [...tokenRecordArray, ...councilRecordArray],
[councilRecordArray, tokenRecordArray]
)
// merge community and council vote records to one big array of members
// sort them by totalVotes sum of community and council votes
const membersWithTokensDeposited = useMemo(
@ -199,16 +202,7 @@ export default function useMembers() {
})
// .sort((a, b) => a.votesCasted - b.votesCasted)
.reverse(),
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
[
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
JSON.stringify(tokenRecordArray),
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
JSON.stringify(councilRecordArray),
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
realm?.pubkey.toBase58(),
]
[communityAndCouncilTokenRecords]
)
// Loop through Members list to get our delegates and their tokens
@ -267,6 +261,8 @@ export default function useMembers() {
// Move to store if will be used more across application
useEffect(() => {
console.log('useMembers is fetching')
const handleSetMembers = async () => {
let members = [...membersWithTokensDeposited]
@ -286,22 +282,14 @@ export default function useMembers() {
const delegateMap = getDelegateWalletMap(members)
setDelegates(delegateMap)
}
if (
realm?.pubkey &&
previousRealmPubKey !== realm?.pubkey.toBase58() &&
!config?.account.communityTokenConfig.voterWeightAddin
) {
handleSetMembers()
getDelegates()
}
if (
!realm?.pubkey ||
(realm.pubkey && config?.account.communityTokenConfig.voterWeightAddin)
) {
getDelegates()
setMembers([])
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
}, [realm?.pubkey.toBase58()])
handleSetMembers()
getDelegates()
}, [
fetchCommunityMembersATAS,
fetchCouncilMembersWithTokensOutsideRealm,
membersWithTokensDeposited,
realm?.pubkey,
setDelegates,
setMembers,
])
}

View File

@ -6,14 +6,14 @@ import useQueryContext from '@hooks/useQueryContext'
import useRealm from '@hooks/useRealm'
import React from 'react'
import useTreasuryAccountStore from 'stores/useTreasuryAccountStore'
import useWalletStore from 'stores/useWalletStore'
import Link from 'next/link'
import Loading from '@components/Loading'
import useGovernanceAssetsStore from 'stores/useGovernanceAssetsStore'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
const NFTSCompactWrapper = () => {
const { nftsGovernedTokenAccounts } = useGovernanceAssets()
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const realmNfts = useTreasuryAccountStore((s) => s.allNfts)
const isLoading = useTreasuryAccountStore((s) => s.isLoadingNfts)
const isLoadingAssets = useGovernanceAssetsStore((s) => s.loadTokenAccounts)

View File

@ -11,7 +11,7 @@ import { PublicKey } from '@solana/web3.js'
import Loading from '@components/Loading'
import { getNfts } from '@utils/tokens'
import ImgWithLoader from '@components/ImgWithLoader'
import useWalletStore from 'stores/useWalletStore'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
export interface NftSelectorFunctions {
handleGetNfts: () => void
@ -40,7 +40,7 @@ function NFTSelector(
const isPredefinedMode = typeof predefinedNfts !== 'undefined'
const [nfts, setNfts] = useState<NFTWithMint[]>([])
const [selected, setSelected] = useState<NFTWithMint[]>([])
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const [isLoading, setIsLoading] = useState(false)
const handleSelectNft = (nft: NFTWithMint) => {
const nftMint: string[] = []

View File

@ -6,12 +6,12 @@ import cx from 'classnames'
// import ChevronRightIcon from '@carbon/icons-react/lib/ChevronRight'
import useVotePluginsClientStore from 'stores/useVotePluginsClientStore'
import useWalletStore from 'stores/useWalletStore'
import { ConnectionContext } from '@utils/connection'
import BigNumber from 'bignumber.js'
import * as RE from '@utils/uiTypes/Result'
import NFTIcon from '@components/treasuryV2/icons/NFTCollectionPreviewIcon'
import { tryGetMint, getNFTsByCollection } from '@utils/tokens'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
interface CollectionConfig {
collection: PublicKey
@ -128,7 +128,7 @@ interface Props {
}
export function NFTVotePluginSettingsDisplay(props: Props) {
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const registrar = useVotePluginsClientStore((s) => s.state.nftMintRegistrar)
const [collections, setCollections] = useState<RE.Result<Data>>(RE.pending())

View File

@ -3,7 +3,6 @@ import { MintInfo, u64 } from '@solana/spl-token'
import { PublicKey } from '@solana/web3.js'
import { getMintSupplyAsDecimal } from '@tools/sdk/units'
import useWalletStore from 'stores/useWalletStore'
import { tryGetMint } from '@utils/tokens'
import { validatePubkey } from '@utils/formValidation'
import { preventNegativeNumberInput } from '@utils/helpers'
@ -18,6 +17,7 @@ import TokenInfoTable, {
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { TokenInfo } from '@utils/services/types'
import tokenPriceService from '@utils/services/tokenPrice'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
interface MintInfoWithDecimalSupply extends MintInfo {
supplyAsDecimal: number
@ -60,7 +60,7 @@ export default function TokenInput({
onValidation,
disableMinTokenInput = false,
}) {
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const wallet = useWalletOnePointOh()
const connected = !!wallet?.connected
const tokenList = tokenPriceService._tokenList

View File

@ -8,7 +8,6 @@ import { updateUserInput, validatePubkey } from '@utils/formValidation'
import { notify } from '@utils/notifications'
import { abbreviateAddress } from '@utils/formatting'
import useWalletStore from 'stores/useWalletStore'
import { NewButton as Button } from '@components/Button'
import Text from '@components/Text'
@ -24,6 +23,7 @@ import { Metaplex } from '@metaplex-foundation/js'
import { Connection, PublicKey } from '@solana/web3.js'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import asFindable from '@utils/queries/asFindable'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
function filterAndMapVerifiedCollections(nfts) {
return nfts
@ -202,7 +202,7 @@ export default function AddNFTCollectionForm({
onSubmit,
onPrevClick,
}) {
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const wallet = useWalletOnePointOh()
const connected = !!wallet?.connected
const [walletConnecting, setWalletConnecting] = useState(false)

View File

@ -1,8 +1,8 @@
import { useEffect, useState } from 'react'
import { Connection, PublicKey } from '@solana/web3.js'
import { CivicProfile, Profile as BaseProfile } from '@civic/profile'
import useWalletStore from 'stores/useWalletStore'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
type Profile = BaseProfile & {
exists: boolean
@ -24,7 +24,7 @@ const profileIsSet = (profile: BaseProfile): boolean =>
export const useProfile = (
publicKey?: PublicKey
): { profile: Profile | undefined; loading: boolean } => {
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const connectedWallet = useWalletOnePointOh()
const [profile, setProfile] = useState<Profile>()
const [loading, setLoading] = useState(true)

View File

@ -1,12 +1,11 @@
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import { useEffect, useState } from 'react'
import { useHasVoteTimeExpired } from '../hooks/useHasVoteTimeExpired'
import useRealm from '../hooks/useRealm'
import {
getSignatoryRecordAddress,
ProposalState,
SignatoryRecord,
} from '@solana/spl-governance'
import useWalletStore from '../stores/useWalletStore'
import Button, { SecondaryButton } from './Button'
import { RpcContext } from '@solana/spl-governance'
@ -22,19 +21,30 @@ import dayjs from 'dayjs'
import { diffTime } from './ProposalRemainingVotingTime'
import { useMaxVoteRecord } from '@hooks/useMaxVoteRecord'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import {
proposalQueryKeys,
useRouteProposalQuery,
} from '@hooks/queries/proposal'
import { useProposalGovernanceQuery } from '@hooks/useProposal'
import { useTokenOwnerRecordByPubkeyQuery } from '@hooks/queries/tokenOwnerRecord'
import { useAsync } from 'react-async-hook'
import { useGovernanceAccountByPubkeyQuery } from '@hooks/queries/governanceAccount'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
import queryClient from '@hooks/queries/queryClient'
const ProposalActionsPanel = () => {
const { governance, proposal, proposalOwner } = useWalletStore(
(s) => s.selectedProposal
)
const proposal = useRouteProposalQuery().data?.result
const governance = useProposalGovernanceQuery().data?.result
const proposalOwner = useTokenOwnerRecordByPubkeyQuery(
proposal?.account.tokenOwnerRecord
).data?.result
const { realmInfo } = useRealm()
const wallet = useWalletOnePointOh()
const connected = !!wallet?.connected
const hasVoteTimeExpired = useHasVoteTimeExpired(governance, proposal!)
const signatories = useWalletStore((s) => s.selectedProposal.signatories)
const connection = useWalletStore((s) => s.connection)
const refetchProposals = useWalletStore((s) => s.actions.refetchProposals)
const [signatoryRecord, setSignatoryRecord] = useState<any>(undefined)
const connection = useLegacyConnectionContext()
const maxVoteRecordPk = useMaxVoteRecord()?.pubkey
const votePluginsClientMaxVoterWeight = useVotePluginsClientStore(
(s) => s.state.maxVoterWeight
@ -61,24 +71,27 @@ const ProposalActionsPanel = () => {
: undefined
const walletPk = wallet?.publicKey
useEffect(() => {
const setup = async () => {
if (proposal && realmInfo && walletPk) {
const signatoryRecordPk = await getSignatoryRecordAddress(
realmInfo.programId,
proposal.pubkey,
walletPk
)
if (signatoryRecordPk && signatories) {
setSignatoryRecord(signatories[signatoryRecordPk.toBase58()])
}
}
}
const { result: signatoryRecordPk } = useAsync(
async () =>
realmInfo === undefined ||
proposal === undefined ||
walletPk === undefined ||
walletPk === null
? undefined
: getSignatoryRecordAddress(
realmInfo.programId,
proposal.pubkey,
walletPk
),
[realmInfo, proposal, walletPk]
)
setup()
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
}, [proposal?.pubkey.toBase58(), realmInfo?.symbol, walletPk?.toBase58()])
const signatoryRecord = useGovernanceAccountByPubkeyQuery(
SignatoryRecord,
'SignatoryRecord',
signatoryRecordPk
).data?.result
const canSignOff =
signatoryRecord &&
@ -145,8 +158,10 @@ const ProposalActionsPanel = () => {
proposal,
maxVoterWeight
)
await refetchProposals()
}
queryClient.invalidateQueries({
queryKey: proposalQueryKeys.all(connection.endpoint),
})
} catch (error) {
notify({
type: 'error',
@ -160,7 +175,7 @@ const ProposalActionsPanel = () => {
const handleSignOffProposal = async () => {
try {
if (proposal && realmInfo) {
if (proposal && realmInfo && signatoryRecord) {
const rpcContext = new RpcContext(
proposal.owner,
getProgramVersionForRealm(realmInfo),
@ -175,9 +190,10 @@ const ProposalActionsPanel = () => {
proposal,
signatoryRecord
)
await refetchProposals()
}
queryClient.invalidateQueries({
queryKey: proposalQueryKeys.all(connection.endpoint),
})
} catch (error) {
notify({
type: 'error',
@ -202,9 +218,10 @@ const ProposalActionsPanel = () => {
)
await cancelProposal(rpcContext, realmInfo.realmId, proposal)
await refetchProposals()
}
queryClient.invalidateQueries({
queryKey: proposalQueryKeys.all(connection.endpoint),
})
} catch (error) {
notify({
type: 'error',

View File

@ -48,12 +48,10 @@ const ProposalCard = ({ proposalPk, proposal }: ProposalCardProps) => {
{proposal.name}
</h3>
<div className="flex items-center pl-4 pt-1">
{proposal.state === ProposalState.Voting && (
<ProposalMyVoteBadge
className="mr-2"
proposal={{ account: proposal, pubkey: proposalPk }}
/>
)}
<ProposalMyVoteBadge
className="mr-2"
proposal={{ account: proposal, pubkey: proposalPk }}
/>
<ProposalStateBadge proposal={proposal} />
<StyledSvg className="default-transition h-6 ml-3 text-fgd-2 w-6" />
</div>

View File

@ -7,26 +7,25 @@ import {
ExecuteAllInstructionButton,
PlayState,
} from '@components/instructions/ExecuteAllInstructionButton'
import useProposal from '@hooks/useProposal'
import { ntext } from '@utils/ntext'
import Button from '@components/Button'
import { diffTime } from '@components/ProposalRemainingVotingTime'
import useProposalTransactions from '@hooks/useProposalTransactions'
import { useRouteProposalQuery } from '@hooks/queries/proposal'
import { useSelectedProposalTransactions } from '@hooks/queries/proposalTransaction'
interface Props {
className?: string
}
export default function ProposalExecutionCard(props: Props) {
const { transactions, proposal } = useProposal()
const proposal = useRouteProposalQuery().data?.result
const { data: allTransactions } = useSelectedProposalTransactions()
const [playState, setPlayState] = useState(PlayState.Unplayed)
const [timeLeft, setTimeLeft] = useState<
undefined | ReturnType<typeof diffTime>
>()
const timer = useRef<undefined | number>()
const allTransactions = Object.values(transactions)
const proposalTransactions = useProposalTransactions(
allTransactions,
proposal
@ -49,6 +48,7 @@ export default function ProposalExecutionCard(props: Props) {
}, [proposalTransactions?.nextExecuteAt])
if (
allTransactions === undefined ||
allTransactions.length === 0 ||
!proposal ||
!proposalTransactions ||

View File

@ -1,50 +1,13 @@
import { useMemo } from 'react'
import {
Proposal,
ProgramAccount,
VoteRecord,
Realm,
} from '@solana/spl-governance'
import { Proposal, ProgramAccount } from '@solana/spl-governance'
import classNames from 'classnames'
import { ThumbUpIcon, ThumbDownIcon } from '@heroicons/react/solid'
import { isYesVote } from '@models/voteRecords'
import useRealm from '@hooks/useRealm'
import useWalletStore from '../stores/useWalletStore'
import Tooltip from './Tooltip'
interface VoteRecords {
[proposal: string]: ProgramAccount<VoteRecord>
}
function getOwnVoteRecord(
communityDelegateVoteRecords: VoteRecords,
councilDelegateVoteRecords: VoteRecords,
ownVoteRecords: VoteRecords,
proposal: Omit<ProgramAccount<Proposal>, 'owner'>,
realm?: ProgramAccount<Realm>
): ProgramAccount<VoteRecord> | undefined {
const proposalKey = proposal.pubkey.toBase58()
const councilDelegateVote = councilDelegateVoteRecords[proposalKey]
const communityDelegateVote = communityDelegateVoteRecords[proposalKey]
const ownRecord = ownVoteRecords[proposalKey]
const governingTokenMint = proposal.account.governingTokenMint.toBase58()
if (
councilDelegateVote &&
governingTokenMint === realm?.account?.config?.councilMint?.toBase58()
) {
return councilDelegateVote
}
if (
communityDelegateVote &&
governingTokenMint === realm?.account?.communityMint.toBase58()
) {
return communityDelegateVote
}
return ownRecord
}
import { useRealmQuery } from '@hooks/queries/realm'
import { useAddressQuery_VoteRecord } from '@hooks/queries/addresses/voteRecord'
import { useAddressQuery_TokenOwnerRecord } from '@hooks/queries/addresses/tokenOwnerRecord'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useVoteRecordByPubkeyQuery } from '@hooks/queries/voteRecord'
interface Props {
className?: string
@ -52,41 +15,27 @@ interface Props {
}
export default function ProposalMyVoteBadge(props: Props) {
const { realm, ownTokenRecord } = useRealm()
const [
ownVoteRecords,
communityDelegateVoteRecords,
councilDelegateVoteRecords,
] = useWalletStore((s) => [
s.ownVoteRecordsByProposal,
s.communityDelegateVoteRecordsByProposal,
s.councilDelegateVoteRecordsByProposal,
])
const realm = useRealmQuery().data?.result
const wallet = useWalletOnePointOh()
const ownVoteRecord = useMemo(
() =>
getOwnVoteRecord(
communityDelegateVoteRecords,
councilDelegateVoteRecords,
ownVoteRecords,
props.proposal,
realm
),
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
[
communityDelegateVoteRecords,
councilDelegateVoteRecords,
ownVoteRecords,
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
ownTokenRecord?.account.governingTokenOwner.toBase58(),
]
const { data: tokenOwnerRecordPk } = useAddressQuery_TokenOwnerRecord(
realm?.owner,
realm?.pubkey,
props.proposal.account.governingTokenMint,
wallet?.publicKey ?? undefined
)
const { data: voteRecordPk } = useAddressQuery_VoteRecord(
realm?.owner,
props.proposal.pubkey,
tokenOwnerRecordPk
)
const { data: ownVoteRecord } = useVoteRecordByPubkeyQuery(voteRecordPk)
if (!ownVoteRecord) {
if (!ownVoteRecord?.result?.account) {
return null
}
const isYes = isYesVote(ownVoteRecord.account)
const isYes = isYesVote(ownVoteRecord?.result?.account)
return (
<Tooltip content={isYes ? 'You voted "Yes"' : 'You voted "No"'}>
<div

View File

@ -7,6 +7,11 @@ import ProposalTimeStatus from './ProposalTimeStatus'
import { PublicKey } from '@solana/web3.js'
import VoteResults from './VoteResults'
import { SelectedProposal } from 'pages/dao/[symbol]'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useRealmQuery } from '@hooks/queries/realm'
import { useAddressQuery_TokenOwnerRecord } from '@hooks/queries/addresses/tokenOwnerRecord'
import { useAddressQuery_VoteRecord } from '@hooks/queries/addresses/voteRecord'
import { useVoteRecordByPubkeyQuery } from '@hooks/queries/voteRecord'
type ProposalCardProps = {
proposalPk: PublicKey
@ -21,17 +26,30 @@ const ProposalSelectCard = ({
setSelectedProposals,
selectedProposals,
}: ProposalCardProps) => {
const realm = useRealmQuery().data?.result
const wallet = useWalletOnePointOh()
const { data: tokenOwnerRecordPk } = useAddressQuery_TokenOwnerRecord(
realm?.owner,
realm?.pubkey,
proposal.governingTokenMint,
wallet?.publicKey ?? undefined
)
const { data: voteRecordPk } = useAddressQuery_VoteRecord(
realm?.owner,
proposalPk,
tokenOwnerRecordPk
)
const { data: ownVoteRecord } = useVoteRecordByPubkeyQuery(voteRecordPk)
const votesData = useProposalVotes(proposal)
const checked = !!selectedProposals.find(
// @ts-ignore
(p) => p.proposalPk.toString() === proposalPk.toString()
)
const toggleCheckbox = () => {
if (checked) {
const proposals = selectedProposals.filter(
// @ts-ignore
(p) => p.proposalPk.toString() !== proposalPk.toString()
)
setSelectedProposals(proposals)
@ -40,7 +58,9 @@ const ProposalSelectCard = ({
}
}
return (
const myVoteExists = ownVoteRecord?.result !== undefined
return myVoteExists ? null : (
<button
className={`border ${
checked ? 'border-primary-light' : 'border-fgd-4'

View File

@ -1,10 +1,13 @@
import { Proposal, ProposalState } from '@solana/spl-governance'
import classNames from 'classnames'
import useRealm from '@hooks/useRealm'
import useRealmGovernance from '../hooks/useRealmGovernance'
import assertUnreachable from '@utils/typescript/assertUnreachable'
import { isInCoolOffTime } from './VotePanel/hooks'
import {
useUserCommunityTokenOwnerRecord,
useUserCouncilTokenOwnerRecord,
} from '@hooks/queries/tokenOwnerRecord'
import { useGovernanceByPubkeyQuery } from '@hooks/queries/governance'
export const hasInstructions = (proposal: Proposal) => {
if (proposal.instructionsCount) {
@ -151,9 +154,10 @@ interface Props {
}
export default function ProposalStateBadge(props: Props) {
const { ownTokenRecord, ownCouncilTokenRecord } = useRealm()
const governance = useRealmGovernance(props.proposal.governance)
const ownTokenRecord = useUserCommunityTokenOwnerRecord().data?.result
const ownCouncilTokenRecord = useUserCouncilTokenOwnerRecord().data?.result
const governance = useGovernanceByPubkeyQuery(props.proposal.governance).data
?.result
const isCreator =
ownTokenRecord?.pubkey.equals(props.proposal.tokenOwnerRecord) ||
ownCouncilTokenRecord?.pubkey.equals(props.proposal.tokenOwnerRecord) ||
@ -163,9 +167,10 @@ export default function ProposalStateBadge(props: Props) {
const isSignatory = false
const votingEnded =
governance && props.proposal.getTimeToVoteEnd(governance) < 0
governance !== undefined &&
props.proposal.getTimeToVoteEnd(governance.account) < 0
const coolOff = isInCoolOffTime(props.proposal, governance)
const coolOff = isInCoolOffTime(props.proposal, governance?.account)
const otherState = {
isCreator,

View File

@ -1,15 +1,15 @@
import useRealm from '../hooks/useRealm'
import { Proposal, ProposalState } from '@solana/spl-governance'
import { fmtUnixTime } from '../utils/formatting'
import ProposalTimer from './ProposalTimer'
import { useGovernanceByPubkeyQuery } from '@hooks/queries/governance'
type ProposalTimeStatusProps = {
proposal: Proposal
}
const ProposalTimeStatus = ({ proposal }: ProposalTimeStatusProps) => {
const { governances } = useRealm()
const governance = governances[proposal?.governance.toBase58()]?.account
const governance = useGovernanceByPubkeyQuery(proposal.governance).data
?.result
return proposal && governance ? (
<div className="flex items-center text-fgd-3 text-sm">
@ -18,7 +18,7 @@ const ProposalTimeStatus = ({ proposal }: ProposalTimeStatusProps) => {
proposal.votingCompletedAt
)}`
) : proposal.votingAt ? (
<ProposalTimer proposal={proposal} governance={governance} />
<ProposalTimer proposal={proposal} governance={governance.account} />
) : (
`Drafted ${fmtUnixTime(proposal.draftAt)}`
)}

View File

@ -4,8 +4,6 @@ import classNames from 'classnames'
import useRealm from '@hooks/useRealm'
import { calculateMaxVoteScore } from '@models/proposal/calulateMaxVoteScore'
import useProposal from '@hooks/useProposal'
import useWalletStore from 'stores/useWalletStore'
import { SecondaryButton } from '@components/Button'
import { getMintMetadata } from '../instructions/programs/splToken'
@ -13,26 +11,24 @@ import getNumTokens from './getNumTokens'
import depositTokens from './depositTokens'
import VotingPowerPct from './VotingPowerPct'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useUserCommunityTokenOwnerRecord } from '@hooks/queries/tokenOwnerRecord'
import { useRealmQuery } from '@hooks/queries/realm'
import { useRealmCommunityMintInfoQuery } from '@hooks/queries/mintInfo'
import { useRouteProposalQuery } from '@hooks/queries/proposal'
import { useConnection } from '@solana/wallet-adapter-react'
interface Props {
className?: string
}
export default function CommunityVotingPower(props: Props) {
const {
mint,
ownTokenRecord,
ownVoterWeight,
realm,
realmInfo,
realmTokenAccount,
} = useRealm()
const { proposal } = useProposal()
const fetchWalletTokenAccounts = useWalletStore(
(s) => s.actions.fetchWalletTokenAccounts
)
const fetchRealm = useWalletStore((s) => s.actions.fetchRealm)
const connection = useWalletStore((s) => s.connection.current)
const ownTokenRecord = useUserCommunityTokenOwnerRecord().data?.result
const realm = useRealmQuery().data?.result
const mint = useRealmCommunityMintInfoQuery().data?.result
const { ownVoterWeight, realmInfo, realmTokenAccount } = useRealm()
const proposal = useRouteProposalQuery().data?.result
const { connection } = useConnection()
const wallet = useWalletOnePointOh()
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
@ -62,19 +58,8 @@ export default function CommunityVotingPower(props: Props) {
amount: depositAmount,
depositTokenAccount: realmTokenAccount,
})
await fetchWalletTokenAccounts()
await fetchRealm(realmInfo.programId, realmInfo.realmId)
}
}, [
depositAmount,
fetchRealm,
fetchWalletTokenAccounts,
connection,
realmTokenAccount,
realmInfo,
realm,
wallet,
])
}, [depositAmount, connection, realmTokenAccount, realmInfo, realm, wallet])
if (!(realm && realmInfo)) {
return (

View File

@ -1,11 +1,9 @@
import { BigNumber } from 'bignumber.js'
import { useCallback } from 'react'
import { useCallback, useMemo } from 'react'
import classNames from 'classnames'
import useRealm from '@hooks/useRealm'
import { calculateMaxVoteScore } from '@models/proposal/calulateMaxVoteScore'
import useProposal from '@hooks/useProposal'
import useWalletStore from 'stores/useWalletStore'
import { SecondaryButton } from '@components/Button'
import { getMintMetadata } from '../instructions/programs/splToken'
@ -13,32 +11,33 @@ import getNumTokens from './getNumTokens'
import depositTokens from './depositTokens'
import VotingPowerPct from './VotingPowerPct'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useUserCouncilTokenOwnerRecord } from '@hooks/queries/tokenOwnerRecord'
import { useRealmQuery } from '@hooks/queries/realm'
import { useRealmCouncilMintInfoQuery } from '@hooks/queries/mintInfo'
import { useRouteProposalQuery } from '@hooks/queries/proposal'
import { useConnection } from '@solana/wallet-adapter-react'
interface Props {
className?: string
}
export default function CouncilVotingPower(props: Props) {
const {
councilMint,
councilTokenAccount,
ownCouncilTokenRecord,
ownVoterWeight,
realm,
realmInfo,
} = useRealm()
const { proposal } = useProposal()
const fetchWalletTokenAccounts = useWalletStore(
(s) => s.actions.fetchWalletTokenAccounts
)
const fetchRealm = useWalletStore((s) => s.actions.fetchRealm)
const connection = useWalletStore((s) => s.connection.current)
const ownCouncilTokenRecord = useUserCouncilTokenOwnerRecord().data?.result
const realm = useRealmQuery().data?.result
const councilMint = useRealmCouncilMintInfoQuery().data?.result
const { councilTokenAccount, ownVoterWeight, realmInfo } = useRealm()
const proposal = useRouteProposalQuery().data?.result
const { connection } = useConnection()
const wallet = useWalletOnePointOh()
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
const depositAmount = councilTokenAccount
? new BigNumber(councilTokenAccount.account.amount.toString())
: new BigNumber(0)
const depositAmount = useMemo(
() =>
councilTokenAccount
? new BigNumber(councilTokenAccount.account.amount.toString())
: new BigNumber(0),
[councilTokenAccount]
)
const depositMint = realm?.account.config.councilMint
const tokenName =
getMintMetadata(depositMint)?.name ?? realm?.account.name ?? ''
@ -67,19 +66,8 @@ export default function CouncilVotingPower(props: Props) {
amount: depositAmount,
depositTokenAccount: councilTokenAccount,
})
await fetchWalletTokenAccounts()
await fetchRealm(realmInfo.programId, realmInfo.realmId)
}
}, [
depositAmount,
fetchRealm,
fetchWalletTokenAccounts,
connection,
councilTokenAccount,
realmInfo,
realm,
wallet,
])
}, [depositAmount, connection, councilTokenAccount, realmInfo, realm, wallet])
if (!(realm && realmInfo)) {
return (
@ -93,7 +81,7 @@ export default function CouncilVotingPower(props: Props) {
<div className={props.className}>
{amount.isZero() ? (
<div className={'text-xs text-white/50'}>
You do not have any voting power in this dao.
You do not have any council voting power in this dao.
</div>
) : (
<div className={'p-3 rounded-md bg-bkg-1'}>

View File

@ -11,8 +11,11 @@ import Link from 'next/link'
import useQueryContext from '@hooks/useQueryContext'
import InlineNotification from '@components/InlineNotification'
import useVotePluginsClientStore from 'stores/useVotePluginsClientStore'
import { useAddressQuery_CommunityTokenOwner } from '@hooks/queries/addresses/tokenOwner'
import { useAddressQuery_CommunityTokenOwner } from '@hooks/queries/addresses/tokenOwnerRecord'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useUserCommunityTokenOwnerRecord } from '@hooks/queries/tokenOwnerRecord'
import { useRealmQuery } from '@hooks/queries/realm'
import { useRealmCommunityMintInfoQuery } from '@hooks/queries/mintInfo'
interface Props {
className?: string
@ -21,7 +24,11 @@ interface Props {
export default function LockedCommunityNFTRecordVotingPower(props: Props) {
const { fmtUrlWithCluster } = useQueryContext()
const [amount, setAmount] = useState(new BigNumber(0))
const { mint, realm, ownTokenRecord, realmTokenAccount, symbol } = useRealm()
const ownTokenRecord = useUserCommunityTokenOwnerRecord().data?.result
const realm = useRealmQuery().data?.result
const mint = useRealmCommunityMintInfoQuery().data?.result
const { realmTokenAccount, symbol } = useRealm()
const wallet = useWalletOnePointOh()
const connected = !!wallet?.connected
const { data: tokenOwnerRecordPk } = useAddressQuery_CommunityTokenOwner()

View File

@ -5,35 +5,39 @@ import { useCallback } from 'react'
import classNames from 'classnames'
import { calculateMaxVoteScore } from '@models/proposal/calulateMaxVoteScore'
import useProposal from '@hooks/useProposal'
import useDepositStore from 'VoteStakeRegistry/stores/useDepositStore'
import { getMintDecimalAmount } from '@tools/sdk/units'
import Tooltip from '@components/Tooltip'
import { SecondaryButton } from '@components/Button'
import useVotePluginsClientStore from 'stores/useVotePluginsClientStore'
import useWalletStore from 'stores/useWalletStore'
import { notify } from '@utils/notifications'
import { getMintMetadata } from '../instructions/programs/splToken'
import depositTokensVSR from './depositTokensVSR'
import VotingPowerPct from './VotingPowerPct'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useRealmQuery } from '@hooks/queries/realm'
import { useUserCommunityTokenOwnerRecord } from '@hooks/queries/tokenOwnerRecord'
import { useRealmCommunityMintInfoQuery } from '@hooks/queries/mintInfo'
import { useRouteProposalQuery } from '@hooks/queries/proposal'
import { useConnection } from '@solana/wallet-adapter-react'
interface Props {
className?: string
}
export default function LockedCommunityVotingPower(props: Props) {
const { mint, realm, realmInfo, realmTokenAccount, tokenRecords } = useRealm()
const { proposal } = useProposal()
const realm = useRealmQuery().data?.result
const mint = useRealmCommunityMintInfoQuery().data?.result
const { realmInfo, realmTokenAccount } = useRealm()
const proposal = useRouteProposalQuery().data?.result
const client = useVotePluginsClientStore((s) => s.state.vsrClient)
const connection = useWalletStore((s) => s.connection.current)
const { connection } = useConnection()
const deposits = useDepositStore((s) => s.state.deposits)
const endpoint = useWalletStore((s) => s.connection.endpoint)
const fetchRealm = useWalletStore((s) => s.actions.fetchRealm)
const fetchWalletTokenAccounts = useWalletStore(
(s) => s.actions.fetchWalletTokenAccounts
)
const endpoint = connection.rpcEndpoint
const getOwnedDeposits = useDepositStore((s) => s.getOwnedDeposits)
const votingPower = useDepositStore((s) => s.state.votingPower)
const votingPowerFromDeposits = useDepositStore(
@ -42,10 +46,9 @@ export default function LockedCommunityVotingPower(props: Props) {
const wallet = useWalletOnePointOh()
const isLoading = useDepositStore((s) => s.state.isLoading)
const currentTokenOwnerRecord =
wallet && wallet.publicKey
? tokenRecords[wallet.publicKey.toBase58()]
: null
const currentTokenOwnerRecord = useUserCommunityTokenOwnerRecord().data
?.result
const tokenOwnerRecordPk = currentTokenOwnerRecord
? currentTokenOwnerRecord.pubkey
: null
@ -53,7 +56,7 @@ export default function LockedCommunityVotingPower(props: Props) {
const depositRecord = deposits.find(
(deposit) =>
deposit.mint.publicKey.toBase58() ===
realm!.account.communityMint.toBase58() && deposit.lockup.kind.none
realm?.account.communityMint.toBase58() && deposit.lockup.kind.none
)
const depositMint = realm?.account.communityMint
@ -127,9 +130,6 @@ export default function LockedCommunityVotingPower(props: Props) {
realmPk: realm.pubkey,
walletPk: wallet.publicKey,
})
await fetchWalletTokenAccounts()
await fetchRealm(realmInfo.programId, realmInfo.realmId)
} catch (e) {
console.error(e)
notify({ message: `Something went wrong ${e}`, type: 'error' })
@ -139,8 +139,6 @@ export default function LockedCommunityVotingPower(props: Props) {
client,
connection,
endpoint,
fetchWalletTokenAccounts,
fetchRealm,
getOwnedDeposits,
realm,
realmInfo,

View File

@ -1,22 +1,24 @@
import useRealm from '@hooks/useRealm'
import { BigNumber } from 'bignumber.js'
import classNames from 'classnames'
import { calculateMaxVoteScore } from '@models/proposal/calulateMaxVoteScore'
import useProposal from '@hooks/useProposal'
import useDepositStore from 'VoteStakeRegistry/stores/useDepositStore'
import { fmtMintAmount, getMintDecimalAmount } from '@tools/sdk/units'
import { getMintMetadata } from '../instructions/programs/splToken'
import VotingPowerPct from './VotingPowerPct'
import { useRealmQuery } from '@hooks/queries/realm'
import { useRealmCouncilMintInfoQuery } from '@hooks/queries/mintInfo'
import { useRouteProposalQuery } from '@hooks/queries/proposal'
interface Props {
className?: string
}
export default function LockedCouncilVotingPower(props: Props) {
const { councilMint, realm } = useRealm()
const { proposal } = useProposal()
const realm = useRealmQuery().data?.result
const councilMint = useRealmCouncilMintInfoQuery().data?.result
const proposal = useRouteProposalQuery().data?.result
const deposits = useDepositStore((s) => s.state.deposits)
const votingPower = useDepositStore((s) => s.state.votingPower)
const isLoading = useDepositStore((s) => s.state.isLoading)
@ -24,7 +26,7 @@ export default function LockedCouncilVotingPower(props: Props) {
const depositRecord = deposits.find(
(deposit) =>
deposit.mint.publicKey.toBase58() ===
realm!.account.communityMint.toBase58() && deposit.lockup.kind.none
realm?.account.communityMint.toBase58() && deposit.lockup.kind.none
)
const depositMint = realm?.account.config.councilMint

View File

@ -9,7 +9,6 @@ import {
import { NftVoterClient } from '@utils/uiTypes/NftVoterClient'
import useNftPluginStore from 'NftVotePlugin/store/nftPluginStore'
import useWalletStore from 'stores/useWalletStore'
import useRealm from '@hooks/useRealm'
import Button from '@components/Button'
import { getVoterWeightRecord } from '@utils/plugin/accounts'
@ -18,6 +17,9 @@ import { sendTransaction } from '@utils/send'
import VotingPowerPct from './VotingPowerPct'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useUserCommunityTokenOwnerRecord } from '@hooks/queries/tokenOwnerRecord'
import { useRealmQuery } from '@hooks/queries/realm'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
interface Props {
className?: string
@ -32,9 +34,10 @@ export default function NftVotingPower(props: Props) {
const isLoading = useNftPluginStore((s) => s.state.isLoadingNfts)
const wallet = useWalletOnePointOh()
const connected = !!wallet?.connected
const connection = useWalletStore((s) => s.connection)
const fetchRealm = useWalletStore((s) => s.actions.fetchRealm)
const { ownTokenRecord, realm, realmInfo } = useRealm()
const connection = useLegacyConnectionContext()
const ownTokenRecord = useUserCommunityTokenOwnerRecord().data?.result
const realm = useRealmQuery().data?.result
const { realmInfo } = useRealm()
const client = useVotePluginsClientStore(
(s) => s.state.currentRealmVotingClient
)
@ -47,46 +50,47 @@ export default function NftVotingPower(props: Props) {
const amount = new BigNumber(votingPower.toString())
const handleRegister = async () => {
if (!realm || !wallet?.publicKey || !client.client || !realmInfo)
throw new Error()
const instructions: TransactionInstruction[] = []
const { voterWeightPk } = await getVoterWeightRecord(
realm!.pubkey,
realm!.account.communityMint,
wallet!.publicKey!,
client.client!.program.programId
realm.pubkey,
realm.account.communityMint,
wallet.publicKey,
client.client.program.programId
)
const createVoterWeightRecordIx = await (client.client as NftVoterClient).program.methods
.createVoterWeightRecord(wallet!.publicKey!)
.createVoterWeightRecord(wallet.publicKey)
.accounts({
voterWeightRecord: voterWeightPk,
governanceProgramId: realm!.owner,
realm: realm!.pubkey,
realmGoverningTokenMint: realm!.account.communityMint,
payer: wallet!.publicKey!,
governanceProgramId: realm.owner,
realm: realm.pubkey,
realmGoverningTokenMint: realm.account.communityMint,
payer: wallet.publicKey,
systemProgram: SYSTEM_PROGRAM_ID,
})
.instruction()
instructions.push(createVoterWeightRecordIx)
await withCreateTokenOwnerRecord(
instructions,
realm!.owner!,
realmInfo?.programVersion!,
realm!.pubkey,
wallet!.publicKey!,
realm!.account.communityMint,
wallet!.publicKey!
realm.owner,
realmInfo.programVersion!,
realm.pubkey,
wallet.publicKey,
realm.account.communityMint,
wallet.publicKey
)
const transaction = new Transaction()
transaction.add(...instructions)
await sendTransaction({
transaction: transaction,
wallet: wallet!,
wallet: wallet,
connection: connection.current,
signers: [],
sendingMessage: `Registering`,
successMessage: `Registered`,
})
await fetchRealm(realm?.owner, realm?.pubkey)
}
if (isLoading) {

View File

@ -8,17 +8,14 @@ import {
} from '@solana/spl-governance'
import { AccountInfo, MintInfo } from '@solana/spl-token'
import type { PublicKey } from '@solana/web3.js'
import { GoverningTokenRole } from '@solana/spl-governance'
import { TokenProgramAccount } from '@utils/tokens'
import useRealm from '@hooks/useRealm'
import {
heliumVsrPluginsPks,
nftPluginsPks,
vsrPluginsPks,
} from '@hooks/useVotingPlugins'
import useProposal from '@hooks/useProposal'
import useWalletStore from 'stores/useWalletStore'
HELIUM_VSR_PLUGINS_PKS,
NFT_PLUGINS_PKS,
VSR_PLUGIN_PKS,
} from '@constants/plugins'
import CommunityVotingPower from './CommunityVotingPower'
import CouncilVotingPower from './CouncilVotingPower'
@ -27,6 +24,18 @@ import LockedCouncilVotingPower from './LockedCouncilVotingPower'
import NftVotingPower from './NftVotingPower'
import LockedCommunityNFTRecordVotingPower from './LockedCommunityNFTRecordVotingPower'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import {
useUserCommunityTokenOwnerRecord,
useUserCouncilTokenOwnerRecord,
} from '@hooks/queries/tokenOwnerRecord'
import { useRealmQuery } from '@hooks/queries/realm'
import { useRealmConfigQuery } from '@hooks/queries/realmConfig'
import {
useRealmCommunityMintInfoQuery,
useRealmCouncilMintInfoQuery,
} from '@hooks/queries/mintInfo'
import { useVotingPop } from '@components/VotePanel/hooks'
import { useRouteProposalQuery } from '@hooks/queries/proposal'
enum Type {
Council,
@ -46,7 +55,7 @@ function getTypes(
ownTokenRecord?: ProgramAccount<TokenOwnerRecord>,
proposal?: ProgramAccount<Proposal>,
realm?: ProgramAccount<Realm>,
tokenRole?: GoverningTokenRole
tokenRole?: 'community' | 'council'
) {
const types: Type[] = []
@ -61,45 +70,45 @@ function getTypes(
if (
currentPluginPk &&
nftPluginsPks.includes(currentPluginPk.toBase58()) &&
tokenRole === GoverningTokenRole.Community
NFT_PLUGINS_PKS.includes(currentPluginPk.toBase58()) &&
tokenRole === 'community'
) {
types.push(Type.NFT)
} else if (
currentPluginPk &&
vsrPluginsPks.includes(currentPluginPk.toBase58())
VSR_PLUGIN_PKS.includes(currentPluginPk.toBase58())
) {
if (
(!realm?.account.config.councilMint ||
isDepositVisible(mint, realm?.account.communityMint)) &&
tokenRole === GoverningTokenRole.Community
tokenRole === 'community'
) {
types.push(Type.LockedCommunity)
} else if (
isDepositVisible(councilMint, realm?.account.config.councilMint) &&
tokenRole === GoverningTokenRole.Council
tokenRole === 'council'
) {
types.push(Type.LockedCouncil)
}
} else if (
currentPluginPk &&
heliumVsrPluginsPks.includes(currentPluginPk.toBase58())
HELIUM_VSR_PLUGINS_PKS.includes(currentPluginPk.toBase58())
) {
if (
(!realm?.account.config.councilMint ||
isDepositVisible(mint, realm?.account.communityMint)) &&
tokenRole === GoverningTokenRole.Community
tokenRole === 'community'
) {
types.push(Type.LockedCommunityNFTRecord)
} else if (
isDepositVisible(councilMint, realm?.account.config.councilMint) &&
tokenRole === GoverningTokenRole.Council
tokenRole === 'council'
) {
types.push(Type.Council)
}
} else if (tokenRole === GoverningTokenRole.Council) {
} else if (tokenRole === 'council') {
types.push(Type.Council)
} else if (tokenRole === GoverningTokenRole.Community) {
} else if (tokenRole === 'community') {
types.push(Type.Community)
}
@ -111,19 +120,18 @@ interface Props {
}
export default function VotingPower(props: Props) {
const { proposal } = useProposal()
const {
config,
councilMint,
councilTokenAccount,
mint,
ownCouncilTokenRecord,
ownTokenRecord,
realm,
} = useRealm()
const proposal = useRouteProposalQuery().data?.result
const ownTokenRecord = useUserCommunityTokenOwnerRecord().data?.result
const ownCouncilTokenRecord = useUserCouncilTokenOwnerRecord().data?.result
const realm = useRealmQuery().data?.result
const config = useRealmConfigQuery().data?.result
const mint = useRealmCommunityMintInfoQuery().data?.result
const councilMint = useRealmCouncilMintInfoQuery().data?.result
const { councilTokenAccount } = useRealm()
const wallet = useWalletOnePointOh()
const connected = !!wallet?.connected
const tokenRole = useWalletStore((s) => s.selectedProposal.tokenRole)
const tokenRole = useVotingPop()
const types = getTypes(
config,

View File

@ -1,34 +1,33 @@
import classNames from 'classnames'
import useWalletStore from 'stores/useWalletStore'
import {
gatewayPluginsPks,
switchboardPluginsPks,
} from '@hooks/useVotingPlugins'
GATEWAY_PLUGINS_PKS,
SWITCHBOARD_PLUGINS_PKS,
} from '@constants/plugins'
import TokenBalanceCardWrapper from '@components/TokenBalance/TokenBalanceCardWrapper'
import useRealm from '@hooks/useRealm'
import useProposal from '@hooks/useProposal'
import { option } from '@tools/core/option'
import VotingPower from './VotingPower'
import { useRealmConfigQuery } from '@hooks/queries/realmConfig'
import { useRouteProposalQuery } from '@hooks/queries/proposal'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
interface Props {
className?: string
}
export default function ProposalVotingPower(props: Props) {
const connected = !!useWalletStore((s) => s.current?.connected)
const { config } = useRealm()
const { proposal } = useProposal()
const connected = useWalletOnePointOh()?.connected
const config = useRealmConfigQuery().data?.result
const proposal = useRouteProposalQuery().data?.result
const currentPluginPk = config?.account?.communityTokenConfig.voterWeightAddin
const isUsingGatewayPlugin =
currentPluginPk && gatewayPluginsPks.includes(currentPluginPk.toBase58())
currentPluginPk && GATEWAY_PLUGINS_PKS.includes(currentPluginPk.toBase58())
const isUsingSwitchboardPlugin =
currentPluginPk &&
switchboardPluginsPks.includes(currentPluginPk.toBase58())
SWITCHBOARD_PLUGINS_PKS.includes(currentPluginPk.toBase58())
if (isUsingGatewayPlugin || isUsingSwitchboardPlugin) {
return <TokenBalanceCardWrapper proposal={option(proposal?.account)} />

View File

@ -9,17 +9,15 @@ import { getRealmExplorerHost } from 'tools/routing'
import useMembersStore from 'stores/useMembersStore'
import { tryParsePublicKey } from '@tools/core/pubkey'
import { useRealmQuery } from '@hooks/queries/realm'
import { useRealmConfigQuery } from '@hooks/queries/realmConfig'
const RealmHeader = () => {
const { fmtUrlWithCluster } = useQueryContext()
const {
realm,
realmInfo,
realmDisplayName,
symbol,
config,
vsrMode,
} = useRealm()
const realm = useRealmQuery().data?.result
const config = useRealmConfigQuery().data?.result
const { realmInfo, symbol, vsrMode } = useRealm()
const { REALM } = process.env
const activeMembers = useMembersStore((s) => s.compact.activeMembers)
const isBackNavVisible = realmInfo?.symbol !== REALM // hide backnav for the default realm
@ -44,7 +42,7 @@ const RealmHeader = () => {
) : null}
</div>
<div className="flex flex-col items-center md:flex-row md:justify-between">
{realmDisplayName ? (
{realmInfo?.displayName ? (
<div className="flex items-center">
<div className="flex flex-col items-center pb-3 md:flex-row md:pb-0">
{realmInfo?.ogImage ? (
@ -54,11 +52,11 @@ const RealmHeader = () => {
></img>
) : (
<div className="bg-[rgba(255,255,255,0.1)] h-14 w-14 flex font-bold items-center justify-center rounded-full text-fgd-3">
{realmDisplayName?.charAt(0)}
{realmInfo.displayName.charAt(0)}
</div>
)}
<div className="flex items-center">
<h1 className="ml-3">{realmDisplayName}</h1>
<h1 className="ml-3">{realmInfo.displayName}</h1>
</div>
</div>
</div>

View File

@ -14,7 +14,6 @@ import {
parseMintNaturalAmountFromDecimalAsBN,
} from '@tools/sdk/units'
import { useMemo, useState } from 'react'
import useWalletStore from 'stores/useWalletStore'
import Loading from '@components/Loading'
import {
getInstructionDataFromBase64,
@ -29,6 +28,7 @@ import useRealm from '@hooks/useRealm'
import { useRouter } from 'next/router'
import { getAssociatedTokenAddress } from '@blockworks-foundation/mango-v4'
import { InstructionDataWithHoldUpTime } from 'actions/createProposal'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
type DepositCardProps = {
mint: 'SRM' | 'MSRM'
@ -54,7 +54,7 @@ const DepositCard = ({ mint, callback, createProposal }: DepositCardProps) => {
const { wallet, anchorProvider } = useWalletDeprecated()
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const actions = useSerumGovStore((s) => s.actions)
const { srmMint, msrmMint } = useSerumGovStore((s) => ({
srmMint: s.srmMint,

View File

@ -14,7 +14,6 @@ import useSerumGovStore, {
} from 'stores/useSerumGovStore'
import { notify } from '@utils/notifications'
import useWalletDeprecated from '@hooks/useWalletDeprecated'
import useWalletStore from 'stores/useWalletStore'
import { useRouter } from 'next/router'
import useRealm from '@hooks/useRealm'
import useQueryContext from '@hooks/useQueryContext'
@ -31,6 +30,7 @@ import { dryRunInstruction } from 'actions/dryRunInstruction'
import Link from 'next/link'
import { getExplorerUrl } from '@components/explorer/tools'
import { ExternalLinkIcon } from '@heroicons/react/outline'
import { useConnection } from '@solana/wallet-adapter-react'
const BurnLockedAccountSchema = {
amount: yup.string().required(),
@ -64,7 +64,7 @@ const LockedAccount: FC<Props> = ({
const actions = useSerumGovStore((s) => s.actions)
const { anchorProvider, wallet } = useWalletDeprecated()
const connection = useWalletStore((s) => s.connection.current)
const { connection } = useConnection()
const [isBurning, setIsBurning] = useState(false)

View File

@ -12,6 +12,7 @@ import {
ProgramAccount,
serializeInstructionToBase64,
} from '@solana/spl-governance'
import { useConnection } from '@solana/wallet-adapter-react'
import { PublicKey, Transaction, TransactionInstruction } from '@solana/web3.js'
import { fmtBnMintDecimals } from '@tools/sdk/units'
import { createAssociatedTokenAccount } from '@utils/associated'
@ -29,7 +30,6 @@ import useSerumGovStore, {
RedeemTicketType,
SRM_DECIMALS,
} from 'stores/useSerumGovStore'
import useWalletStore from 'stores/useWalletStore'
type TicketType = ClaimTicketType | RedeemTicketType
@ -57,7 +57,7 @@ const Ticket: FC<Props> = ({ ticket, createProposal, callback }) => {
const { symbol } = useRealm()
const { fmtUrlWithCluster } = useQueryContext()
const connection = useWalletStore((s) => s.connection.current)
const { connection } = useConnection()
const { anchorProvider, wallet } = useWalletDeprecated()
const actions = useSerumGovStore((s) => s.actions)

View File

@ -13,7 +13,6 @@ import useSerumGovStore, {
SRM_DECIMALS,
VestAccountType,
} from 'stores/useSerumGovStore'
import useWalletStore from 'stores/useWalletStore'
import { SubmitHandler, useForm } from 'react-hook-form'
import { notify } from '@utils/notifications'
import { MSRM_DECIMALS } from '@project-serum/serum/lib/token-instructions'
@ -34,6 +33,7 @@ import { dryRunInstruction } from 'actions/dryRunInstruction'
import { ExternalLinkIcon } from '@heroicons/react/outline'
import Link from 'next/link'
import { getExplorerUrl } from '@components/explorer/tools'
import { useConnection } from '@solana/wallet-adapter-react'
const BurnVestAccountSchema = {
amount: yup.string().required(),
@ -68,7 +68,7 @@ const VestAccount: FC<Props> = ({
const actions = useSerumGovStore((s) => s.actions)
const { anchorProvider, wallet } = useWalletDeprecated()
const connection = useWalletStore((s) => s.connection.current)
const { connection } = useConnection()
const [isBurning, setIsBurning] = useState(false)
const [currentTimestamp, setCurrentTimestamp] = useState(0)

View File

@ -1,6 +1,5 @@
import useRealm from '@hooks/useRealm'
import { useEffect, useState } from 'react'
import useWalletStore from 'stores/useWalletStore'
import { TransactionInstruction } from '@solana/web3.js'
import { SecondaryButton } from '@components/Button'
import useVotePluginsClientStore from 'stores/useVotePluginsClientStore'
@ -12,9 +11,17 @@ import {
SequenceType,
txBatchesToInstructionSetWithSigners,
} from '@utils/sendTransactions'
import { ProposalState } from '@solana/spl-governance'
import { ProposalState, getProposal } from '@solana/spl-governance'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useAddressQuery_CommunityTokenOwner } from '@hooks/queries/addresses/tokenOwner'
import { useAddressQuery_CommunityTokenOwner } from '@hooks/queries/addresses/tokenOwnerRecord'
import { useRealmQuery } from '@hooks/queries/realm'
import { useConnection } from '@solana/wallet-adapter-react'
import queryClient from '@hooks/queries/queryClient'
import asFindable from '@utils/queries/asFindable'
import {
proposalQueryKeys,
useRealmProposalsQuery,
} from '@hooks/queries/proposal'
const NFT_SOL_BALANCE = 0.0014616
@ -25,17 +32,18 @@ const ClaimUnreleasedNFTs = ({
}) => {
const wallet = useWalletOnePointOh()
const [isLoading, setIsLoading] = useState(false)
const { current: connection } = useWalletStore((s) => s.connection)
const { connection } = useConnection()
const [ownNftVoteRecords, setOwnNftVoteRecords] = useState<any[]>([])
const [solToBeClaimed, setSolToBeClaimed] = useState(0)
const ownNftVoteRecordsFilterd = ownNftVoteRecords
const { realm } = useWalletStore((s) => s.selectedRealm)
const realm = useRealmQuery().data?.result
const client = useVotePluginsClientStore(
(s) => s.state.currentRealmVotingClient
)
const { proposals, isNftMode } = useRealm()
const { isNftMode } = useRealm()
const { data: tokenOwnerRecord } = useAddressQuery_CommunityTokenOwner()
const { data: proposals } = useRealmProposalsQuery()
const releaseNfts = async (count: number | null = null) => {
if (!wallet?.publicKey) throw new Error('no wallet')
@ -61,8 +69,20 @@ const ClaimUnreleasedNFTs = ({
count ? count : ownNftVoteRecordsFilterd.length
)
for (const i of nfts) {
const proposal = proposals[i.account.proposal.toBase58()]
if (proposal.account.state === ProposalState.Voting) {
const proposalQuery = await queryClient.fetchQuery({
queryKey: proposalQueryKeys.byPubkey(
connection.rpcEndpoint,
i.account.proposal
),
staleTime: 0,
queryFn: () =>
asFindable(() => getProposal(connection, i.account.proposal))(),
})
const proposal = proposalQuery.result
if (
proposal === undefined ||
proposal.account.state === ProposalState.Voting
) {
// ignore this one as it's still in voting
continue
}
@ -118,16 +138,17 @@ const ClaimUnreleasedNFTs = ({
},
])
const nftVoteRecordsFiltered = nftVoteRecords.filter(
(x) =>
proposals[x.account.proposal.toBase58()] &&
proposals[
x.account.proposal.toBase58()
].account.governingTokenMint.toBase58() ===
const nftVoteRecordsFiltered = nftVoteRecords.filter((x) => {
const proposal = proposals?.find((y) =>
y.pubkey.equals(x.account.proposal)
)
return (
proposal &&
proposal.account.governingTokenMint.toBase58() ===
realm?.account.communityMint.toBase58() &&
proposals[x.account.proposal.toBase58()].account.state !==
ProposalState.Voting
)
proposal.account.state !== ProposalState.Voting
)
})
setOwnNftVoteRecords(nftVoteRecordsFiltered)
setSolToBeClaimed(nftVoteRecordsFiltered.length * NFT_SOL_BALANCE)
}

View File

@ -1,36 +1,30 @@
import { BN_ZERO } from '@solana/spl-governance'
import { DisplayAddress } from '@cardinal/namespaces-components'
import Select from '@components/inputs/Select'
import { fmtMintAmount } from '@tools/sdk/units'
import useMembersStore from 'stores/useMembersStore'
import useWalletStore from 'stores/useWalletStore'
import useRealm from 'hooks/useRealm'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import {
useUserCommunityTokenOwnerRecord,
useUserCouncilTokenOwnerRecord,
} from '@hooks/queries/tokenOwnerRecord'
import { useSelectedDelegatorStore } from 'stores/useSelectedDelegatorStore'
import { PublicKey } from '@solana/web3.js'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
const DelegateBalanceCard = () => {
const delegates = useMembersStore((s) => s.compact.delegates)
const wallet = useWalletOnePointOh()
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const walletId = wallet?.publicKey?.toBase58()
const {
ownDelegateTokenRecords,
ownDelegateCouncilTokenRecords,
ownTokenRecord,
ownCouncilTokenRecord,
mint,
councilMint,
} = useRealm()
const { actions } = useWalletStore((s) => s)
const ownTokenRecord = useUserCommunityTokenOwnerRecord().data?.result
const ownCouncilTokenRecord = useUserCouncilTokenOwnerRecord().data?.result
const getCouncilTokenCount = () => {
if (walletId && delegates?.[walletId]) {
return fmtMintAmount(
councilMint,
delegates?.[walletId].councilTokenCount ?? BN_ZERO
)
}
return 0
}
const { ownDelegateTokenRecords, ownDelegateCouncilTokenRecords } = useRealm()
const {
setCommunityDelegator,
setCouncilDelegator,
} = useSelectedDelegatorStore()
const getCouncilDelegateAmt = () => {
if (walletId && delegates?.[walletId]) {
@ -39,16 +33,6 @@ const DelegateBalanceCard = () => {
return 0
}
const getCommunityTokenCount = () => {
if (walletId && delegates?.[walletId]) {
return fmtMintAmount(
mint,
delegates?.[walletId].communityTokenCount ?? BN_ZERO
)
}
return 0
}
const getCommunityDelegateAmt = () => {
if (walletId && delegates?.[walletId]) {
return delegates?.[walletId]?.communityMembers?.length ?? 0
@ -56,12 +40,16 @@ const DelegateBalanceCard = () => {
return 0
}
const handleCouncilSelect = (councilTokenRecord: string) => {
actions.selectCouncilDelegate(councilTokenRecord)
const handleCouncilSelect = (councilTokenRecord?: string) => {
setCouncilDelegator(
councilTokenRecord ? new PublicKey(councilTokenRecord) : undefined
)
}
const handleCommunitySelect = (communityPubKey: string) => {
actions.selectCommunityDelegate(communityPubKey)
const handleCommunitySelect = (communityPubKey?: string) => {
setCommunityDelegator(
communityPubKey ? new PublicKey(communityPubKey) : undefined
)
}
if (!walletId || !delegates?.[walletId]) {
@ -75,12 +63,6 @@ const DelegateBalanceCard = () => {
<div className="flex space-x-4 items-center mt-4">
<div className="bg-bkg-1 px-4 py-2 justify-between rounded-md w-full">
<div className="flex flex-row justify-between w-full mb-2">
<div>
<p className="text-fgd-3 text-xs"> Council Votes</p>
<p className="font-bold mb-0 text-fgd-1 text-xl">
{getCouncilTokenCount()}
</p>
</div>
<div>
<p className="text-fgd-3 text-xs">Delegate Accounts</p>
<p className="font-bold mb-0 text-fgd-1 text-xl">
@ -117,7 +99,7 @@ const DelegateBalanceCard = () => {
)
}
>
<Select.Option key={'reset'} value={''}>
<Select.Option key={'reset'} value={undefined}>
Use own wallet
</Select.Option>
{ownDelegateCouncilTokenRecords?.map((councilDelegate) => (
@ -145,12 +127,6 @@ const DelegateBalanceCard = () => {
<div className="flex space-x-4 items-center mt-4">
<div className="bg-bkg-1 px-4 py-2 justify-between rounded-md w-full">
<div className="flex flex-row justify-between w-full mb-2">
<div>
<p className="text-fgd-3 text-xs">Community Votes</p>
<p className="font-bold mb-0 text-fgd-1 text-xl">
{getCommunityTokenCount()}
</p>
</div>
<div>
<p className="text-fgd-3 text-xs">Delegate Accounts</p>
<p className="font-bold mb-0 text-fgd-1 text-xl">

View File

@ -8,9 +8,10 @@ import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { getTokenOwnerRecordAddress } from '@solana/spl-governance'
import Link from 'next/link'
import { useState, useEffect } from 'react'
import useWalletStore from 'stores/useWalletStore'
import useSwitchboardPluginStore from 'SwitchboardVotePlugin/store/switchboardStore'
import { sbRefreshWeight } from '../../actions/switchboardRefreshVoterWeight'
import { useRealmQuery } from '@hooks/queries/realm'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
const SwitchboardPermissionCard = () => {
const { fmtUrlWithCluster } = useQueryContext()
@ -25,8 +26,9 @@ const SwitchboardPermissionCard = () => {
)
const [tokenOwnerRecordPk, setTokenOwneRecordPk] = useState('')
const { realm, symbol } = useRealm()
const connection = useWalletStore((s) => s.connection)
const realm = useRealmQuery().data?.result
const { symbol } = useRealm()
const connection = useLegacyConnectionContext()
useEffect(() => {
const getTokenOwnerRecord = async () => {

View File

@ -18,7 +18,6 @@ import { getUnrelinquishedVoteRecords } from '@models/api'
import { withDepositGoverningTokens } from '@solana/spl-governance'
import { withRelinquishVote } from '@solana/spl-governance'
import { withWithdrawGoverningTokens } from '@solana/spl-governance'
import useWalletStore from '../../stores/useWalletStore'
import { sendTransaction } from '@utils/send'
import { approveTokenTransfer } from '@utils/tokens'
import Button, { SecondaryButton } from '../Button'
@ -33,7 +32,7 @@ import { notify } from '@utils/notifications'
import { ExclamationIcon } from '@heroicons/react/outline'
import { useEffect, useState } from 'react'
import useVotePluginsClientStore from 'stores/useVotePluginsClientStore'
import { vsrPluginsPks } from '@hooks/useVotingPlugins'
import { VSR_PLUGIN_PKS } from '@constants/plugins'
import { REALM_ID as PYTH_REALM_ID } from 'pyth-staking-api'
import DelegateTokenBalanceCard from '@components/TokenBalance/DelegateTokenBalanceCard'
import SerumGovernanceTokenWrapper from './SerumGovernanceTokenWrapper'
@ -41,6 +40,21 @@ import getNumTokens from '@components/ProposalVotingPower/getNumTokens'
import VotingPowerPct from '@components/ProposalVotingPower/VotingPowerPct'
import { useMaxVoteRecord } from '@hooks/useMaxVoteRecord'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import {
useUserCommunityTokenOwnerRecord,
useUserCouncilTokenOwnerRecord,
} from '@hooks/queries/tokenOwnerRecord'
import { useRealmQuery } from '@hooks/queries/realm'
import { useRealmConfigQuery } from '@hooks/queries/realmConfig'
import {
useRealmCommunityMintInfoQuery,
useRealmCouncilMintInfoQuery,
} from '@hooks/queries/mintInfo'
import { fetchGovernanceByPubkey } from '@hooks/queries/governance'
import { useConnection } from '@solana/wallet-adapter-react'
import queryClient from '@hooks/queries/queryClient'
import { proposalQueryKeys } from '@hooks/queries/proposal'
import asFindable from '@utils/queries/asFindable'
const TokenBalanceCard = ({
proposal,
@ -51,9 +65,11 @@ const TokenBalanceCard = ({
inAccountDetails?: boolean
children?: React.ReactNode
}) => {
const realmProgramId = useWalletStore((s) => s.selectedRealm.programId)
const [hasGovPower, setHasGovPower] = useState<boolean>(false)
const { councilMint, mint, realm } = useRealm()
const realm = useRealmQuery().data?.result
const realmProgramId = realm?.owner
const mint = useRealmCommunityMintInfoQuery().data?.result
const councilMint = useRealmCouncilMintInfoQuery().data?.result
const wallet = useWalletOnePointOh()
const connected = !!wallet?.connected
const isDepositVisible = (
@ -145,34 +161,27 @@ export const TokenDeposit = ({
}) => {
const wallet = useWalletOnePointOh()
const connected = !!wallet?.connected
const connection = useWalletStore((s) => s.connection.current)
const { fetchWalletTokenAccounts, fetchRealm } = useWalletStore(
(s) => s.actions
)
const { connection } = useConnection()
const client = useVotePluginsClientStore(
(s) => s.state.currentRealmVotingClient
)
const maxVoterWeight = useMaxVoteRecord()?.pubkey || undefined
const ownTokenRecord = useUserCommunityTokenOwnerRecord().data?.result
const ownCouncilTokenRecord = useUserCouncilTokenOwnerRecord().data?.result
const realm = useRealmQuery().data?.result
const config = useRealmConfigQuery().data?.result
const councilMint = useRealmCouncilMintInfoQuery().data?.result
const {
realm,
realmInfo,
realmTokenAccount,
ownTokenRecord,
ownCouncilTokenRecord,
ownVoterWeight,
councilMint,
councilTokenAccount,
proposals,
governances,
toManyCommunityOutstandingProposalsForUser,
toManyCouncilOutstandingProposalsForUse,
config,
} = useRealm()
// Do not show deposits for mints with zero supply because nobody can deposit anyway
if (!mint || mint.supply.isZero()) {
return null
}
const amount =
councilMint && tokenRole === GoverningTokenRole.Council
@ -184,10 +193,12 @@ export const TokenDeposit = ({
)
: getNumTokens(ownVoterWeight, ownCouncilTokenRecord, mint, realmInfo)
const max: BigNumber =
const max: BigNumber | undefined =
councilMint && tokenRole === GoverningTokenRole.Council
? getMintDecimalAmount(councilMint, councilMint.supply)
: getMintDecimalAmount(mint, mint.supply)
: mint
? getMintDecimalAmount(mint, mint.supply)
: undefined
const depositTokenRecord =
tokenRole === GoverningTokenRole.Community
@ -248,9 +259,6 @@ export const TokenDeposit = ({
sendingMessage: 'Depositing tokens',
successMessage: 'Tokens have been deposited',
})
await fetchWalletTokenAccounts()
await fetchRealm(realmInfo!.programId, realmInfo!.realmId)
}
const depositAllTokens = async () =>
@ -267,17 +275,31 @@ export const TokenDeposit = ({
)
for (const voteRecord of Object.values(voteRecords)) {
let proposal = proposals[voteRecord.account.proposal.toBase58()]
const proposalQuery = await queryClient.fetchQuery({
queryKey: proposalQueryKeys.byPubkey(
connection.rpcEndpoint,
voteRecord.account.proposal
),
staleTime: 0,
queryFn: () =>
asFindable(() =>
getProposal(connection, voteRecord.account.proposal)
)(),
})
const proposal = proposalQuery.result
if (!proposal) {
continue
}
if (proposal.account.state === ProposalState.Voting) {
// If the Proposal is in Voting state refetch it to make sure we have the latest state to avoid false positives
proposal = await getProposal(connection, proposal.pubkey)
if (proposal.account.state === ProposalState.Voting) {
const governance =
governances[proposal.account.governance.toBase58()]
const governance = (
await fetchGovernanceByPubkey(
connection,
proposal.account.governance
)
).result
if (!governance) throw new Error('failed to fetch governance')
if (proposal.account.getTimeToVoteEnd(governance.account) > 0) {
// Note: It's technically possible to withdraw the vote here but I think it would be confusing and people would end up unconsciously withdrawing their votes
notify({
@ -379,8 +401,6 @@ export const TokenDeposit = ({
: `Released tokens (${index}/${ixChunks.length - 2})`,
})
}
await fetchWalletTokenAccounts()
await fetchRealm(realmInfo!.programId, realmInfo!.realmId)
} catch (ex) {
//TODO change to more friendly notification
notify({ type: 'error', message: `${ex}` })
@ -422,13 +442,11 @@ export const TokenDeposit = ({
)
: '0'
// eslint-disable-next-line react-hooks/rules-of-hooks -- TODO this is potentially quite serious! please fix next time the file is edited, -@asktree
useEffect(() => {
if (availableTokens != '0' || hasTokensDeposited || hasTokensInWallet) {
if (setHasGovPower) setHasGovPower(true)
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO please fix, it can cause difficult bugs. You might wanna check out https://bobbyhadz.com/blog/react-hooks-exhaustive-deps for info. -@asktree
}, [availableTokens, hasTokensDeposited, hasTokensInWallet])
}, [availableTokens, hasTokensDeposited, hasTokensInWallet, setHasGovPower])
const canShowAvailableTokensMessage = hasTokensInWallet && connected
const tokensToShow =
@ -439,11 +457,16 @@ export const TokenDeposit = ({
: 0
const isVsr =
config?.account.communityTokenConfig.voterWeightAddin &&
vsrPluginsPks.includes(
VSR_PLUGIN_PKS.includes(
config?.account.communityTokenConfig.voterWeightAddin.toBase58()
) &&
tokenRole === GoverningTokenRole.Community
// Do not show deposits for mints with zero supply because nobody can deposit anyway
if (!mint || mint.supply.isZero()) {
return null
}
return (
<TokenDepositWrapper inAccountDetails={inAccountDetails}>
{inAccountDetails && (

View File

@ -5,15 +5,20 @@ import dynamic from 'next/dynamic'
import { ChevronRightIcon } from '@heroicons/react/solid'
import useQueryContext from '@hooks/useQueryContext'
import {
gatewayPluginsPks,
nftPluginsPks,
switchboardPluginsPks,
} from '@hooks/useVotingPlugins'
GATEWAY_PLUGINS_PKS,
NFT_PLUGINS_PKS,
SWITCHBOARD_PLUGINS_PKS,
} from '@constants/plugins'
import GatewayCard from '@components/Gateway/GatewayCard'
import ClaimUnreleasedNFTs from './ClaimUnreleasedNFTs'
import Link from 'next/link'
import { useAddressQuery_CommunityTokenOwner } from '@hooks/queries/addresses/tokenOwner'
import { useAddressQuery_CommunityTokenOwner } from '@hooks/queries/addresses/tokenOwnerRecord'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import {
useUserCommunityTokenOwnerRecord,
useUserCouncilTokenOwnerRecord,
} from '@hooks/queries/tokenOwnerRecord'
import { useRealmConfigQuery } from '@hooks/queries/realmConfig'
import ClaimUnreleasedPositions from 'HeliumVotePlugin/components/ClaimUnreleasedPositions'
const LockPluginTokenBalanceCard = dynamic(
@ -67,6 +72,98 @@ const GovernancePowerTitle = () => {
)
}
const TokenBalanceCardInner = ({
proposal,
inAccountDetails,
}: {
proposal?: Option<Proposal>
inAccountDetails?: boolean
}) => {
const ownTokenRecord = useUserCommunityTokenOwnerRecord().data?.result
const ownCouncilTokenRecord = useUserCouncilTokenOwnerRecord().data?.result
const config = useRealmConfigQuery().data?.result
const { councilTokenAccount, vsrMode } = useRealm()
const currentPluginPk = config?.account?.communityTokenConfig.voterWeightAddin
const isNftMode =
currentPluginPk && NFT_PLUGINS_PKS.includes(currentPluginPk?.toBase58())
const isGatewayMode =
currentPluginPk && GATEWAY_PLUGINS_PKS.includes(currentPluginPk?.toBase58())
const isSwitchboardMode =
currentPluginPk &&
SWITCHBOARD_PLUGINS_PKS.includes(currentPluginPk?.toBase58())
if (
vsrMode === 'default' &&
(!ownTokenRecord ||
ownTokenRecord.account.governingTokenDepositAmount.isZero())
) {
return <LockPluginTokenBalanceCard inAccountDetails={inAccountDetails} />
}
if (
vsrMode === 'helium' &&
(!ownTokenRecord ||
ownTokenRecord.account.governingTokenDepositAmount.isZero())
) {
return (
<>
{!inAccountDetails && <GovernancePowerTitle />}
<HeliumVotingPowerCard inAccountDetails={inAccountDetails} />
<ClaimUnreleasedPositions inAccountDetails={inAccountDetails} />
</>
)
}
if (
isNftMode &&
(!ownTokenRecord ||
ownTokenRecord.account.governingTokenDepositAmount.isZero())
) {
return (
<>
{(ownCouncilTokenRecord &&
!ownCouncilTokenRecord?.account.governingTokenDepositAmount.isZero()) ||
(councilTokenAccount &&
!councilTokenAccount?.account.amount.isZero()) ? (
<>
{!inAccountDetails && <GovernancePowerTitle />}
<NftVotingPower inAccountDetails={inAccountDetails} />
<TokenBalanceCard
proposal={proposal}
inAccountDetails={inAccountDetails}
/>
<ClaimUnreleasedNFTs inAccountDetails={inAccountDetails} />
</>
) : (
<>
{!inAccountDetails && <GovernancePowerTitle />}
<NftVotingPower inAccountDetails={inAccountDetails} />
<ClaimUnreleasedNFTs inAccountDetails={inAccountDetails} />
</>
)}
</>
)
}
if (
isSwitchboardMode &&
(!ownTokenRecord ||
ownTokenRecord.account.governingTokenDepositAmount.isZero())
) {
return <SwitchboardPermissionCard></SwitchboardPermissionCard>
}
//Default
return (
<>
{!inAccountDetails && <GovernancePowerTitle />}
<TokenBalanceCard proposal={proposal} inAccountDetails={inAccountDetails}>
{/*Add the gateway card if this is a gated DAO*/}
{isGatewayMode && <GatewayCard></GatewayCard>}
</TokenBalanceCard>
</>
)
}
const TokenBalanceCardWrapper = ({
proposal,
inAccountDetails,
@ -74,101 +171,14 @@ const TokenBalanceCardWrapper = ({
proposal?: Option<Proposal>
inAccountDetails?: boolean
}) => {
const {
ownTokenRecord,
config,
ownCouncilTokenRecord,
councilTokenAccount,
vsrMode,
} = useRealm()
const currentPluginPk = config?.account?.communityTokenConfig.voterWeightAddin
const getTokenBalanceCard = () => {
const isNftMode =
currentPluginPk && nftPluginsPks.includes(currentPluginPk?.toBase58())
const isGatewayMode =
currentPluginPk && gatewayPluginsPks.includes(currentPluginPk?.toBase58())
const isSwitchboardMode =
currentPluginPk &&
switchboardPluginsPks.includes(currentPluginPk?.toBase58())
if (
vsrMode === 'default' &&
(!ownTokenRecord ||
ownTokenRecord.account.governingTokenDepositAmount.isZero())
) {
return <LockPluginTokenBalanceCard inAccountDetails={inAccountDetails} />
}
if (
vsrMode === 'helium' &&
(!ownTokenRecord ||
ownTokenRecord.account.governingTokenDepositAmount.isZero())
) {
return (
<>
{!inAccountDetails && <GovernancePowerTitle />}
<HeliumVotingPowerCard inAccountDetails={inAccountDetails} />
<ClaimUnreleasedPositions inAccountDetails={inAccountDetails} />
</>
)
}
if (
isNftMode &&
(!ownTokenRecord ||
ownTokenRecord.account.governingTokenDepositAmount.isZero())
) {
return (
<>
{(ownCouncilTokenRecord &&
!ownCouncilTokenRecord?.account.governingTokenDepositAmount.isZero()) ||
(councilTokenAccount &&
!councilTokenAccount?.account.amount.isZero()) ? (
<>
{!inAccountDetails && <GovernancePowerTitle />}
<NftVotingPower inAccountDetails={inAccountDetails} />
<TokenBalanceCard
proposal={proposal}
inAccountDetails={inAccountDetails}
/>
<ClaimUnreleasedNFTs inAccountDetails={inAccountDetails} />
</>
) : (
<>
{!inAccountDetails && <GovernancePowerTitle />}
<NftVotingPower inAccountDetails={inAccountDetails} />
<ClaimUnreleasedNFTs inAccountDetails={inAccountDetails} />
</>
)}
</>
)
}
if (
isSwitchboardMode &&
(!ownTokenRecord ||
ownTokenRecord.account.governingTokenDepositAmount.isZero())
) {
return <SwitchboardPermissionCard></SwitchboardPermissionCard>
}
//Default
return (
<>
{!inAccountDetails && <GovernancePowerTitle />}
<TokenBalanceCard
proposal={proposal}
inAccountDetails={inAccountDetails}
>
{/*Add the gateway card if this is a gated DAO*/}
{isGatewayMode && <GatewayCard></GatewayCard>}
</TokenBalanceCard>
</>
)
}
return (
<div
className={`rounded-lg bg-bkg-2 ${inAccountDetails ? `` : `p-4 md:p-6`}`}
>
{getTokenBalanceCard()}
<TokenBalanceCardInner
proposal={proposal}
inAccountDetails={inAccountDetails}
/>
</div>
)
}

View File

@ -1,10 +1,10 @@
import { ExternalLinkIcon } from '@heroicons/react/outline'
import useTransactionsStore from 'stores/useTransactionStore'
import useWalletStore from 'stores/useWalletStore'
import Button from './Button'
import { getExplorerUrl } from './explorer/tools'
import Loading from './Loading'
import Modal from './Modal'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
const TransactionLoader = () => {
const {
@ -17,7 +17,7 @@ const TransactionLoader = () => {
hasErrors,
closeTransactionProcess,
} = useTransactionsStore()
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const currentlyProcessing = processedTransactions + 1
return isProcessing ? (
<Modal

View File

@ -1,10 +1,10 @@
import { PublicKey } from '@solana/web3.js'
import { abbreviateAddress } from '@utils/formatting'
import useWalletStore from '../../stores/useWalletStore'
import useTreasuryAccountStore from 'stores/useTreasuryAccountStore'
import { AssetAccount } from '@utils/uiTypes/assets'
import tokenPriceService from '@utils/services/tokenPrice'
import { WSOL_MINT } from '@components/instructions/tools'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
const AccountItemNFT = ({
governedAccountTokenAccount,
@ -17,7 +17,7 @@ const AccountItemNFT = ({
onClick?: () => void
border?: boolean
}) => {
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const nftsPerPubkey = useTreasuryAccountStore((s) => s.governanceNfts)
const { setCurrentAccount } = useTreasuryAccountStore()

View File

@ -11,7 +11,6 @@ import BN from 'bn.js'
import { useRouter } from 'next/router'
import React, { useEffect, useState } from 'react'
import useTreasuryAccountStore from 'stores/useTreasuryAccountStore'
import useWalletStore from 'stores/useWalletStore'
import AccountHeader from './AccountHeader'
import DepositNFT from './DepositNFT'
import SendTokens from './SendTokens'
@ -40,6 +39,11 @@ import tokenPriceService from '@utils/services/tokenPrice'
import { EVERLEND } from '../../Strategies/protocols/everlend/tools'
import { findAssociatedTokenAccount } from '@everlend/common'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import {
useUserCommunityTokenOwnerRecord,
useUserCouncilTokenOwnerRecord,
} from '@hooks/queries/tokenOwnerRecord'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
type InvestmentType = TreasuryStrategy & {
investedAmount: number
@ -47,7 +51,9 @@ type InvestmentType = TreasuryStrategy & {
const AccountOverview = () => {
const router = useRouter()
const { ownTokenRecord, ownCouncilTokenRecord } = useRealm()
const ownTokenRecord = useUserCommunityTokenOwnerRecord().data?.result
const ownCouncilTokenRecord = useUserCouncilTokenOwnerRecord().data?.result
const {
governedTokenAccounts,
auxiliaryTokenAccounts,
@ -68,7 +74,7 @@ const AccountOverview = () => {
const { canUseTransferInstruction } = useGovernanceAssets()
const wallet = useWalletOnePointOh()
const connected = !!wallet?.connected
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const recentActivity = useTreasuryAccountStore((s) => s.recentActivity)
const isLoadingRecentActivity = useTreasuryAccountStore(
(s) => s.isLoadingRecentActivity

View File

@ -16,31 +16,28 @@ import useRealm from '@hooks/useRealm'
import VoteBySwitch from 'pages/dao/[symbol]/proposal/components/VoteBySwitch'
import Button from '@components/Button'
import Tooltip from '@components/Tooltip'
import useWalletStore from 'stores/useWalletStore'
import { getStakeSchema } from '@utils/validations'
import { getConvertToMsolInstruction } from '@utils/instructionTools'
import {
getInstructionDataFromBase64,
Governance,
ProgramAccount,
} from '@solana/spl-governance'
import { getInstructionDataFromBase64 } from '@solana/spl-governance'
import useQueryContext from '@hooks/useQueryContext'
import { useRouter } from 'next/router'
import { notify } from '@utils/notifications'
import useCreateProposal from '@hooks/useCreateProposal'
import { AssetAccount } from '@utils/uiTypes/assets'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useRealmQuery } from '@hooks/queries/realm'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
const ConvertToMsol = () => {
const { canChooseWhoVote, realm, symbol } = useRealm()
const realm = useRealmQuery().data?.result
const { canChooseWhoVote, symbol } = useRealm()
const { canUseTransferInstruction } = useGovernanceAssets()
const { governedTokenAccounts } = useGovernanceAssets()
const { fmtUrlWithCluster } = useQueryContext()
const router = useRouter()
const { handleCreateProposal } = useCreateProposal()
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const wallet = useWalletOnePointOh()
const { fetchRealmGovernance } = useWalletStore((s) => s.actions)
const currentAccount = useTreasuryAccountStore((s) => s.currentAccount)
const notConnectedMessage =
'You need to be connected to your wallet to have the ability to create a staking proposal'
@ -76,6 +73,8 @@ const ConvertToMsol = () => {
}
const handlePropose = async () => {
if (currentAccount?.governance === undefined) throw new Error()
setIsLoading(true)
const instruction: UiInstruction = await getConvertToMsolInstruction({
schema,
@ -103,15 +102,10 @@ const ConvertToMsol = () => {
}
try {
// Fetch governance to get up to date proposalCount
const selectedGovernance = (await fetchRealmGovernance(
currentAccount?.governance?.pubkey
)) as ProgramAccount<Governance>
const proposalAddress = await handleCreateProposal({
title: form.title ? form.title : proposalTitle,
description: form.description ? form.description : '',
governance: selectedGovernance,
governance: currentAccount?.governance,
instructionsData: [instructionData],
voteByCouncil,
isDraft: false,

View File

@ -16,14 +16,9 @@ import useRealm from '@hooks/useRealm'
import VoteBySwitch from 'pages/dao/[symbol]/proposal/components/VoteBySwitch'
import Button from '@components/Button'
import Tooltip from '@components/Tooltip'
import useWalletStore from 'stores/useWalletStore'
import { getStakeSchema } from '@utils/validations'
import { getConvertToStSolInstruction } from '@utils/instructionTools'
import {
getInstructionDataFromBase64,
Governance,
ProgramAccount,
} from '@solana/spl-governance'
import { getInstructionDataFromBase64 } from '@solana/spl-governance'
import useQueryContext from '@hooks/useQueryContext'
import { useRouter } from 'next/router'
import { notify } from '@utils/notifications'
@ -31,6 +26,8 @@ import useCreateProposal from '@hooks/useCreateProposal'
import { AssetAccount } from '@utils/uiTypes/assets'
import { PublicKey } from '@solana/web3.js'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useRealmQuery } from '@hooks/queries/realm'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
const defaultFormState = {
destinationAccount: undefined,
@ -56,16 +53,16 @@ export const LIDO_PROGRAM_ID_DEVNET =
'CbxVmURN74QZGuFj6qKjM8VDM8b8KKZrbPFLM2CC2hC8'
const ConvertToStSol = () => {
const { canChooseWhoVote, realm, symbol } = useRealm()
const realm = useRealmQuery().data?.result
const { canChooseWhoVote, symbol } = useRealm()
const { canUseTransferInstruction } = useGovernanceAssets()
const { governedTokenAccounts } = useGovernanceAssets()
const { fmtUrlWithCluster } = useQueryContext()
const router = useRouter()
const { handleCreateProposal } = useCreateProposal()
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const wallet = useWalletOnePointOh()
const { fetchRealmGovernance } = useWalletStore((s) => s.actions)
const currentAccount = useTreasuryAccountStore((s) => s.currentAccount)
const [formErrors, setFormErrors] = useState({})
@ -131,15 +128,10 @@ const ConvertToStSol = () => {
}
try {
// Fetch governance to get up to date proposalCount
const selectedGovernance = (await fetchRealmGovernance(
currentAccount?.governance?.pubkey
)) as ProgramAccount<Governance>
const proposalAddress = await handleCreateProposal({
title: form.title ? form.title : getProposalText(form.amount),
description: form.description ? form.description : '',
governance: selectedGovernance,
governance: currentAccount!.governance!,
instructionsData: [instructionData],
voteByCouncil,
isDraft: false,

View File

@ -1,5 +1,4 @@
import { useState } from 'react'
import useWalletStore from 'stores/useWalletStore'
import {
Keypair,
PublicKey,
@ -10,12 +9,13 @@ import Button from '@components/Button'
import { createATA } from '@utils/ataTools'
import { tryGetAta } from '@utils/validations'
import { sendTransaction } from '@utils/send'
import useRealm from '@hooks/useRealm'
import useGovernanceAssetsStore from 'stores/useGovernanceAssetsStore'
import * as serum from '@project-serum/common'
import TokenMintInput from '@components/inputs/TokenMintInput'
import { TokenInfoWithoutDecimals } from '@utils/services/tokenPrice'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useRealmQuery } from '@hooks/queries/realm'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
const CreateAta = ({
owner,
@ -26,11 +26,11 @@ const CreateAta = ({
governancePk: PublicKey
createCallback: () => void
}) => {
const { realm } = useRealm()
const realm = useRealmQuery().data?.result
const refetchGovernanceAccounts = useGovernanceAssetsStore(
(s) => s.refetchGovernanceAccounts
)
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const wallet = useWalletOnePointOh()
const [isLoading, setIsLoading] = useState(false)
const [validatedTypedMint, setValidatedTypedMint] = useState<
@ -40,6 +40,7 @@ const CreateAta = ({
TokenInfoWithoutDecimals | undefined
>()
const handleCreate = async () => {
if (!realm) throw new Error()
const mintPk = validatedTypedMint
? new PublicKey(validatedTypedMint)
: new PublicKey(foundByNameToken!.address)
@ -57,7 +58,7 @@ const CreateAta = ({
wallet,
mintPk,
owner,
wallet!.publicKey!
wallet.publicKey!
)
} else {
const instructions: TransactionInstruction[] = []
@ -82,12 +83,12 @@ const CreateAta = ({
await sendTransaction({
transaction,
wallet: wallet!,
connection: connection.current!,
wallet: wallet,
connection: connection.current,
signers,
})
}
await refetchGovernanceAccounts(connection, realm!, governancePk)
await refetchGovernanceAccounts(connection, realm, governancePk)
setIsLoading(false)
createCallback()
}

View File

@ -1,5 +1,4 @@
import React, { useState } from 'react'
import useWalletStore from 'stores/useWalletStore'
import Button, { SecondaryButton } from '@components/Button'
import Tooltip from '@components/Tooltip'
import DepositNFTFromWallet from './DepositNFTFromWallet'
@ -8,6 +7,7 @@ import useTreasuryAccountStore from 'stores/useTreasuryAccountStore'
import { ArrowLeftIcon, ExternalLinkIcon } from '@heroicons/react/solid'
import { getExplorerUrl } from '@components/explorer/tools'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
enum DepositState {
DepositNFTFromWallet,
@ -16,7 +16,7 @@ enum DepositState {
const DepositNFT = ({ onClose }) => {
const currentAccount = useTreasuryAccountStore((s) => s.currentAccount)
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const wallet = useWalletOnePointOh()
const connected = !!wallet?.connected
const [

View File

@ -1,9 +1,8 @@
import React, { useEffect, useState } from 'react'
import { useEffect, useState } from 'react'
import useTreasuryAccountStore from 'stores/useTreasuryAccountStore'
import Input from '@components/inputs/Input'
import { tryParseKey } from '@tools/validators/pubkey'
import { debounce } from '@utils/debounce'
import useWalletStore from 'stores/useWalletStore'
import axios from 'axios'
import { notify } from '@utils/notifications'
import Loading from '@components/Loading'
@ -16,7 +15,6 @@ import {
} from '@solana/spl-token'
import Tooltip from '@components/Tooltip'
import { tryGetAta } from '@utils/validations'
import useRealm from '@hooks/useRealm'
import { createATA } from '@utils/ataTools'
import { abbreviateAddress } from '@utils/formatting'
import { DuplicateIcon, ExclamationIcon } from '@heroicons/react/outline'
@ -32,11 +30,13 @@ import {
SftWithToken,
} from '@metaplex-foundation/js/dist/types/plugins/nftModule/models'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useRealmQuery } from '@hooks/queries/realm'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
const DepositNFTAddress = ({ additionalBtns }: { additionalBtns?: any }) => {
const currentAccount = useTreasuryAccountStore((s) => s.currentAccount)
const wallet = useWalletOnePointOh()
const { realm } = useRealm()
const realm = useRealmQuery().data?.result
const connected = !!wallet?.connected
const [form, setForm] = useState({
mint: '',
@ -51,7 +51,7 @@ const DepositNFTAddress = ({ additionalBtns }: { additionalBtns?: any }) => {
const [ataAddress, setAtaAddress] = useState('')
const { nftsGovernedTokenAccounts } = useGovernanceAssets()
const { setCurrentAccount } = useTreasuryAccountStore()
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const handleSetForm = ({ propertyName, value }) => {
setFormErrors({})
setForm({ ...form, [propertyName]: value })

View File

@ -1,6 +1,5 @@
import { useEffect, useRef, useState } from 'react'
import useTreasuryAccountStore from 'stores/useTreasuryAccountStore'
import useWalletStore from 'stores/useWalletStore'
import Button from '@components/Button'
import Tooltip from '@components/Tooltip'
import { NFTWithMint } from '@utils/uiTypes/nfts'
@ -19,10 +18,11 @@ import { createATA } from '@utils/ataTools'
import { createIx_transferNft } from '@utils/metaplex'
import { SequenceType, sendTransactionsV3 } from '@utils/sendTransactions'
import { getNativeTreasuryAddress } from '@solana/spl-governance'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
const useMetaplexDeposit = () => {
const wallet = useWalletOnePointOh()
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const currentAccount = useTreasuryAccountStore((s) => s.currentAccount)
return async (address: PublicKey) => {
@ -65,7 +65,7 @@ const DepositNFTFromWallet = ({ additionalBtns }: { additionalBtns?: any }) => {
const [selectedNfts, setSelectedNfts] = useState<NFTWithMint[]>([])
const wallet = useWalletOnePointOh()
const connected = !!wallet?.connected
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const [isLoading, setIsLoading] = useState(false)
const [sendingSuccess, setSendingSuccess] = useState(false)
const { nftsGovernedTokenAccounts } = useGovernanceAssets()

View File

@ -19,7 +19,6 @@ import {
} from '@utils/uiTypes/proposalCreationTypes'
import { useEffect, useState } from 'react'
import useTreasuryAccountStore from 'stores/useTreasuryAccountStore'
import useWalletStore from 'stores/useWalletStore'
import { getTokenTransferSchema } from '@utils/validations'
import {
@ -31,8 +30,6 @@ import tokenPriceService from '@utils/services/tokenPrice'
import BigNumber from 'bignumber.js'
import { getInstructionDataFromBase64 } from '@solana/spl-governance'
import useQueryContext from '@hooks/useQueryContext'
import { Governance } from '@solana/spl-governance'
import { ProgramAccount } from '@solana/spl-governance'
import { useRouter } from 'next/router'
import { notify } from '@utils/notifications'
import Textarea from '@components/inputs/Textarea'
@ -52,6 +49,8 @@ import { NFTWithMint } from '@utils/uiTypes/nfts'
import useCreateProposal from '@hooks/useCreateProposal'
import NFTAccountSelect from './NFTAccountSelect'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useRealmQuery } from '@hooks/queries/realm'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
const SendTokens = ({
isNft = false,
@ -61,10 +60,11 @@ const SendTokens = ({
selectedNft?: NFTWithMint | null
}) => {
const currentAccount = useTreasuryAccountStore((s) => s.currentAccount)
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const { nftsGovernedTokenAccounts } = useGovernanceAssets()
const { setCurrentAccount } = useTreasuryAccountStore()
const { realmInfo, symbol, realm, canChooseWhoVote } = useRealm()
const realm = useRealmQuery().data?.result
const { realmInfo, symbol, canChooseWhoVote } = useRealm()
const { handleCreateProposal } = useCreateProposal()
const { canUseTransferInstruction } = useGovernanceAssets()
const tokenInfo = useTreasuryAccountStore((s) => s.tokenInfo)
@ -73,7 +73,6 @@ const SendTokens = ({
const { fmtUrlWithCluster } = useQueryContext()
const wallet = useWalletOnePointOh()
const router = useRouter()
const { fetchRealmGovernance } = useWalletStore((s) => s.actions)
const programId: PublicKey | undefined = realmInfo?.programId
const [form, setForm] = useState<SendTokenCompactViewForm>({
destinationAccount: '',
@ -190,10 +189,6 @@ const SendTokens = ({
? abbreviateAddress(new PublicKey(form.destinationAccount))
: ''
}`
// Fetch governance to get up to date proposalCount
const selectedGovernance = (await fetchRealmGovernance(
governance?.pubkey
)) as ProgramAccount<Governance>
try {
const proposalAddress = await handleCreateProposal({
@ -201,7 +196,7 @@ const SendTokens = ({
description: form.description ? form.description : '',
voteByCouncil,
instructionsData,
governance: selectedGovernance!,
governance,
})
const url = fmtUrlWithCluster(
`/dao/${symbol}/proposal/${proposalAddress}`
@ -250,16 +245,12 @@ const SendTokens = ({
prerequisiteInstructions: instruction.prerequisiteInstructions || [],
}
try {
// Fetch governance to get up to date proposalCount
const selectedGovernance = (await fetchRealmGovernance(
governance?.pubkey
)) as ProgramAccount<Governance>
proposalAddress = await handleCreateProposal({
title: form.title ? form.title : proposalTitle,
description: form.description ? form.description : '',
voteByCouncil,
instructionsData: [instructionData],
governance: selectedGovernance!,
governance: governance!,
})
const url = fmtUrlWithCluster(
`/dao/${symbol}/proposal/${proposalAddress}`

View File

@ -10,7 +10,6 @@ import tokenPriceService from '@utils/services/tokenPrice'
import React, { useCallback, useState } from 'react'
import useTreasuryAccountStore from 'stores/useTreasuryAccountStore'
import AccountLabel from './BaseAccountHeader'
import useWalletStore from 'stores/useWalletStore'
import {
ArrowCircleDownIcon,
ArrowCircleUpIcon,
@ -26,8 +25,6 @@ import { getValidatedPublickKey } from '@utils/validations'
import { validateInstruction } from '@utils/instructionTools'
import {
getInstructionDataFromBase64,
Governance,
ProgramAccount,
serializeInstructionToBase64,
} from '@solana/spl-governance'
import { notify } from '@utils/notifications'
@ -53,6 +50,7 @@ import {
} from '@utils/instructions/PsyFinance/PoseidonIdl'
import { deriveAllBoundedStrategyKeysV2 } from '@utils/instructions/PsyFinance/poseidon'
import { TokenInfo } from '@utils/services/types'
import useLegacyConnectionContext from '@hooks/useLegacyConnectionContext'
export type TradeProps = { tokenAccount: AssetAccount }
@ -171,9 +169,8 @@ const poseidonProgramId = new web3.PublicKey(
const Trade: React.FC<TradeProps> = ({ tokenAccount }) => {
const currentAccount = useTreasuryAccountStore((s) => s.currentAccount)
const router = useRouter()
const connection = useWalletStore((s) => s.connection)
const connection = useLegacyConnectionContext()
const { wallet, anchorProvider } = useWalletDeprecated()
const { fetchRealmGovernance } = useWalletStore((s) => s.actions)
const { handleCreateProposal } = useCreateProposal()
const { canUseTransferInstruction } = useGovernanceAssets()
const { canChooseWhoVote, symbol } = useRealm()
@ -325,15 +322,10 @@ const Trade: React.FC<TradeProps> = ({ tokenAccount }) => {
proposalInstructions.push(instructionData)
try {
// Fetch governance to get up to date proposalCount
const selectedGovernance = (await fetchRealmGovernance(
currentAccount?.governance?.pubkey
)) as ProgramAccount<Governance>
const proposalAddress = await handleCreateProposal({
title: form.title,
description: form.description,
governance: selectedGovernance,
governance: currentAccount.governance,
instructionsData: proposalInstructions,
voteByCouncil,
isDraft: false,

View File

@ -1,7 +1,6 @@
import React, { FunctionComponent, useState } from 'react'
import { BanIcon, ThumbDownIcon, ThumbUpIcon } from '@heroicons/react/solid'
import { VoteKind } from '@solana/spl-governance'
import useWalletStore from '../stores/useWalletStore'
import Button, { SecondaryButton } from './Button'
import Loading from './Loading'
@ -32,8 +31,6 @@ const VoteCommentModal: FunctionComponent<VoteCommentModalProps> = ({
vote,
voterTokenRecord,
}) => {
const { fetchChatMessages } = useWalletStore((s) => s.actions)
const { proposal } = useWalletStore((s) => s.selectedProposal)
const [comment, setComment] = useState('')
const { submitting, submitVote } = useSubmitVote()
@ -46,7 +43,6 @@ const VoteCommentModal: FunctionComponent<VoteCommentModalProps> = ({
comment,
})
onClose()
await fetchChatMessages(proposal!.pubkey)
}
return (

View File

@ -6,7 +6,6 @@ import VoteCommentModal from '../VoteCommentModal'
import {
useIsInCoolOffTime,
useIsVoting,
useProposalVoteRecordQuery,
useVoterTokenRecord,
useVotingPop,
} from './hooks'
@ -14,7 +13,9 @@ import useRealm from '@hooks/useRealm'
import { VotingClientType } from '@utils/uiTypes/VotePlugin'
import useVotePluginsClientStore from 'stores/useVotePluginsClientStore'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useProposalVoteRecordQuery } from '@hooks/queries/voteRecord'
import { useSubmitVote } from '@hooks/useSubmitVote'
import { useSelectedRealmInfo } from '@hooks/selectedRealm/useSelectedRealmRegistryEntry'
const useCanVote = () => {
const client = useVotePluginsClientStore(
@ -61,7 +62,8 @@ const useCanVote = () => {
export const CastVoteButtons = () => {
const [showVoteModal, setShowVoteModal] = useState(false)
const [vote, setVote] = useState<'yes' | 'no' | null>(null)
const { allowDiscussion } = useRealm()
const realmInfo = useSelectedRealmInfo()
const allowDiscussion = realmInfo?.allowDiscussion ?? true
const { submitting, submitVote } = useSubmitVote()
const votingPop = useVotingPop()
const voterTokenRecord = useVoterTokenRecord()

Some files were not shown because too many files have changed in this diff Show More