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

2x weekly promotion of develop to main #1311

Merged
merged 16 commits into from
Oct 4, 2024
2 changes: 1 addition & 1 deletion next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const nextConfig = {
compiler: { styledComponents: true },
reactStrictMode: true,
images: {
domains: ['ipfs.near.social'],
domains: ['ipfs.near.social','ipfs.io'],
},
experimental: {
optimizePackageImports: ['@phosphor-icons/react'],
Expand Down
24 changes: 21 additions & 3 deletions src/components/NTFImage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,27 +15,40 @@ interface Nft {
}

interface NftImageProps {
nft: Nft;
nft?: Nft;
ipfs_cid?: string;
alt: string;
}

const DEFAULT_IMAGE = 'https://ipfs.near.social/ipfs/bafkreibmiy4ozblcgv3fm3gc6q62s55em33vconbavfd2ekkuliznaq3zm';

const getImage = (key: string) => {
const imgUrl = localStorage.getItem(`keysImage:${key}`);
return imgUrl || null;
};

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

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

const fetchNftData = useCallback(async () => {
if (!wallet || !nft || !nft.contractId || !nft.tokenId || ipfs_cid) return;

const imgCache = getImage(nft.tokenId);
if (imgCache) {
setImageUrl(imgCache);
return;
}
const [nftMetadata, tokenData] = await Promise.all([
wallet.viewMethod({ contractId: nft.contractId, method: 'nft_metadata' }),
wallet.viewMethod({ contractId: nft.contractId, method: 'nft_token', args: { token_id: nft.tokenId } }),
]);

const tokenMetadata = tokenData.metadata;
const tokenMedia = tokenMetadata?.media || '';
const tokenMedia = tokenData?.metadata?.media || '';

if (tokenMedia.startsWith('https://') || tokenMedia.startsWith('http://') || tokenMedia.startsWith('data:image')) {
setImageUrl(tokenMedia);
Expand All @@ -54,5 +67,10 @@ export const NftImage: React.FC<NftImageProps> = ({ nft, ipfs_cid, alt }) => {
}
}, [ipfs_cid, fetchNftData]);

useEffect(() => {
if (!wallet || !nft || !nft.contractId || !nft.tokenId || ipfs_cid || DEFAULT_IMAGE === imageUrl) return;
setImage(nft.tokenId, imageUrl);
}, [imageUrl, wallet, nft, ipfs_cid]);

return <RoundedImage width={43} height={43} src={imageUrl} alt={alt} />;
};
190 changes: 190 additions & 0 deletions src/components/tools/FungibleToken/CreateTokenForm.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
import { Button, FileInput, Flex, Form, Grid, Input, openToast, Text } from '@near-pagoda/ui';
import React, { useContext } from 'react';
import type { SubmitHandler } from 'react-hook-form';
import { Controller, useForm } from 'react-hook-form';

import { NearContext } from '@/components/WalletSelector';

type FormData = {
total_supply: string;
name: string;
symbol: string;
icon: FileList;
decimals: number;
};

const FACTORY_CONTRACT = 'tkn.primitives.near';

const MAX_FILE_SIZE = 10 * 1024;
const ACCEPTED_IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/svg+xml'];

const CreateTokenForm: React.FC = () => {
const {
control,
register,
handleSubmit,
formState: { errors, isSubmitting },
} = useForm<FormData>();

const { wallet, signedAccountId } = useContext(NearContext);

const validateImage = (files: FileList) => {
if (files.length === 0) return 'Image is required';
const file = files[0];
if (file.size > MAX_FILE_SIZE) return 'Image size should be less than 10KB';
if (!ACCEPTED_IMAGE_TYPES.includes(file.type)) return 'Not a valid image format';
return true;
};

const convertToBase64 = (file: File): Promise<string> => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result as string);
reader.onerror = (error) => reject(error);
});
};

