Solidity 솔리디티 강좌 14강 : event - indexed
이번엔 solidity의 event의 index에 대해 알아보도록 하자.
indexed
는 solidity 내에서는 event에만 사용되는 키워드이다. indexed
를 활용해 특정 event의 값을 불러올 수 있다.
// SPDX-License-Identifier: GPL-3.0
pragma solidity >= 0.7.0 < 0.9.0;
contract lec14 {
event numberTracker(uint256 num, string str);
// 특정 index 값만 필터하여 가지고 올 수 있음
event numberTracker2(uint256 indexed num, string str);
uint256 num = 0;
function PushEvent (string memory _str) public {
emit numberTracker(num, _str);
emit numberTracker2(num, _str);
num++;
}
}
numberTracker
event와 numberTracker2
event는 모두 변수 num
과 str
값을 출력한다. PushEvent
함수는 두 event를 실행하고 변수 num
의 값을 1씩 증가시킨다.
여기서 주목할 점은 numberTracker
event와 달리 numberTracker2
event는 num
변수 앞에 indexed
가 붙었다.
👉 결과
배포 시, 위와 같이 두 event 모두 별 차이가 없다.
//App.js
async function getEvent (){
//num 1, 2일 때만 출력
let events = await lecture14.getPastEvents('numberTracker2',{ filter:{num:[2,1]},fromBlock: 1, toBlock:'latest'});
console.log(events)
//모든 값 출력
let events2 = await lecture14.getPastEvents('numberTracker',{ filter:{num:[2,1]},fromBlock: 1, toBlock:'latest'});
console.log(events2)
}
그러나 javascript를 통해 다음과 같이 출력을 해보면 확연한 차이를 느낄 수 있다.
getPastEvents
뒤에는 갖고 오고 싶은 event 이름을 써주면된다.
{ filter:{num:[2,1]},fromBlock: 1, toBlock:'latest'}
를 살펴보면 이는 첫 block부터 최근에 나온 block까지를 범위로 두고 num
이 2나 1일 경우에만 출력을 하겠다고 필터링을 하고 있는 것이다.
그러나 실제로 위 코드를 돌려보면 numberTracker2
event는 필터링이 되어 num
이 2와 1일 때만 출력이 되지만numberTracker
event는 indexed
키워드가 존재하지 않으므로 필터링이 되지 않고 모두 출력이 된다.
📍 학습하고 있는 영상에서는 solidity 강의가 목적이기 때문에 remix에서 VSCode로 넘어와 Solidity, javascript 코드를 어떻게 compile하는 지가 자세히 나오지 않았다. 따라서 본인도 영상만 시청하고 습득하여 넘어갔다. 실제로 해보고 싶은 사람들이라면 영상을 시청하면서 lec14 깃헙을 클론해 참고하길 바란다.
출처 및 참고 자료