이번에는 web3.js로 NFT를 전송해보자
자신이 가지고 있는 토큰을 조회하면
각 토큰을 보낼 수 있는 input box
가 뜬다
Erc721 Component
import React, {useState} from 'react';
import erc721Abi from '../erc721Abi';
function Erc721({newErc721addr, web3, account, erc721list}){
const [to, setTo] = useState('');
const sendToken = async (tokenId) =>{
const tokenContract = await new web3.eth.Contract(erc721Abi, newErc721addr, {from: account});
tokenContract.methods
.transferFrom(account, to, tokenId)
.send({from: account})
.on("receipt", (receipt)=>{
setTo("");
})
}
return(
<div className="erc721list">
{erc721list.map((token)=>{
return (
<div className="erc721Token" key={token.tokenId}>
Name: <span className="name">{token.name}</span>
(<span className="symbol">{token.symbol}</span>)
<div className="nft">id: {token.tokenId}</div>
<img src={token.tokenURI} width={300}/>
<div className='tokenTransfer'>
To:
<input
type = 'text'
value = {to}
onChange={(event)=>{setTo(event.target.value);}}/>
<button className='sendTokenBtn'
onClick={sendToken.bind(this, token.tokenId)}>
sendToken
</button>
</div>
</div>
);
})}
</div>
)
}
export default Erc721;
<div className='tokenTransfer'>
To:
<input
type = 'text'
value = {to}
onChange={(event)=>{setTo(event.target.value);}}/>
<button className='sendTokenBtn'
onClick={sendToken.bind(this, token.tokenId)}>
sendToken
</button>
</div>
input box
생성 후, 토큰을 보낼 주소를 입력 받음
button
을 눌러서 sendToken()
함수 실행
transferFrom()
함수를 실행하여 토큰을 to
주소로 전송 const [to, setTo] = useState('');
const sendToken = async (tokenId) =>{
const tokenContract = await new web3.eth.Contract(erc721Abi, newErc721addr, {from: account});
tokenContract.methods
.transferFrom(account, to, tokenId)
.send({from: account})
.on("receipt", (receipt)=>{
setTo("");
})
}
contract.methods().send()
: 컨트랙트 함수를 실행하는 트랜잭션을 만들어 올리는 web3.js
send()
: event promise 객체를 반환하며 on
으로 받을 수 있음
on(‘receipt’, function(receipt){…}
: 트랜잭션 receipt을 사용할 수 있을 때 이벤트 트리거 && 콜백 함수 실행
보기 쉽게 잠깐 정리하자면
계정1: 0xa38c3be357e4470555c7e33561AA822F08fd36e6
계정2: 0x9126f6697893114A2eD44b66548b79721e47BFf3
컨트랙트 주소: 0x11227624b7c15E0e364a2cF521fb8869493e2648
계정1: 0xa38~~~
의 NFT를 계정2: 0x91~~~
에게 전달
다시 토큰을 확인해보면 방금 보낸 토큰은 안 보인다
{erc721list.length === 0 && pressBtn? <div> No Token :(</div>: <TokenList newErc721addr={newErc721addr} web3={web3} account ={account} erc721list={erc721list}/>
erc721list
가 비었을 경우No Token :(
출력
계정2: 0x91~~~
로 지갑 계정을 바꾸고 토큰을 확인해보면 전송된 NFT! 두둥
이더스캔에서도 확인 가능하다!
🦊 빠잇!🦊