const onSubmit: SubmitHandler<FormData> = async (data) => {
let base64Image = '';
if (data.icon[0]) {
base64Image = await convertToBase64(data.icon[0]);
}

const total_supply = BigInt(data.total_supply) * BigInt(Math.pow(10, Number(data.decimals)));

const args = {
args: {
owner_id: signedAccountId,
total_supply: total_supply.toString(),
metadata: {
spec: 'ft-1.0.0',
name: data.name,
symbol: data.symbol,
icon: base64Image,
decimals: data.decimals,
},
},
account_id: signedAccountId,
};

const requiredDeposit = await wallet?.viewMethod({ contractId: FACTORY_CONTRACT, method: 'get_required', args });

try {
const result = await wallet?.signAndSendTransactions({
transactions: [
{
receiverId: FACTORY_CONTRACT,
actions: [
{
type: 'FunctionCall',
params: {
methodName: 'create_token',
args,
gas: '300000000000000',
deposit: requiredDeposit,
},
},
],
},
],
});

if (result) {
const transactionId = result[0].transaction_outcome.id;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
window.open(`https://nearblocks.io/txns/${transactionId}`, '_blank')!.focus();
}

openToast({
type: 'success',
title: 'Token Created',
description: `Token ${data.name} (${data.symbol}) created successfully`,
duration: 5000,
});
} catch (error) {
openToast({
type: 'error',
title: 'Error',
description: 'Failed to create token',
duration: 5000,
});
}
};

return (
<>
<Text size="text-l" style={{ marginBottom: '12px' }}>
Mint a Fungible Token
</Text>
<Form onSubmit={handleSubmit(onSubmit)}>
<Flex stack gap="l">
<Grid columns="1fr 1fr" columnsTablet="1fr" columnsPhone="1fr">
<Input
label="Total Supply"
placeholder="e.g., 1000"
error={errors.total_supply?.message}
{...register('total_supply', { required: 'Total supply is required' })}
/>
<Input
label="Decimals"
type="number"
placeholder="e.g., 6"
error={errors.decimals?.message}
{...register('decimals', {
required: 'Decimals is required',
valueAsNumber: true,
min: { value: 0, message: 'Decimals must be non-negative' },
max: { value: 24, message: 'Decimals must be 24 or less' },
})}
/>
</Grid>
<Grid columns="1fr 1fr" columnsTablet="1fr" columnsPhone="1fr">
<Input
label="Token Name"
placeholder="e.g., Test Token"
error={errors.name?.message}
{...register('name', { required: 'Token name is required' })}
/>
<Input
label="Token Symbol"
placeholder="e.g., TEST"
error={errors.symbol?.message}
{...register('symbol', { required: 'Token symbol is required' })}
/>
</Grid>
<div style={{ display: 'flex', flexDirection: 'column' }}>
<Controller
control={control}
name="icon"
rules={{
required: 'Image is required',
validate: validateImage,
}}
render={({ field, fieldState }) => (
<FileInput
label="Image Upload"
accept={ACCEPTED_IMAGE_TYPES.join(',')}
error={fieldState.error?.message}
{...field}
value={field.value ? Array.from(field.value) : []}
onChange={(value: File[] | null) => {
const files = value;
field.onChange(files);
}}
/>
)}
/>
<span style={{ fontSize: '0.8rem', color: 'gray' }}>
Accepted Formats: PNG, JPEG, GIF, SVG | Ideal dimension: 1:1 | Max size: 10kb
</span>
</div>

<Button label="Create Token" variant="affirmative" type="submit" loading={isSubmitting} />
</Flex>
</Form>
</>
);
};

export default CreateTokenForm;
28 changes: 28 additions & 0 deletions src/components/tools/FungibleToken/ListToken.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Accordion, Flex, Text } from '@near-pagoda/ui';
import Image from 'next/image';

import type { FT } from '@/pages/tools';

const ListToken = ({ tokens }: { tokens: FT[] }) => {
return (
<Accordion.Root type="multiple">
<Accordion.Item value="one">
<Accordion.Trigger>Tokens you minted</Accordion.Trigger>
<Accordion.Content>
{tokens.map((token) => {
return (
<Flex justify="space-between" align="center" key={`ft-${token.symbol}`}>
<Text>{token.name}</Text>
<Text>{token.symbol}</Text>
<Text>{BigInt(token.total_supply) / BigInt(Math.pow(10, Number(token.decimals)))}</Text>
<Image src={token.icon} alt={token.name} width={50} height={50} />
</Flex>
);
})}
</Accordion.Content>
</Accordion.Item>
</Accordion.Root>
);
};

export default ListToken;
15 changes: 15 additions & 0 deletions src/components/tools/FungibleToken/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import type { FT } from '@/pages/tools';

import CreateTokenForm from './CreateTokenForm';
import ListToken from './ListToken';

const FungibleToken = ({ tokens }: { tokens: FT[] }) => {
return (
<>
<CreateTokenForm />
<hr />
<ListToken tokens={tokens} />
</>
);
};
export default FungibleToken;
Loading
Loading