Solidity 메모11!
유튜브 영상 자료(Dapp Campus)를 따라해보면서 배우고 있는 중입니다. 한번 따라해보면 처음에 익숙해지는데 꽤나 좋을 것 같습니다.
여기서는 로또비스무리한 컨트랙트를 만들고 있군요. 그래서 Lottery Contract로 만들어 보고 있습니다.
드디어 화면개발입니다. 지금까지는 약간 지겨울 수 있었던 검정색 화면을 벗어나, Frontend UI에서 Metamask를 이용하여 트랜잭션을 일으켜봅니다.
Metamask 연동
- Metamask 연동방법은 수시로 변경이 되곤합니다.
- 그렇기 때문에 최신 연동방법을 확인 후 진행하시는 것이 좋습니다.
- 참고 사이트 : https://awantoch.medium.com/how-to-connect-web3-js-to-metamask-in-2020-fee2b2edf58a
// window.ethereum 이 존재 할 시 Metamask 연동
// 없는 경우 구버전방식으로 window.web3을 검색하여 연동
if (window.ethereum) {
console.log("recent mode");
this.web3 = new Web3(window.ethereum);
window.ethereum.enable();
return true;
} else if (window.web3) {
console.log("legacy mode");
this.web3 = new Web3(Web3.currentProvider);
}
return false;
Smartcontract 연동
- Smartcontract와 연동하기 위해서는 ABI 부분이 필요합니다. 그렇기 떄문에 해당 Contract의 ABI 부분은 따로 파일로 불러와서 사용해야합니다.
- 스마트컨트랙트를 호출 하는 방법(call, send)
- call은 스마트컨트랙트 내부 변수를 변화시키지 않고, 값을 "조회"하는데에 사용되는 함수
- send는 트랜잭션을 일으키거나, 코인/토큰의 전송이 필요한 경우에 사용되는 함수
- nonce : 해당 유저 address에서 일어난 트랜잭션 수를 저장(트랜잭션 리플레이 방지)하는 값으로 트랜잭션 실행시 논스값을 같이 보낸다.
// Lottery SmartContract 인스턴스 생성
// lotteryAbi는 별도로 가져와서 변수에 저장
// contractAddress : 스마트컨트랙트 Address
this.lotteryContract = new this.web3.eth.Contract(
lotteryAbi,
contractAddress
);
// call 함수를 이용하여 스마트컨트랙트 호출
const pot = await this.lotteryContract.methods.getPot().call();
// get nonce
let nonce = await this.web3.eth.getTransactionCount(this.account);
// betting
this.lotteryContract.methods.betAndDistribute("0x11").send({
from: this.account,
value: 5 * 10 ** 15,
gas: 300000,
gasPrice: 10 * 10 ** 9,
nonce: nonce,
});