-
Notifications
You must be signed in to change notification settings - Fork 267
Expand file tree
/
Copy pathNFTOfferEditor.tsx
More file actions
736 lines (675 loc) · 25.1 KB
/
Copy pathNFTOfferEditor.tsx
File metadata and controls
736 lines (675 loc) · 25.1 KB
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
import { WalletType } from '@chia-network/api';
import type { NFTInfo } from '@chia-network/api';
import { useCreateOfferForIdsMutation, useGetWalletBalanceQuery } from '@chia-network/api-react';
import {
Amount,
AmountProps,
Back,
Button,
ButtonLoading,
Color,
Fee,
Flex,
Form,
FormatLargeNumber,
StateColor,
TextField,
Tooltip,
TooltipIcon,
catToMojo,
chiaToMojo,
mojoToCAT,
mojoToCATLocaleString,
mojoToChia,
mojoToChiaLocaleString,
useColorModeValue,
useCurrencyCode,
useLocale,
useShowError,
} from '@chia-network/core';
import { Trans, t } from '@lingui/macro';
import { Warning as WarningIcon } from '@mui/icons-material';
import { alpha, Box, Divider, Grid, Tabs, Tab, Typography, useTheme } from '@mui/material';
import BigNumber from 'bignumber.js';
import React, { useMemo, useState } from 'react';
import { useForm, useFormContext } from 'react-hook-form';
import { useNavigate } from 'react-router-dom';
import styled from 'styled-components';
import useNFT from '../../hooks/useNFT';
import useNFTs from '../../hooks/useNFTs';
import useSuppressShareOnCreate from '../../hooks/useSuppressShareOnCreate';
import { convertRoyaltyToPercentage, isValidNFTId, launcherIdFromNFTId } from '../../util/nfts';
import NFTOfferExchangeType from './NFTOfferExchangeType';
import NFTOfferPreview from './NFTOfferPreview';
import NFTOfferTokenSelector from './NFTOfferTokenSelector';
import { calculateNFTRoyalties } from './utils';
/* ========================================================================== */
/* Temporary home for the NFT-specific Offer Editor */
/* An NFT offer consists of a single NFT being offered for XCH/CAT */
/* ========================================================================== */
const StyledWarningIcon = styled(WarningIcon)`
color: ${StateColor.WARNING};
`;
/* ========================================================================== */
type NFTOfferCreationFeeProps = AmountProps & {
disabled?: boolean;
onChange?: (fee: string) => void;
defaultValue?: string;
};
function NFTOfferCreationFee(props: NFTOfferCreationFeeProps) {
const { disabled = true, onChange, defaultValue = '', ...rest } = props;
return (
<Flex flexDirection="column" gap={1}>
<Grid item>
<Flex flexDirection="row" gap={1}>
<Fee
id="fee"
variant="filled"
name="fee"
color="secondary"
disabled={disabled}
onChange={onChange}
defaultValue={defaultValue}
label={<Trans>Fee (Optional)</Trans>}
{...rest}
/>
<Box style={{ position: 'relative', top: '20px' }}>
<TooltipIcon>
<Trans>
Including a fee in the offer can help expedite the transaction when the offer is accepted. The
recommended minimum fee is 0.000005 XCH (5,000,000 mojos)
</Trans>
</TooltipIcon>
</Box>
</Flex>
</Grid>
</Flex>
);
}
/* ========================================================================== */
type NFTOfferConditionalsPanelProps = {
defaultValues: NFTOfferEditorFormData;
isProcessing?: boolean;
};
function NFTOfferConditionalsPanel(props: NFTOfferConditionalsPanelProps) {
const { defaultValues, isProcessing = false } = props;
const disabled = isProcessing;
const methods = useFormContext();
const [locale] = useLocale();
const [amountFocused, setAmountFocused] = useState<boolean>(false);
const [makerFeeFocused, setMakerFeeFocused] = useState<boolean>(false);
const tab = methods.watch('exchangeType');
const tokenWalletInfo = methods.watch('tokenWalletInfo');
const amount = methods.watch('tokenAmount');
const makerFee = methods.watch('fee');
const nftId = methods.watch('nftId');
const launcherId = launcherIdFromNFTId(nftId ?? '');
const { nft } = useNFT(launcherId);
const { data: walletBalance, isLoading: isLoadingWalletBalance } = useGetWalletBalanceQuery(
{
walletId: tokenWalletInfo.walletId,
},
{
skip: tab !== NFTOfferExchangeType.TokenForNFT,
},
);
const spendableBalanceString: string | undefined = useMemo(() => {
let balanceString: string | undefined;
let balance = new BigNumber(0);
if (
!isLoadingWalletBalance &&
tab === NFTOfferExchangeType.TokenForNFT &&
walletBalance &&
walletBalance.walletId === tokenWalletInfo.walletId
) {
switch (tokenWalletInfo.walletType) {
case WalletType.STANDARD_WALLET:
balanceString = mojoToChiaLocaleString(walletBalance.spendableBalance, locale);
balance = mojoToChia(walletBalance.spendableBalance);
break;
case WalletType.CAT:
case WalletType.RCAT:
balanceString = mojoToCATLocaleString(walletBalance.spendableBalance, locale);
balance = mojoToCAT(walletBalance.spendableBalance);
break;
default:
break;
}
}
if (
balanceString !== tokenWalletInfo.spendableBalanceString ||
!balance.isEqualTo(tokenWalletInfo.spendableBalance)
) {
tokenWalletInfo.spendableBalanceString = balanceString;
tokenWalletInfo.spendableBalance = balance;
methods.setValue('tokenWalletInfo', tokenWalletInfo);
}
return balanceString;
}, [isLoadingWalletBalance, tab, walletBalance, tokenWalletInfo, locale, methods]);
// HACK: manually determine the value for the amount field's shrink input prop.
// Without this, toggling between the two tabs with an amount specified will cause
// the textfield's label and value to overlap.
const shrinkAmount = useMemo(() => {
if (!amountFocused && (amount === undefined || amount.length === 0)) {
return false;
}
return true;
}, [amount, amountFocused]);
const shrinkMakerFee = useMemo(() => {
if (!makerFeeFocused && (makerFee === undefined || makerFee.length === 0)) {
return false;
}
return true;
}, [makerFee, makerFeeFocused]);
const result = useMemo(() => {
if (!nft || nft.royaltyPercentage === undefined) {
return undefined;
}
const royaltyPercentage = convertRoyaltyToPercentage(nft.royaltyPercentage);
const includedMakerFee = tokenWalletInfo.walletType === WalletType.STANDARD_WALLET ? makerFee : 0;
return {
...calculateNFTRoyalties(
parseFloat(amount || '0'),
parseFloat(includedMakerFee || '0'),
convertRoyaltyToPercentage(nft.royaltyPercentage),
tab,
),
royaltyPercentage,
};
}, [amount, makerFee, nft, tokenWalletInfo, tab]);
const { royaltyPercentage, royaltyAmountString, nftSellerNetAmount, totalAmountString } = result ?? {};
const nftElem = (
<Grid item>
<TextField
id={`${tab}-nftId}`}
key={`${tab}-nftId}`}
variant="filled"
name="nftId"
color="secondary"
disabled={disabled}
label={<Trans>NFT</Trans>}
defaultValue={defaultValues.nftId}
placeholder={t`NFT Identifier`}
inputProps={{ spellCheck: false }}
fullWidth
required
/>
</Grid>
);
const amountElem = (
<Flex flexDirection="row" gap={2}>
<Grid xs={6} item>
<Flex flexDirection="column" gap={1}>
<Amount
id={`${tab}-amount}`}
key={`${tab}-amount}`}
variant="filled"
name="tokenAmount"
color="secondary"
disabled={disabled}
label={<Trans>Amount</Trans>}
defaultValue={amount}
symbol={tokenWalletInfo.symbol ?? ''}
onChange={handleAmountChange}
onFocus={() => setAmountFocused(true)}
onBlur={() => setAmountFocused(false)}
showAmountInMojos
InputLabelProps={{ shrink: shrinkAmount }}
autoFocus
required
fullWidth
/>
{tab === NFTOfferExchangeType.TokenForNFT && (
<Flex flexDirection="row" alignItems="center" gap={1}>
<Typography variant="body2">Spendable balance: </Typography>
{spendableBalanceString === undefined ? (
<Typography variant="body2">Loading...</Typography>
) : (
<Typography variant="body2">{spendableBalanceString}</Typography>
)}
</Flex>
)}
</Flex>
</Grid>
<Grid xs={6} item>
<NFTOfferTokenSelector
selectedWalletId={tokenWalletInfo.walletId}
id="tokenWalletId"
onChange={(selection) =>
handleTokenSelectionChanged(selection.walletId, selection.walletType, selection.symbol, selection.name)
}
/>
</Grid>
</Flex>
);
const offerElem = tab === NFTOfferExchangeType.NFTForToken ? nftElem : amountElem;
const takerElem = tab === NFTOfferExchangeType.NFTForToken ? amountElem : nftElem;
const showRoyaltyWarning = (royaltyPercentage ?? 0) >= 20;
const royaltyPercentageColor = showRoyaltyWarning ? StateColor.WARNING : 'textSecondary';
const showNegativeAmountWarning = (nftSellerNetAmount ?? 0) < 0;
function handleAmountChange(amountLocal: string) {
methods.setValue('tokenAmount', amountLocal);
}
function handleFeeChange(fee: string) {
methods.setValue('fee', fee);
}
function handleTokenSelectionChanged(walletId: number, walletType: WalletType, symbol?: string, name?: string) {
methods.setValue('tokenWalletInfo', { walletId, walletType, symbol, name });
}
function handleReset() {
methods.reset(defaultValues);
}
const makerFeeElem = (
<NFTOfferCreationFee
disabled={disabled}
onChange={handleFeeChange}
defaultValue={defaultValues.fee}
onFocus={() => setMakerFeeFocused(true)}
onBlur={() => setMakerFeeFocused(false)}
InputLabelProps={{ shrink: shrinkMakerFee }}
/>
);
return (
<Flex flexDirection="column" flexGrow={1} gap={3} style={{ padding: '1.5rem' }}>
<Tabs
value={tab}
onChange={(_event, newValue) => methods.setValue('exchangeType', newValue)}
textColor="primary"
indicatorColor="primary"
>
<Tab value={NFTOfferExchangeType.TokenForNFT} label={<Trans>Buy an NFT</Trans>} disabled={disabled} />
<Tab value={NFTOfferExchangeType.NFTForToken} label={<Trans>Sell an NFT</Trans>} disabled={disabled} />
</Tabs>
<Grid container>
<Flex flexDirection="column" flexGrow={1} gap={3}>
<Flex flexDirection="column" gap={1}>
<Typography variant="subtitle1" color="textSecondary">
You will offer
</Typography>
{offerElem}
</Flex>
<Flex flexDirection="column" gap={1}>
<Typography variant="subtitle1" color="textSecondary">
In exchange for
</Typography>
{takerElem}
</Flex>
{nft?.royaltyPercentage ? (
<Flex flexDirection="column" gap={2}>
<Flex flexDirection="column" gap={0.5}>
<Flex flexDirection="row" alignItems="center" gap={1}>
<Typography variant="body1" color={royaltyPercentageColor}>
<Trans>Creator Fee ({`${royaltyPercentage}%)`}</Trans>
</Typography>
{showRoyaltyWarning && (
<Tooltip title={<Trans>Creator royalty percentage seems high</Trans>}>
<StyledWarningIcon fontSize="small" />
</Tooltip>
)}
</Flex>
{amount && (
<Typography variant="subtitle1" color="textSecondary">
<FormatLargeNumber value={new BigNumber(royaltyAmountString ?? 0)} />{' '}
{tokenWalletInfo.symbol ?? tokenWalletInfo.name ?? ''}
</Typography>
)}
</Flex>
</Flex>
) : null}
{tab === NFTOfferExchangeType.TokenForNFT && (
<Flex flexDirection="column" gap={2}>
{!nft?.royaltyPercentage && <Divider />}
{makerFeeElem}
</Flex>
)}
{nft?.royaltyPercentage && amount ? (
<Flex flexDirection="column" gap={2}>
<>
<Flex flexDirection="column" gap={0.5}>
<Typography variant="body1" color="textSecondary">
{tab === NFTOfferExchangeType.NFTForToken ? (
<Trans>You will receive</Trans>
) : (
<Trans>They will receive</Trans>
)}
</Typography>
<Typography variant="subtitle1" color={showNegativeAmountWarning ? StateColor.ERROR : 'inherit'}>
<FormatLargeNumber value={new BigNumber(nftSellerNetAmount ?? 0)} />{' '}
{tokenWalletInfo.symbol ?? tokenWalletInfo.name ?? ''}
</Typography>
{showNegativeAmountWarning && (
<Typography variant="body2" color={StateColor.ERROR}>
<Trans>Unable to create an offer where the net amount is negative</Trans>
</Typography>
)}
</Flex>
<Divider />
<Flex flexDirection="column" gap={0.5}>
<Flex flexDirection="row" alignItems="center" gap={1}>
<Typography variant="h6" color="textSecondary">
{tab === NFTOfferExchangeType.NFTForToken ? (
<Trans>Total Amount Requested</Trans>
) : (
<Trans>Total Amount Offered</Trans>
)}
</Typography>
<Flex justifyContent="center">
<TooltipIcon>
{tab === NFTOfferExchangeType.NFTForToken ? (
<Trans>
The total amount requested includes the asking price, plus the associated creator fees (if
the NFT has royalty payments enabled). Creator fees will be paid by the party that accepts
the offer.
<p />
The optional offer creation fee is not included in this total, and will be deducted from
your spendable balance upon offer creation.
</Trans>
) : (
<Trans>
The total amount offered includes the price you're willing to pay for the NFT, plus the
optional offer creation fee. One or more coins totalling at least the amount shown below
will be deducted from your spendable balance upon offer creation.
<p />
If the NFT has royalty payments enabled, those creator fees will be paid by the party that
accepts the offer.
</Trans>
)}
</TooltipIcon>
</Flex>
</Flex>
<Typography variant="h5" fontWeight="bold">
<FormatLargeNumber value={new BigNumber(totalAmountString ?? 0)} />{' '}
{tokenWalletInfo.symbol ?? tokenWalletInfo.name ?? ''}
{tab === NFTOfferExchangeType.TokenForNFT &&
tokenWalletInfo.walletType !== WalletType.STANDARD_WALLET &&
makerFee > 0 && (
<div>
<FormatLargeNumber value={new BigNumber(makerFee ?? 0)} />
{' XCH'}
</div>
)}
</Typography>
</Flex>
</>
</Flex>
) : null}
{tab === NFTOfferExchangeType.NFTForToken && (
<Flex flexDirection="column" gap={2}>
<Divider />
{makerFeeElem}
</Flex>
)}
</Flex>
</Grid>
<Flex flexDirection="column" flexGrow={1} alignItems="flex-end" justifyContent="flex-end">
<Flex justifyContent="flex-end" gap={2}>
<Button variant="outlined" type="reset" onClick={handleReset} disabled={isProcessing}>
<Trans>Reset</Trans>
</Button>
<ButtonLoading variant="contained" color="primary" type="submit" loading={isProcessing}>
<Trans>Create Offer</Trans>
</ButtonLoading>
</Flex>
</Flex>
</Flex>
);
}
/* ========================================================================== */
/* NFT Offer Editor */
/* Currently only supports a single NFT <--> XCH/CAT offer */
/* ========================================================================== */
export type NFTOfferEditorTokenWalletInfo = {
walletId: number;
walletType: WalletType;
symbol?: string;
name?: string;
spendableBalance?: BigNumber;
spendableBalanceString?: string;
};
type NFTOfferEditorFormData = {
exchangeType: NFTOfferExchangeType;
nftId?: string;
tokenWalletInfo: NFTOfferEditorTokenWalletInfo;
tokenAmount: string;
fee: string;
};
type NFTOfferEditorValidatedFormData = {
exchangeType: NFTOfferExchangeType;
launcherId: string;
tokenWalletInfo: NFTOfferEditorTokenWalletInfo;
tokenAmount: string;
fee: string;
};
type NFTOfferEditorProps = {
nft?: NFTInfo;
onOfferCreated: (obj: { offerRecord: any; offerData: any }) => void;
exchangeType: NFTOfferExchangeType;
};
type NFTBuildOfferRequestParams = {
exchangeType: NFTOfferExchangeType;
nft: NFTInfo;
nftLauncherId: string;
tokenWalletInfo: NFTOfferEditorTokenWalletInfo;
tokenAmount: string;
fee: string;
};
function buildOfferRequest(params: NFTBuildOfferRequestParams) {
const { exchangeType, nft, nftLauncherId, tokenWalletInfo, tokenAmount, fee } = params;
const baseMojoAmount: BigNumber = [WalletType.CAT, WalletType.RCAT, WalletType.CRCAT].includes(
tokenWalletInfo.walletType,
)
? catToMojo(tokenAmount)
: chiaToMojo(tokenAmount);
const mojoAmount = exchangeType === NFTOfferExchangeType.NFTForToken ? baseMojoAmount : baseMojoAmount.negated();
const feeMojoAmount = chiaToMojo(fee);
const nftAmount = exchangeType === NFTOfferExchangeType.NFTForToken ? -1 : 1;
const innerAlsoDict = nft.supportsDid
? {
type: 'ownership',
owner: '()',
transfer_program: {
type: 'royalty transfer program',
launcher_id: `0x${nftLauncherId}`,
royalty_address: nft.royaltyPuzzleHash,
royalty_percentage: `${nft.royaltyPercentage}`,
},
}
: undefined;
const outerAlsoDict = {
type: 'metadata',
metadata: nft.chainInfo,
updater_hash: nft.updaterPuzhash,
...(innerAlsoDict ? { also: innerAlsoDict } : undefined),
};
const driverDict = {
[nftLauncherId]: {
type: 'singleton',
launcher_id: `0x${nftLauncherId}`,
launcher_ph: nft.launcherPuzhash,
also: outerAlsoDict,
},
};
return [
{
[nftLauncherId]: nftAmount,
[tokenWalletInfo.walletId]: mojoAmount,
},
exchangeType === NFTOfferExchangeType.TokenForNFT ? driverDict : undefined,
feeMojoAmount,
];
}
export default function NFTOfferEditor(props: NFTOfferEditorProps) {
const { nft, onOfferCreated, exchangeType } = props;
const [createOfferForIds, { isLoading: isCreateOfferForIdsLoading }] = useCreateOfferForIdsMutation();
const { nfts } = useNFTs();
const currencyCode = useCurrencyCode();
const errorDialog = useShowError();
const navigate = useNavigate();
const theme = useTheme();
const [suppressShareOnCreate] = useSuppressShareOnCreate();
const defaultValues: NFTOfferEditorFormData = {
exchangeType,
nftId: nft?.$nftId ?? '',
tokenWalletInfo: {
walletId: 1,
walletType: WalletType.STANDARD_WALLET,
symbol: currencyCode,
name: 'Chia',
spendableBalance: new BigNumber(0),
},
tokenAmount: '',
fee: '',
};
const methods = useForm<NFTOfferEditorFormData>({
shouldUnregister: false,
defaultValues,
});
const nftId = methods.watch('nftId');
const launcherId = launcherIdFromNFTId(nftId ?? '');
const { nft: queriedNFTInfo } = useNFT(launcherId);
function validateFormData(unvalidatedFormData: NFTOfferEditorFormData): NFTOfferEditorValidatedFormData | undefined {
const {
exchangeType: exchangeTypeLocal,
nftId: nftIdLocal,
tokenWalletInfo,
tokenAmount,
fee,
} = unvalidatedFormData;
let result: NFTOfferEditorValidatedFormData | undefined;
if (!nftIdLocal) {
errorDialog(new Error(t`Please enter an NFT identifier`));
} else if (!isValidNFTId(nftIdLocal)) {
errorDialog(new Error(t`Invalid NFT identifier`));
} else if (!launcherId) {
errorDialog(new Error(t`Failed to decode NFT identifier`));
} else if (!tokenWalletInfo?.walletId) {
errorDialog(new Error(t`Please select an asset type`));
} else if (!tokenAmount || tokenAmount === '0') {
errorDialog(new Error(t`Please enter an amount`));
} else if (
exchangeTypeLocal === NFTOfferExchangeType.TokenForNFT &&
tokenWalletInfo.spendableBalance?.isLessThan(tokenAmount)
) {
errorDialog(new Error(t`Amount exceeds spendable balance`));
} else {
result = {
exchangeType: exchangeTypeLocal,
launcherId,
tokenWalletInfo,
tokenAmount,
fee,
};
}
return result;
}
async function handleSubmit(unvalidatedFormData: NFTOfferEditorFormData) {
const formData = validateFormData(unvalidatedFormData);
if (!formData) {
console.error('Invalid NFT offer:');
console.error(unvalidatedFormData);
return;
}
const offerNFT = nft || queriedNFTInfo;
if (!offerNFT) {
errorDialog(new Error(t`NFT details not available`));
return;
}
const {
exchangeType: exchangeTypeLocal,
launcherId: launcherIdLocal,
tokenWalletInfo,
tokenAmount,
fee,
} = formData;
if (exchangeTypeLocal === NFTOfferExchangeType.NFTForToken) {
const haveNFT = nfts.find((nftItem: NFTInfo) => nftItem.$nftId === offerNFT.$nftId) !== undefined;
if (!haveNFT) {
errorDialog(new Error(t`Unable to create an offer for an NFT that you do not own.`));
return;
}
}
const royaltyPercentage = convertRoyaltyToPercentage(offerNFT.royaltyPercentage ?? 0);
if (royaltyPercentage > 100) {
errorDialog(
new Error(t`Unable to create an offer for an NFT with a creator royalty percentage greater than 100%`),
);
return;
}
const [offer, driverDict, feeInMojos] = buildOfferRequest({
exchangeType: exchangeTypeLocal,
nft: offerNFT,
nftLauncherId: launcherIdLocal,
tokenWalletInfo,
tokenAmount,
fee,
});
try {
const response = await createOfferForIds({
offer,
fee: feeInMojos,
driverDict,
validateOnly: false,
disableJSONFormatting: true,
}).unwrap();
const { offer: offerData, tradeRecord: offerRecord } = response;
navigate(-1);
if (!suppressShareOnCreate) {
onOfferCreated({ offerRecord, offerData });
}
} catch (err) {
errorDialog(err);
}
}
return (
<Form methods={methods} onSubmit={handleSubmit}>
<Flex
flexDirection="column"
flexGrow={1}
gap={1}
sx={{
border: `1px solid ${useColorModeValue(theme, 'border')}`,
borderRadius: '4px',
bgcolor: 'background.paper',
boxShadow: `0px 2px 1px -1px ${alpha(Color.Neutral[900], 0.2)}, 0px 1px 1px 0px ${alpha(
Color.Neutral[900],
0.14,
)}, 0px 1px 3px 0px ${alpha(Color.Neutral[900], 0.12)}`,
overflow: 'hidden',
}}
>
<Flex flexDirection="row">
<NFTOfferConditionalsPanel defaultValues={defaultValues} isProcessing={isCreateOfferForIdsLoading} />
<NFTOfferPreview nftId={nftId} />
</Flex>
</Flex>
</Form>
);
}
/* ========================================================================== */
/* Create and Host the NFT Offer Editor */
/* ========================================================================== */
type CreateNFTOfferEditorProps = {
nft?: NFTInfo;
exchangeType?: NFTOfferExchangeType;
referrerPath?: string;
onOfferCreated: (obj: { offerRecord: any; offerData: any }) => void;
};
export function CreateNFTOfferEditor(props: CreateNFTOfferEditorProps) {
const { nft, exchangeType = NFTOfferExchangeType.TokenForNFT, referrerPath, onOfferCreated } = props;
const title = <Trans>Create an NFT Offer</Trans>;
const navElement = referrerPath ? (
<Back variant="h5" to={referrerPath}>
{title}
</Back>
) : (
<>{title}</>
);
return (
<Grid container>
<Flex flexDirection="column" flexGrow={1} gap={3}>
<Flex>{navElement}</Flex>
<NFTOfferEditor nft={nft} onOfferCreated={onOfferCreated} exchangeType={exchangeType} />
</Flex>
</Grid>
);
}