Skip to content

Commit

Permalink
Refactoring to use useMutation and useQuery hooks, new token is drawer
Browse files Browse the repository at this point in the history
  • Loading branch information
hariria committed Jun 10, 2022
1 parent 6e0cae2 commit 49f19c2
Show file tree
Hide file tree
Showing 16 changed files with 435 additions and 266 deletions.
43 changes: 43 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
module.exports = {
env: {
browser: true,
es2021: true,
jest: true,
webextensions: true
},
extends: [
'airbnb',
'airbnb-typescript',
'plugin:typescript-sort-keys/recommended'
],
ignorePatterns: [
'*.css',
'*.js',
'*.jsx'
],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaFeatures: {
jsx: true
},
tsconfigRootDir: __dirname,
project: ["tsconfig.json"],
ecmaVersion: 'latest',
sourceType: 'module'
},
plugins: [
'sort-class-members',
'typescript-sort-keys',
'sort-keys-fix',
'sort-destructure-keys',
'react',
'@typescript-eslint'
],
rules: {
"react/require-default-props": 0,
"react/jsx-props-no-spreading": "off",
"sort-destructure-keys/sort-destructure-keys": 2,
"sort-keys-fix/sort-keys-fix": "warn",
"sort-keys": ["error", "asc", { caseSensitive: true, minKeys: 2, natural: false }]
}
}
21 changes: 21 additions & 0 deletions .github/PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<!--
Thank you for sending a PR. We appreciate you spending time to help improve the Aptos Core project.
The project is undergoing daily changes. Pull Requests will be reviewed and responded to as time permits.
-->

## Motivation

(Write your motivation for proposed changes here.)

### Have you read the [Contributing Guidelines on pull requests](https://github.com/aptos-labs/aptos-core/blob/main/CONTRIBUTING.md#pull-requests)?

