본문 바로가기
프로그래밍/solidity

[220518] 구매기능 만들기

by 한코코 2022. 5. 18.

SaleAnimalCard.tsx

import { Box, Button, Text } from "@chakra-ui/react";
import React, { FC, useEffect, useState } from "react";
import {
  mintAnimalTokenContract,
  saleAnimalTokenContract,
  web3,
} from "../web3Config";
import AnimalCard from "./AnimalCard";

interface SaleAnimalCardProps {
  animalType: string;
  animalPrice: string;
  animalTokenId: string;
  account: string;
  getOnSaleAnimalTokens: () => Promise<void>;
  // async 함수라서 Promise<> 형태
}

const SaleAnimalCard: FC<SaleAnimalCardProps> = ({
  animalType,
  animalPrice,
  animalTokenId,
  account,
  getOnSaleAnimalTokens,
}) => {
  const [isBuyable, setIsBuyable] = useState<boolean>(false); // 구매값

  const getAnimalTokenOnwer = async () => {
    try {
      const response = await mintAnimalTokenContract.methods
        .ownerOf(animalTokenId)
        .call();

      setIsBuyable(
        response.toLocaleLowerCase() === account.toLocaleLowerCase()
      );
    } catch (error) {
      console.error(error);
    }
  };

  const onClickBuy = async () => {
    try {
      if (!account) return;

      const response = await saleAnimalTokenContract.methods
        .purchaseAnimalToken(animalTokenId)
        .send({ from: account, value: animalPrice }); // payable을 위한 valuer값

      if (response.status) {
        getOnSaleAnimalTokens();
      }
    } catch (error) {
      console.error(error);
    }
  };

  useEffect(() => {
    getAnimalTokenOnwer();
  }, []);

  return (
    <Box textAlign="center" w={150}>
      <AnimalCard animalType={animalType} />
      <Box>
        <Text d="inline-block">{web3.utils.fromWei(animalPrice)} Matic</Text>
        
        <Button
          size="sm"
          colorScheme="green"
          m={2}
          disabled={isBuyable}
          onClick={onClickBuy}
        >
          Buy
        </Button>
      </Box>
    </Box>
  );
};

export default SaleAnimalCard;

 

 

sale-animal.tsx

...
        animalPrice={v.animalPrice}
        animalTokenId={v.animalTokenId}
        account={account}
        getOnSaleAnimalTokens={getOnSaleAnimalTokens}
    />
);
...

 

 

 

결과

nft를 구매하면 다음과 같이 판매목록에서 사라진다.

 

 

 

내가 가진 nft 목록에 들어가면 구매한 nft를 볼 수 있고, 다시 판매할 수도 있다.

 

 

 

 

github

https://github.com/h662/h662Animals-frontend/commit/43658103fb3ff9f878b6fe4439431b65438c78da

댓글