본문 바로가기
프로그래밍/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, web3 } from "../web3Config";
import AnimalCard from "./AnimalCard";

interface SaleAnimalCardProps {
  animalType: string;
  animalPrice: string;
  animalTokenId: string; // 계정을 확인하기 위해 필요한 정보
  account: string; // 계정을 확인하기 위해 필요한 정보
}

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

  const getAnimalTokenOnwer = async () => {
    try {
      const response = await mintAnimalTokenContract.methods
        .ownerOf(animalTokenId) // 소유자의 주소값
        .call();

      setIsBuyable(
        // 대문자를 모두 소문자로 바꿔주는 toLocaleLowerCase
        // 생산자와 구매자의 주소값이 같다면
        response.toLocaleLowerCase() === account.toLocaleLowerCase()
      );
    } 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}>
          Buy
        </Button>
      </Box>
    </Box>
  );
};

export default SaleAnimalCard;

 

 

saleAnimal.tsx

...
key={i}
    animalType={v.animalType}
    animalPrice={v.animalPrice}
    animalTokenId={v.animalTokenId} // 계정을 확인하기 위해 필요한 정보
    account={account} // 계정을 확인하기 위해 필요한 정보
/>

 

 

 

결과

생산자와 구매자의 주소가 같을 경우 버튼은 비활성화 되고, 다를 경우는 구매할 수 있도록 활성화 된다.

 

 

 

github

https://github.com/h662/h662Animals-frontend/commit/fa2e22eb5df32f50e4b4b4147de0a906db7ed1ba

댓글