Skip to content

Commit

Permalink
fix: tools
Browse files Browse the repository at this point in the history
  • Loading branch information
gagdiez committed Oct 13, 2024
1 parent c31667b commit b9fa536
Show file tree
Hide file tree
Showing 18 changed files with 386 additions and 602 deletions.
34 changes: 5 additions & 29 deletions src/components/NTFImage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,41 +10,22 @@ interface NftImageProps {
nft?: NFT;
}

const getImage = (contract: string, id: string) => {
return localStorage.getItem(`keysImage:${contract}-${id}`);
};

const setImage = (contract: string, id: string, url: string) => {
localStorage.setItem(`keysImage:${contract}-${id}`, url);
};

export const NftImage: React.FC<NftImageProps> = ({ nft }) => {
const { wallet } = useContext(NearContext);
const [imageUrl, setImageUrl] = useState<string>('');

useEffect(() => {
const fetchNftData = async () => {
if (!wallet || !nft || !nft.contract_id || !nft.token_id) return;

const imgCache = getImage(nft.contract_id, nft.token_id);
if (imgCache) {
setImageUrl(imgCache);
return;
}

const [nftMetadata, tokenData] = await Promise.all([
wallet.viewMethod({ contractId: nft.contract_id, method: 'nft_metadata' }),
wallet.viewMethod({ contractId: nft.contract_id, method: 'nft_token', args: { token_id: nft.token_id } }),
]);

const tokenMedia = tokenData?.metadata?.media || '';
if (!wallet || !nft || !nft.token_id) return;

const tokenMedia = nft.metadata?.media || '';
console.log('tokenMedia', tokenMedia);
if (tokenMedia.startsWith('https://') || tokenMedia.startsWith('http://')) {
setImageUrl(tokenMedia);
} else if (tokenMedia.startsWith('data:image')) {
setImageUrl(tokenMedia);
} else if (nftMetadata?.base_uri) {
setImageUrl(`${nftMetadata.base_uri}/${tokenMedia}`);
} else if (nft.metadata?.base_uri) {
setImageUrl(`${nft.metadata.base_uri}/${tokenMedia}`);
} else if (tokenMedia.startsWith('Qm') || tokenMedia.startsWith('ba')) {
setImageUrl(`https://ipfs.near.social/ipfs/${tokenMedia}`);
}
Expand All @@ -53,10 +34,5 @@ export const NftImage: React.FC<NftImageProps> = ({ nft }) => {
fetchNftData();
}, [nft, imageUrl, wallet]);

useEffect(() => {
if (!nft || !nft.token_id) return;
setImage(nft.contract_id, nft.token_id, imageUrl);
}, [nft, imageUrl]);

return <RoundedImage src={imageUrl} alt={nft?.metadata?.title || ''} />;
};
23 changes: 9 additions & 14 deletions src/components/sidebar-navigation/UserDropdownMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import styled from 'styled-components';

import { signInContractId } from '@/config';
import { useBosComponents } from '@/hooks/useBosComponents';
import type { NFT } from '@/utils/types';

import { NftImage } from '../NTFImage';
import RoundedImage from '../RoundedImage';
Expand Down Expand Up @@ -93,26 +94,20 @@ type Props = {
collapsed?: boolean;
};

const parseNftImage = (nft: any, owner_id: string, title: string | null = null) => {
const parseNftImage = (nft: any, owner_id: string, title: string | null = null): NFT => {
return {
contract_id: nft.contractId as string,
contract_id: '',
approved_account_ids: [],
token_id: nft.tokenId as string,
owner_id,
metadata: {
title: title || owner_id,
description: null,
media: null,
media_hash: null,
copies: null,
issued_at: null,
expires_at: null,
starts_at: null,
updated_at: null,
extra: null,
reference: null,
reference_hash: null,
media: nft.metadata?.media || '',
description: nft.metadata?.description || '',
copies: nft.metadata?.copies || '1',
reference: nft.metadata?.reference || '',
base_uri: nft.metadata?.base_uri || '',
},
approved_account_ids: null,
};
};

Expand Down
2 changes: 1 addition & 1 deletion src/components/tools/FungibleToken/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import type { FT } from '@/utils/types';
import CreateTokenForm from './CreateTokenForm';
import ListToken from './ListToken';

const FungibleToken = ({ tokens, reload }: { tokens: FT[]; reload: (delay: number) => void }) => {
const FungibleToken = ({ user_fts: tokens, reload }: { user_fts: FT[]; reload: (delay: number) => void }) => {
return (
<>
<CreateTokenForm reload={reload} />
Expand Down
163 changes: 95 additions & 68 deletions src/components/tools/Linkdrops/CreateNFTDrop.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { Accordion, Button, Flex, Form, Input, openToast } from '@near-pagoda/ui';
import { Accordion, Button, Flex, Form, Input, openToast, Text } from '@near-pagoda/ui';
import { parseNearAmount } from 'near-api-js/lib/utils/format';
import { useContext, useState } from 'react';
import type { SubmitHandler } from 'react-hook-form';
import { useForm } from 'react-hook-form';

import { network } from '@/config';
import useNFT from '@/hooks/useNFT';
import generateAndStore from '@/utils/linkdrops';
import type { Collection, NFT } from '@/utils/types';

import { NearContext } from '../../wallet-selector/WalletSelector';
import Carousel from '../Shared/Carousel';
Expand All @@ -24,7 +24,13 @@ type FormData = {
const getDeposit = (amountPerLink: number, numberLinks: number) =>
parseNearAmount(((0.0426 + amountPerLink) * numberLinks).toString());

const CreateNFTDrop = ({ reload }: { reload: (delay: number) => void }) => {
const CreateNFTDrop = ({
user_collections,
reload,
}: {
user_collections: Collection[];
reload: (delay: number) => void;
}) => {
const { wallet, signedAccountId } = useContext(NearContext);
const {
register,
Expand All @@ -37,18 +43,16 @@ const CreateNFTDrop = ({ reload }: { reload: (delay: number) => void }) => {
},
});

const [nftSelected, setNftSelected] = useState('');
const [nftSelected, setNftSelected] = useState<NFT | undefined>(undefined);

const contracts = useNFT();

const fillForm = (origin: string, token_id: string) => {
setNftSelected(token_id);
setValue('tokenId', token_id);
setValue('contractId', origin);
const fillForm = (nft: NFT) => {
setNftSelected(nft);
console.log(nft);
setValue('tokenId', nft.token_id);
setValue('contractId', nft.contract_id);
};

const onSubmit: SubmitHandler<FormData> = async (data) => {
if (!wallet) throw new Error('Wallet has not initialized yet');
const dropId = Date.now().toString();
const args = {
deposit_per_use: '0',
Expand All @@ -63,76 +67,93 @@ const CreateNFTDrop = ({ reload }: { reload: (delay: number) => void }) => {
},
};

await wallet.signAndSendTransactions({
transactions: [
{
receiverId: KEYPOM_CONTRACT_ADDRESS,
actions: [
{
type: 'FunctionCall',
params: {
methodName: 'create_drop',
args,
gas: '300000000000000',
deposit: getDeposit(1, 1),
try {
await wallet?.signAndSendTransactions({
transactions: [
{
receiverId: KEYPOM_CONTRACT_ADDRESS,
actions: [
{
type: 'FunctionCall',
params: {
methodName: 'create_drop',
args,
gas: '300000000000000',
deposit: getDeposit(1, 1),
},
},
},
],
},
{
receiverId: data.contractId,
actions: [
{
type: 'FunctionCall',
params: {
methodName: 'nft_transfer_call',
args: {
receiver_id: KEYPOM_CONTRACT_ADDRESS,
token_id: data.tokenId,
msg: dropId,
],
},
{
receiverId: data.contractId,
actions: [
{
type: 'FunctionCall',
params: {
methodName: 'nft_transfer_call',
args: {
receiver_id: KEYPOM_CONTRACT_ADDRESS,
token_id: data.tokenId,
msg: dropId,
},
gas: '300000000000000',
deposit: 1,
},
gas: '300000000000000',
deposit: 1,
},
},
],
},
],
});

openToast({
type: 'success',
title: 'Form Submitted',
description: 'Your form has been submitted successfully',
duration: 5000,
});

reload(1000);
],
},
],
});

openToast({
type: 'success',
title: 'Linkdrop Created',
description: 'Your drop has been created',
duration: 5000,
});

reload(1000);
} catch (error) {
console.error(error);

openToast({
type: 'error',
title: 'Error',
description: 'Failed to create the drop',
duration: 5000,
});
}
};

return (
<>
<Flex stack style={{ border: '1px solid var(--violet3)', padding: '1rem', borderRadius: '10px' }}>
<Form onSubmit={handleSubmit(onSubmit)}>
<Flex stack gap="l">
<Input
label="Token Drop name"
placeholder="NEARCon Token Giveaway"
error={errors.dropName?.message}
{...register('dropName', { required: 'Token Drop name is required' })}
disabled={!signedAccountId}
/>
<Accordion.Root type="multiple">
{contracts.map((nfts, index) => (
<Accordion.Item value={index.toString()} key={`accordion-${nfts[0].contract_id}`}>
<Accordion.Trigger>{nfts[0].contract_id}</Accordion.Trigger>
<Accordion.Content>
<Carousel nfts={nfts} onSelect={fillForm} nftSelected={nftSelected} />
</Accordion.Content>
</Accordion.Item>
))}
</Accordion.Root>
<Flex stack gap="s">
<Text> Please select one of your NFTs to drop:</Text>
<Accordion.Root type="multiple" style={{ margin: 0 }}>
{user_collections.map((collection: Collection) =>
Object.entries(collection).map(([contract, nfts]) => (
<Accordion.Item value={contract} key={`accordion-${contract}`}>
<Accordion.Trigger>{contract}</Accordion.Trigger>
<Accordion.Content>
<Carousel nfts={nfts} onSelect={fillForm} nftSelected={nftSelected} />
</Accordion.Content>
</Accordion.Item>
)),
)}
</Accordion.Root>
</Flex>
<Input
label="NFT contract address"
placeholder="Enter a NFT contract address"
placeholder="Select a Token"
disabled
error={errors.contractId?.message}
{...register('contractId', {
Expand All @@ -141,18 +162,24 @@ const CreateNFTDrop = ({ reload }: { reload: (delay: number) => void }) => {
/>
<Input
label="Token ID"
placeholder="Enter a Token ID"
placeholder="Select a Token"
disabled
error={errors.tokenId?.message}
{...register('tokenId', {
required: 'Token ID per link is required',
})}
/>

<Button label="Create links" variant="affirmative" type="submit" loading={isSubmitting} />
<Button
label="Create Drop"
variant="affirmative"
type="submit"
loading={isSubmitting}
disabled={!signedAccountId}
/>
</Flex>
</Form>
</>
</Flex>
);
};

Expand Down
Loading

0 comments on commit b9fa536

Please sign in to comment.