-
Notifications
You must be signed in to change notification settings - Fork 555
/
Copy pathSendNft.tsx
410 lines (386 loc) · 13.5 KB
/
SendNft.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
import Button from '@components/Button'
import Input from '@components/inputs/Input'
import { PublicKey } from '@solana/web3.js'
import { tryParseKey } from '@tools/validators/pubkey'
import { abbreviateAddress } from '@utils/formatting'
import React, { useMemo, useState } from 'react'
import {
ArrowCircleDownIcon,
ArrowCircleUpIcon,
CheckCircleIcon,
PhotographIcon,
// InformationCircleIcon,
} from '@heroicons/react/solid'
import {
getInstructionDataFromBase64,
getNativeTreasuryAddress,
serializeInstructionToBase64,
} from '@solana/spl-governance'
import useQueryContext from '@hooks/useQueryContext'
import { useRouter } from 'next/router'
import { notify } from '@utils/notifications'
import Textarea from '@components/inputs/Textarea'
// import { Popover } from '@headlessui/react'
import Tooltip from '@components/Tooltip'
import useGovernanceAssets from '@hooks/useGovernanceAssets'
import VoteBySwitch from 'pages/dao/[symbol]/proposal/components/VoteBySwitch'
import useCreateProposal from '@hooks/useCreateProposal'
import useWalletOnePointOh from '@hooks/useWalletOnePointOh'
import { useRealmQuery } from '@hooks/queries/realm'
import NFTAccountSelect from './TreasuryAccount/NFTAccountSelect'
import {
ASSOCIATED_TOKEN_PROGRAM_ID,
TOKEN_PROGRAM_ID,
Token,
} from '@solana/spl-token'
import { createIx_transferNft } from '@utils/metaplex'
import {
fetchDigitalAssetById,
useRealmDigitalAssetsQuery,
} from '@hooks/queries/digitalAssets'
import { SetStateAction } from 'react'
import ImgWithLoader from './ImgWithLoader'
import useTreasuryAddressForGovernance from '@hooks/useTreasuryAddressForGovernance'
import Loading from './Loading'
import { fetchGovernanceByPubkey } from '@hooks/queries/governance'
import { useConnection } from '@solana/wallet-adapter-react'
import useGovernanceSelect from '@hooks/useGovernanceSelect'
import { SUPPORT_CNFTS } from '@constants/flags'
import clsx from 'clsx'
import { getNetworkFromEndpoint } from '@utils/connection'
import { buildTransferCnftInstruction } from '@hooks/instructions/useTransferCnftInstruction'
import {useVoteByCouncilToggle} from "@hooks/useVoteByCouncilToggle";
const SendNft = ({
initialNftAndGovernanceSelected,
}: {
initialNftAndGovernanceSelected?:
| [PublicKey, PublicKey]
| [undefined, PublicKey]
}) => {
const { connection } = useConnection()
const realm = useRealmQuery().data?.result
const { propose } = useCreateProposal()
const { canUseTransferInstruction } = useGovernanceAssets()
const { fmtUrlWithCluster } = useQueryContext()
const wallet = useWalletOnePointOh()
const router = useRouter()
const [selectedNfts, setSelectedNfts] = useState<PublicKey[]>(
initialNftAndGovernanceSelected?.[0]
? [initialNftAndGovernanceSelected[0]]
: []
)
const [selectedGovernance, setSelectedGovernance] = useGovernanceSelect(
initialNftAndGovernanceSelected?.[1]
)
const { voteByCouncil, shouldShowVoteByCouncilToggle, setVoteByCouncil } = useVoteByCouncilToggle();
const [showOptions, setShowOptions] = useState(false)
const [destination, setDestination] = useState<string>('')
const [title, setTitle] = useState<string>('')
const [description, setDescription] = useState<string>('')
const [isLoading, setIsLoading] = useState(false)
const [formErrors, setFormErrors] = useState({})
const nftName: string | undefined = undefined
const defaultTitle = `Send ${nftName ? nftName : 'NFT'} to ${
tryParseKey(destination)
? abbreviateAddress(new PublicKey(destination))
: '...'
}`
const walletPk = wallet?.publicKey ?? undefined
const handleProposeNftSend = async () => {
if (!realm || !selectedGovernance) {
throw new Error()
}
if (walletPk === undefined) {
throw 'connect wallet'
}
const toOwner = tryParseKey(destination)
if (toOwner === null)
return setFormErrors({ destination: 'invalid destination' })
setIsLoading(true)
let anyCompressed = false
const instructions = await Promise.all(
selectedNfts.map(async (nftMint) => {
const network = getNetworkFromEndpoint(connection.rpcEndpoint)
if (network === 'localnet') throw new Error()
const nft = (await fetchDigitalAssetById(network, nftMint)).result
if (nft === undefined) throw new Error('nft not found')
if (nft.compression?.compressed) {
anyCompressed = true
const ix = await buildTransferCnftInstruction(
connection,
nftMint,
toOwner
)
return {
serializedInstruction: serializeInstructionToBase64(ix),
isValid: true,
prerequisiteInstructions: [],
}
} else {
const destinationAtaPk = await Token.getAssociatedTokenAddress(
ASSOCIATED_TOKEN_PROGRAM_ID, // always ASSOCIATED_TOKEN_PROGRAM_ID
TOKEN_PROGRAM_ID, // always TOKEN_PROGRAM_ID
nftMint, // mint
toOwner, // owner
true
)
const destinationAtaQueried = await connection.getAccountInfo(
destinationAtaPk
)
// typically this should just be the same as the account that owns the NFT, but sometimes the governance owns it
const nativeTreasury = await getNativeTreasuryAddress(
realm.owner,
selectedGovernance
)
const fromOwnerString = nft.ownership.owner
const fromOwner = tryParseKey(fromOwnerString)
// should be impossible, but stuff isn't typed
if (fromOwner === null) throw new Error()
const transferIx = await createIx_transferNft(
connection,
fromOwner,
toOwner,
nftMint,
fromOwner,
nativeTreasury
)
return {
serializedInstruction: serializeInstructionToBase64(transferIx),
isValid: true,
prerequisiteInstructions:
destinationAtaQueried === null
? [
Token.createAssociatedTokenAccountInstruction(
ASSOCIATED_TOKEN_PROGRAM_ID, // always ASSOCIATED_TOKEN_PROGRAM_ID
TOKEN_PROGRAM_ID, // always TOKEN_PROGRAM_ID
nftMint, // mint
destinationAtaPk, // ata
toOwner, // owner of token account
walletPk // fee payer
),
]
: [],
}
}
})
)
const governanceFetched = await fetchGovernanceByPubkey(
connection,
selectedGovernance
)
if (governanceFetched.result === undefined)
throw new Error('governance not found')
const instructionsData = instructions.map((instruction) => ({
data: getInstructionDataFromBase64(instruction.serializedInstruction),
holdUpTime:
governanceFetched.result.account.config.minInstructionHoldUpTime,
prerequisiteInstructions: instruction.prerequisiteInstructions ?? [],
chunkBy: 1,
}))
try {
const proposalAddress = await propose({
title: title !== '' ? title : defaultTitle,
description,
voteByCouncil,
instructionsData,
governance: selectedGovernance,
utilizeLookupTable: anyCompressed,
})
const url = fmtUrlWithCluster(
`/dao/${router.query.symbol}/proposal/${proposalAddress}`
)
router.push(url)
} catch (ex) {
notify({ type: 'error', message: `${ex}` })
//console.error(ex)
setIsLoading(false)
throw ex
}
setIsLoading(false)
}
return (
<>
<h3 className="mb-4 flex items-center">
<>Send NFT</>
</h3>
{selectedGovernance !== undefined && (
<NFTAccountSelect
onChange={(value) => setSelectedGovernance(value)}
selectedGovernance={selectedGovernance}
/>
)}
<div className="space-y-4 w-full pb-4">
{
// TODO use some kind of good wallet pubkey input
}
<Input
label="Destination account"
value={destination}
type="text"
onChange={(evt) => setDestination(evt.target.value)}
noMaxWidth={true}
error={formErrors['destination']}
/>
{selectedGovernance !== undefined && (
<GovernanceNFTSelector
selectedNfts={selectedNfts}
setSelectedNfts={setSelectedNfts}
governance={selectedGovernance}
/>
)}
<div
className={'flex items-center hover:cursor-pointer w-24'}
onClick={() => setShowOptions(!showOptions)}
>
{showOptions ? (
<ArrowCircleUpIcon className="h-4 w-4 mr-1 text-primary-light" />
) : (
<ArrowCircleDownIcon className="h-4 w-4 mr-1 text-primary-light" />
)}
<small className="text-fgd-3">Options</small>
</div>
{showOptions && (
<>
<Input
noMaxWidth={true}
label="Title"
placeholder={
tryParseKey(destination)
? defaultTitle
: 'Title of your proposal'
}
value={title}
type="text"
onChange={(evt) => setTitle(evt.target.value)}
/>
<Textarea
noMaxWidth={true}
label="Description"
placeholder={
'Description of your proposal or use a github gist link (optional)'
}
wrapperClassName="mb-5"
value={description}
onChange={(evt) => setDescription(evt.target.value)}
></Textarea>
{shouldShowVoteByCouncilToggle && (
<VoteBySwitch
checked={voteByCouncil}
onChange={() => {
setVoteByCouncil(!voteByCouncil)
}}
></VoteBySwitch>
)}
</>
)}
</div>
<div className="flex flex-col sm:flex-row sm:space-x-4 space-y-4 sm:space-y-0 mt-4">
<Button
className="ml-auto"
onClick={handleProposeNftSend}
isLoading={isLoading}
disabled={selectedNfts.length < 1}
>
<Tooltip
content={
!canUseTransferInstruction
? 'You need to have connected wallet with ability to create token transfer proposals'
: !selectedNfts.length
? 'Please select nft'
: ''
}
>
<div>Propose</div>
</Tooltip>
</Button>
</div>
</>
)
}
/** Select NFTs owned by a given governance */
function GovernanceNFTSelector({
governance,
nftWidth = '150px',
nftHeight = '150px',
selectedNfts,
setSelectedNfts,
}: {
governance: PublicKey
selectedNfts: PublicKey[]
setSelectedNfts: React.Dispatch<SetStateAction<PublicKey[]>>
nftWidth?: string
nftHeight?: string
}) {
const { result: treasuryAddress } = useTreasuryAddressForGovernance(
governance
)
// TODO just query by owner (which should be in cache already)
const { data: allNfts, isLoading } = useRealmDigitalAssetsQuery()
const nfts = useMemo(
() =>
allNfts
?.flat()
.filter((x) => SUPPORT_CNFTS || !x.compression.compressed)
.filter(
(x) =>
x.ownership.owner === governance.toString() ||
x.ownership.owner === treasuryAddress?.toString()
),
[allNfts, governance, treasuryAddress]
)
return (
<>
<div className="overflow-y-auto">
{!isLoading ? (
nfts?.length ? (
<div className="flex flex-row flex-wrap gap-4 mb-4">
{nfts.map((nft) => (
<div
onClick={() =>
setSelectedNfts((prev) => {
const alreadyIncluded = prev.find(
(x) => x.toString() === nft.id
)
return alreadyIncluded
? prev.filter((x) => x.toString() !== nft.id)
: [...prev, new PublicKey(nft.id)]
})
}
key={nft.id}
className={clsx(
`bg-bkg-2 flex-shrink-0 flex items-center justify-center cursor-pointer default-transition rounded-lg relative overflow-hidden`,
selectedNfts.find((k) => k.toString() === nft.id)
? 'border-4 border-green'
: 'border border-transparent hover:border-primary-dark '
)}
style={{
width: nftWidth,
height: nftHeight,
}}
>
{selectedNfts.find((k) => k.toString() === nft.id) && (
<CheckCircleIcon className="w-10 h-10 absolute text-green z-10" />
)}
<ImgWithLoader
style={{ width: '150px' }}
src={
nft.content.files[0]?.cdn_uri ?? nft.content.files[0]?.uri
}
/>
</div>
))}
</div>
) : (
<div className="text-fgd-3 flex flex-col items-center">
{"Account doesn't have any NFTs"}
<PhotographIcon className="opacity-5 w-56 h-56" />
</div>
)
) : (
<Loading />
)}
</div>
</>
)
}
export default SendNft