Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add: multiple council members instruction #30

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions hooks/useGovernanceAssets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,11 @@ export default function useGovernanceAssets() {
isVisible: canUseTokenTransferInstruction,
packageId: PackageEnum.Common,
},
[Instructions.AddCouncilMembers]: {
name: 'Add Council Members',
isVisible: canUseTokenTransferInstruction,
packageId: PackageEnum.Common,
},
[Instructions.TransferDomainName]: {
name: 'SNS Transfer Out Domain Name',
packageId: PackageEnum.Common,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
import React, { useContext, useEffect, useMemo, useState } from 'react'
import Input from '@components/inputs/Input'
import useRealm from '@hooks/useRealm'
import { PublicKey, TransactionInstruction } from '@solana/web3.js'
import {
AddCouncilMembersForm,
UiInstruction,
} from '@utils/uiTypes/proposalCreationTypes'
import { NewProposalContext } from '../../new'
import { getAddCouncilMembersSchema } from '@utils/validations'
import useGovernanceAssets from '@hooks/useGovernanceAssets'
import { serializeInstructionToBase64 } from '@solana/spl-governance'
import {validateInstruction} from '@utils/instructionTools'
import TextareaProps from '@components/inputs/Textarea'
import {withDepositGoverningTokens} from "@realms-today/spl-governance"
import { BN } from 'bn.js'
import useGoverningTokenMint from '@hooks/selectedRealm/useGoverningTokenMint'
import GovernedAccountSelect from '../GovernedAccountSelect'
import { useLegacyVoterWeight } from '@hooks/queries/governancePower'

const AddCouncilMembers = ({
index,
}: {
index: number
}) => {
const { realmInfo } = useRealm()
const communityMint = useGoverningTokenMint("community")
const { result: ownVoterWeight } = useLegacyVoterWeight()
const {assetAccounts} = useGovernanceAssets()

const mintAssetAccount = useMemo(() => (
communityMint ?
assetAccounts.find(account => account.pubkey.equals(communityMint)) :
undefined
), [assetAccounts, communityMint])

const [form, setForm] = useState<AddCouncilMembersForm>({
governedTokenAccount: undefined,
amount: undefined,
memberAddresses: [],
mintInfo: undefined
})
const [formErrors, setFormErrors] = useState({})

const { handleSetInstructions } = useContext(NewProposalContext)

const handleSetForm = ({ propertyName, value }) => {
setFormErrors({})
setForm({ ...form, [propertyName]: value })
}
const setMintInfo = (value) => {
setForm({ ...form, mintInfo: value })
}
const setAmount = (event) => {
const value = event.target.value
handleSetForm({
value: value,
propertyName: 'amount',
})
}

function handleAddressChange(value: string) {
const addresses = value.split(",").map(a => a.trim())
handleSetForm({
value: addresses,
propertyName: 'memberAddresses'
})
}

async function getInstruction(): Promise<UiInstruction> {
const isValid = await validateInstruction({ schema, form, setFormErrors })

let serializedInstruction = ''
const additionalInstructions: string[] = []

if (form.amount && isValid && realmInfo && form.mintInfo && mintAssetAccount) {
for (const member of form.memberAddresses) {
const instructions: TransactionInstruction[] = []
const amount = new BN(form.amount).mul(new BN(10**form.mintInfo.decimals))

await withDepositGoverningTokens(
instructions,
realmInfo.programId,
realmInfo.programVersion,
realmInfo.realmId,
mintAssetAccount.pubkey,
mintAssetAccount.pubkey,
new PublicKey(member),
form.mintInfo.mintAuthority!,
new PublicKey(member),
amount
)

if (serializedInstruction) {
additionalInstructions.push(serializeInstructionToBase64(instructions[0]))
} else {
serializedInstruction = serializeInstructionToBase64(instructions[0])
}
}
}

const obj = {
serializedInstruction,
additionalSerializedInstructions: additionalInstructions.length ? additionalInstructions : undefined,
isValid,
governance: form.governedTokenAccount?.governance,
chunkBy: 1
}

return obj
}

useEffect(() => {
handleSetInstructions(
{ governedAccount: form.governedTokenAccount?.governance, getInstruction },
index
)
}, [form])

useEffect(() => {
setMintInfo(mintAssetAccount?.extensions.mint?.account)
}, [mintAssetAccount])

const schema = getAddCouncilMembersSchema()

return (
<>
<GovernedAccountSelect
label="Select Governance"
governedAccounts={assetAccounts.filter((x) =>
ownVoterWeight?.canCreateProposal(x.governance.account.config)
)}
onChange={(value) => {
handleSetForm({ value, propertyName: 'governedTokenAccount' })
}}
value={form.governedTokenAccount}
error={formErrors['governedTokenAccount']}
></GovernedAccountSelect>
<TextareaProps
label="Member Addresses (separated by a comma)"
value={form.memberAddresses}
type="textarea"
onChange={(evt) => handleAddressChange(evt.target.value)}
error={formErrors['memberAddresses']}
className='h-28'
/>

<Input
min={0}
label="Amount of Tokens to each member"
value={form.amount}
type="number"
onChange={setAmount}
error={formErrors['amount']}
/>
</>
)
}

export default AddCouncilMembers
2 changes: 2 additions & 0 deletions pages/dao/[symbol]/proposal/new.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ import SymmetryEditBasket from './components/instructions/Symmetry/SymmetryEditB
import SymmetryDeposit from './components/instructions/Symmetry/SymmetryDeposit'
import SymmetryWithdraw from './components/instructions/Symmetry/SymmetryWithdraw'
import PythUpdatePoolAuthority from './components/instructions/Pyth/PythUpdatePoolAuthority'
import AddCouncilMembers from './components/instructions/AddCouncilMembers'

const TITLE_LENGTH_LIMIT = 130
// the true length limit is either at the tx size level, and maybe also the total account size level (I can't remember)
Expand Down Expand Up @@ -469,6 +470,7 @@ const New = () => {
| null
} = useMemo(
() => ({
[Instructions.AddCouncilMembers]: AddCouncilMembers,
[Instructions.Burn]: BurnTokens,
[Instructions.Transfer]: SplTokenTransfer,
[Instructions.ProgramUpgrade]: ProgramUpgrade,
Expand Down
8 changes: 8 additions & 0 deletions utils/uiTypes/proposalCreationTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,13 @@ export interface SplTokenTransferForm {
mintInfo: MintInfo | undefined
}

export interface AddCouncilMembersForm {
governedTokenAccount: AssetAccount | undefined,
memberAddresses: string[],
amount: number | undefined,
mintInfo: MintInfo | undefined
}

export interface BurnTokensForm {
amount: number | undefined
governedTokenAccount: AssetAccount | undefined
Expand Down Expand Up @@ -295,6 +302,7 @@ export interface JoinDAOForm {
}

export enum Instructions {
AddCouncilMembers,
Base64,
Burn,
ChangeMakeDonation,
Expand Down
48 changes: 48 additions & 0 deletions utils/validations.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -881,6 +881,54 @@ export const getDualFinanceVoteDepositSchema = () => {
})
}

export const getAddCouncilMembersSchema = () => {
return yup.object().shape({
governedTokenAccount: yup.object().required('Source account is required'),
amount: yup.number()
.typeError('Amount is required')
.min(0)
.test(
'amount',
'Amount validation error',
function (val: number) {
if (new BN(val).gt(new BN(0))) {
return true
}
return this.createError({
message: `Amount is required`,
})
}
),
memberAddresses: yup
.array().min(1).of(
yup
.string()
.typeError('Address is required')
.test(
'memberAddresses',
'Account validation error',
function (val: string) {
if (val) {
try {
getValidatedPublickKey(val)
return true
} catch (e) {
console.log(e)
return this.createError({
message: `Invalid Public Key`,
})
}
} else {
return this.createError({
message: `Member addresses are required`,
})
}
}
)
),
})
}

export const getTokenTransferSchema = ({
form,
connection,
Expand Down
Loading