(You must have submitted a [signed CLA](https://github.com/aptos-labs/aptos-core/blob/main/CONTRIBUTING.md#contributor-license-agreement) that includes your GitHub handle prior to us accepting and landing your work. Write your answer here.)

## Test Plan

(Share your test plan here. If you changed code, please provide us with clear instructions for verifying that your changes work.)

## Related PRs

(If this PR adds or changes functionality, please take some time to update the docs at https://github.com/aptos-labs/aptos-core/tree/main/developer-docs-site, and link to your PR here.)
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"buffer": "^6.0.3",
"constate": "^3.3.2",
"framer-motion": "^6",
"lodash": "^4.17.21",
"numeral": "^2.0.6",
"react": "^18.0.0",
"react-dom": "^18.0.0",
Expand Down
138 changes: 29 additions & 109 deletions src/core/components/CreateNFTModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,114 +4,34 @@
import { AddIcon } from '@chakra-ui/icons';
import {
Button,
Drawer,
DrawerBody,
DrawerContent,
DrawerFooter,
DrawerHeader,
DrawerOverlay,
FormControl,
FormLabel,
Input,
Modal,
ModalBody,
ModalCloseButton,
ModalContent,
ModalFooter,
ModalHeader,
ModalOverlay,
Text,
useColorMode,
useDisclosure,
VStack,
} from '@chakra-ui/react';
import { AptosClient, RequestError, TokenClient } from 'aptos';
import { useMutation, useQueryClient } from 'react-query';
import React from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
import useWalletState from 'core/hooks/useWalletState';
import { secondaryTextColor } from 'pages/Login';
import { NODE_URL } from 'core/constants';
import { AptosAccountState } from 'core/types';
import { AptosNetwork } from 'core/utils/network';
import { useCreateTokenAndCollection } from 'core/mutations/collectibles';

// eslint-disable-next-line global-require
window.Buffer = window.Buffer || require('buffer').Buffer;

export const defaultRequestErrorAttributes = {
config: {},
headers: {},
status: 400,
statusText: 'Move abort',
};

export interface RaiseForErrorProps {
vmStatus: string
}

const raiseForError = ({
vmStatus,
}: RaiseForErrorProps) => {
if (vmStatus.includes('Move abort')) {
throw new RequestError(vmStatus, {
data: {
message: vmStatus,
},
...defaultRequestErrorAttributes,
});
}
};

interface CreateTokenAndCollectionProps {
account: AptosAccountState;
collectionName?: string;
description?: string;
name?: string;
nodeUrl?: AptosNetwork;
supply: number;
uri?: string;
}

const createTokenAndCollection = async ({
account,
collectionName,
description,
name,
nodeUrl = NODE_URL,
supply,
uri,
}: CreateTokenAndCollectionProps): Promise<void> => {
if (!account || !(collectionName && description && uri && name)) {
return;
}
const aptosClient = new AptosClient(nodeUrl);
const tokenClient = new TokenClient(aptosClient);

const collectionTxnHash = await tokenClient.createCollection(
account,
collectionName,
description,
uri,
);

// Move abort errors do not throw so we need to check them manually
const collectionTxn: any = await aptosClient.getTransaction(collectionTxnHash);
let vmStatus: string = collectionTxn.vm_status;
raiseForError({ vmStatus });

const tokenTxnHash = await tokenClient.createToken(
account,
collectionName,
name,
description,
supply,
uri,
);
const tokenTxn: any = await aptosClient.getTransaction(tokenTxnHash);
vmStatus = tokenTxn.vm_status;
raiseForError({ vmStatus });
};

export default function CreateNFTModal() {
const { colorMode } = useColorMode();
const { isOpen, onClose, onOpen } = useDisclosure();
const { handleSubmit, register, watch } = useForm();
const { aptosAccount, aptosNetwork } = useWalletState();
const queryClient = useQueryClient();

const collectionName: string | undefined = watch('collectionName');
const tokenName: string | undefined = watch('tokenName');
Expand All @@ -124,24 +44,21 @@ export default function CreateNFTModal() {
isError,
isLoading,
mutateAsync: createTokenAndCollectionOnClick,
} = useMutation<void, RequestError>(() => (
createTokenAndCollection({
} = useCreateTokenAndCollection();

const errorMessage = error?.response?.data?.message;

const onSubmit: SubmitHandler<Record<string, any>> = async (_data, event) => {
event?.preventDefault();
await createTokenAndCollectionOnClick({
account: aptosAccount,
collectionName,
description,
name: tokenName,
nodeUrl: aptosNetwork,
supply,
uri,
})
));

const errorMessage = error?.response?.data?.message;

const onSubmit: SubmitHandler<Record<string, any>> = async (_data, event) => {
event?.preventDefault();
await createTokenAndCollectionOnClick();
await queryClient.refetchQueries(['gallery-items']);
});
onClose();
};

Expand All @@ -150,13 +67,16 @@ export default function CreateNFTModal() {
<Button size="xs" onClick={onOpen} leftIcon={<AddIcon fontSize="xs" />}>
New
</Button>
<Modal isOpen={isOpen} onClose={onClose}>
<ModalOverlay />
<ModalContent>
<Drawer
isOpen={isOpen}
onClose={onClose}
placement="bottom"
>
<DrawerOverlay />
<DrawerContent>
<form onSubmit={handleSubmit(onSubmit)}>
<ModalHeader>Create an NFT</ModalHeader>
<ModalCloseButton />
<ModalBody>
<DrawerHeader>Create an NFT</DrawerHeader>
<DrawerBody>
<VStack>
<FormControl isRequired>
<FormLabel fontWeight={400} color={secondaryTextColor[colorMode]}>
Expand Down Expand Up @@ -228,16 +148,16 @@ export default function CreateNFTModal() {
: undefined
}
</VStack>
</ModalBody>
<ModalFooter>
</DrawerBody>
<DrawerFooter>
<Button isLoading={isLoading} colorScheme="blue" mr={3} type="submit">
Submit
</Button>
<Button variant="ghost" onClick={onClose}>Close</Button>
</ModalFooter>
</DrawerFooter>
</form>
</ModalContent>
</Modal>
</DrawerContent>
</Drawer>
</>
);
}
9 changes: 2 additions & 7 deletions src/core/components/NetworkBody.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,12 @@ import {
SimpleGrid,
Heading,
useRadioGroup,
useToast,
} from '@chakra-ui/react';
import React, { useEffect, useState } from 'react';
import { AptosNetwork } from 'core/utils/network';
import { DEVNET_NODE_URL, LOCAL_NODE_URL } from 'core/constants';
import useWalletState from 'core/hooks/useWalletState';
import { useQuery } from 'react-query';
import { getLocalhostIsLive } from 'core/queries/network';
import { useTestnetStatus } from 'core/queries/network';
import useSwitchNetwork from 'core/mutations/network';
import NetworkListItem from './NetworkListItem';

Expand All @@ -39,11 +37,9 @@ export default function NetworkBody() {
const {
aptosNetwork,
} = useWalletState();
const { data: localTestnetIsLive } = useQuery('getTestnetStatus', getLocalhostIsLive, { refetchInterval: 1000 });
const { data: localTestnetIsLive } = useTestnetStatus();
const { isLoading, mutateAsync } = useSwitchNetwork();
const [error, setError] = useState<boolean>(false);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const toast = useToast();

const onClick = async (event: AptosNetwork) => {
try {
Expand All @@ -53,7 +49,6 @@ export default function NetworkBody() {
}
};

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { getRadioProps, getRootProps, setValue: radioSetValue } = useRadioGroup({
defaultValue: aptosNetwork,
name: 'aptosNetwork',
Expand Down
39 changes: 8 additions & 31 deletions src/core/components/TransferDrawer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import {
Text,
useColorMode,
useDisclosure,
useToast,
VStack,
} from '@chakra-ui/react';
import { SubmitHandler, useForm } from 'react-hook-form';
Expand All @@ -31,11 +30,9 @@ import {
getAccountExists,
getAccountResources,
getTestCoinTokenBalanceFromAccountResources,
getToAddressAccountExists,
useAccountExists,
} from 'core/queries/account';
import { submitTestCoinTransferTransaction } from 'core/mutations/transaction';
import { useMutation, useQuery, useQueryClient } from 'react-query';
import { getUserTransaction } from 'core/queries/transaction';
import { useSubmitTestCoinTransfer } from 'core/mutations/transaction';
import { ExternalLinkIcon } from '@chakra-ui/icons';
import {
secondaryErrorMessageColor, STATIC_GAS_AMOUNT,
Expand All @@ -52,8 +49,6 @@ export const secondaryDividerColor = {
function TransferDrawer() {
const { colorMode } = useColorMode();
const { aptosAccount, aptosNetwork } = useWalletState();
const toast = useToast();
const queryClient = useQueryClient();
const {
formState: { errors }, handleSubmit, register, setError, watch,
} = useForm();
Expand All @@ -62,26 +57,7 @@ function TransferDrawer() {
const {
isLoading: isTransferLoading,
mutateAsync: submitSendTransaction,
} = useMutation(submitTestCoinTransferTransaction, {
onSettled: async (txnHash) => {
if (!txnHash) {
return;
}
queryClient.invalidateQueries('getAccountResources');
const txn = await getUserTransaction({ nodeUrl: aptosNetwork, txnHashOrVersion: txnHash });
const amount = (txn?.payload)
? (txn.payload as { arguments: string[] }).arguments[1]
: undefined;
toast({
description: (txn?.success) ? `Amount transferred: ${amount}, gas consumed: ${txn?.gas_used}` : `Transfer failed, gas consumed: ${txn?.gas_used}`,
duration: 5000,
isClosable: true,
status: (txn?.success) ? 'success' : 'error',
title: `Transaction ${txn?.success ? 'success' : 'error'}`,
variant: 'solid',
});
},
});
} = useSubmitTestCoinTransfer();

const transferAmount: string | undefined | null = watch('transferAmount');
const transferAmountNumeral = numeral(transferAmount).format('0,0');
Expand All @@ -93,10 +69,10 @@ function TransferDrawer() {
} = { ...register('toAddress') };
const toAddress: string | undefined | null = watch('toAddress');
const explorerAddress = `https://explorer.devnet.aptos.dev/account/${toAddress}`;
const { data: toAddressAccountExists } = useQuery(
['getToAddressAccountExists', { aptosAccount, nodeUrl: aptosNetwork, toAddress }],
getToAddressAccountExists,
);
const { data: toAddressAccountExists } = useAccountExists({
address: toAddress || '',
debounceTimeout: 5000,
});

const onSubmit: SubmitHandler<Record<string, any>> = async (data, event) => {
event?.preventDefault();
Expand Down Expand Up @@ -135,6 +111,7 @@ function TransferDrawer() {
}
return 'Invalid address';
}, [toAddressAccountExists, toAddress]);

return (
<>
<Button
Expand Down
Loading

0 comments on commit 49f19c2

Please sign in to comment.