[Solidity] Truffle 공부 - 12(Frontend Event 연동 및 데이터 관리)
Solidity 메모12!
유튜브 영상 자료(Dapp Campus)를 따라해보면서 배우고 있는 중입니다. 한번 따라해보면 처음에 익숙해지는데 꽤나 좋을 것 같습니다.
여기서는 로또비스무리한 컨트랙트를 만들고 있군요. 그래서 Lottery Contract로 만들어 보고 있습니다.
Frontend 단에서 Event 연동 부분 입니다.
Dapp에서의 데이터 가져오는 방법
- 데이터를 가져오는 방법(2가지)
- (1) smart contract를 직접 call해와서 관리(event 보다는 느리다)
- (2) event log를 읽어서 관리(indexed 를 추가해서 특정 값만 가져오는 것도 가능)
- (2) - 1) http(polling) 방법
- (2) - 2) websocket(subscribe)
데이터 가져오는 순서
(1) init과 동시에 past event들을 가져온다.
(2) websocket으로 geth 또는 infura와 연결한다.
(3) websocket으로 원하는 이벤트를 subscribe 한다.
(3) - 1) websocket를 이용할 수 없는 경우 polling 처리한다.(계속 물어보는 방법)
Event 처리시 주의 할 점
- 중요한 트랜잭션(금전적인 부분이 걸려 있는 경우)에는 블럭 컨펌횟수을 확인한다.
- websocket에는 컨펌이 1회만 되어도 보여주기 때문에 믿을 수 없는 블럭일 수도 있다.
- 이더리움에서는 일정 횟수의 컨펌(20 confirm이 아주 안전하다고 말해진다고 하는데.. 너무 느려질 듯) 이상인 경우 확정처리를 한다.
Events 를 가져오는 방법
- 참조 문서 : https://web3js.readthedocs.io/en/v1.3.0/web3-eth-contract.html#events
- 대표적인 2가지 방법 : pastEvents, Subscribe
// pastEvents
let events = await this.lotteryContract.getPastEvents("BET", {
fromBlock: 0,
toBlock: "latest",
});
console.log("getBetEvents:", events);
// Subscribe
this.lotteryContract.events
.BET(
{
// filter: {
// myIndexedParam: [20, 23],
// myOtherIndexedParam: "0x123456789...",
// },
fromBlock: 0,
},
function (error, event) {
if (error) {
console.log("emitted BET event error=================", error);
}
console.log("emitted BET event=================", event);
}
)
.on("connected", function (subscriptionId) {
console.log("connected:", subscriptionId);
})
.on("data", function (event) {
console.log("data:", event);
})
.on("changed", function (event) {
// remove event from local database
console.log("changed:", event);
})
.on("error", function (error, receipt) {
// If the transaction was rejected by the network with a receipt, the second parameter will be the receipt.
console.log("error:", error, ", receipt:", receipt);
});
0
0
0.000
0 comments