indexed는 event의 키워드이다. 이벤트 내에서만 사용할 수 있는 키워드인데 이 indexed는 특정한 이벤트의 값들을 들고 올 때 사용된다.
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;
contract lec14 {
event numberTracker(uint256 num, string str);
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 ++;
}
}
코드에서는 두 개의 이벤트가 존재한다. 이 이벤트들은 똑같은 파아미터 값을 받아 출력하지만 numberTracker2에 indexed가 있다는 것이다. 즉, numberTracker2는 num을 통해 특정 이벤트 값들을 갖고 올 수 있다는 것이다.
PushEvent 함수는 string 타입인 str을 받아서 numberTracker와 numberTracker2를 출력한다.
출력이 된 후에 num은 1이 오르고 다른 값을 출력할 때 오른 값으로 출력하게 된다.
다음과 같이 배포를 진행하면
logs에서 numberTracker와 numberTracker2가 출력된 것을 알 수 있다.
그러나 여기서는 indexed를 써도 다른 점을 알 수 없다.
sync function getEvent(){
let events = await lecture14.getPastEvents ('numberTracker2', { filter: {num: [2,1]}, from Block: 1, toBlock: 1, toBlock: 'latest'});
console.log(events)
let events2 = await lecture14.getPastEvents ('numberTracker', { filter: {num: [2,1]}, fromBlock: 1, toBlock: 1, toBlock: 'latest'});
console.log(events2)
위에서 사용했던 코드와 getPastEvents를 통해 그동안 출력되었던 이벤트를 가져오도록 한다.
getPastEvents를 사용할 때는 numberTracker와 numberTracker2처럼 가져오고 싶은 이벤트이름을 사용한다.
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;
contract lec14 {
event numberTracker(uint256 num, string str);
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 ++;
}
}
필터를 하여 특정한 값을 가져와야 하는데 lec14.sol을 보면, indexed에 num이 있기 때문에 num을 통해 필터를 적용한다.
따라서 getEvent 함수에 있는 num은 2나 1일 때 이벤트를 가져오라는 이야기이다.
fromBlock와 toBlock은 이 블록들의 범위를 말하는 것인데 블록 첫 번째부터 최근 나온 블록까지에 대한 블록 중에서 이벤트를 확인하여 number가 2나 1인 이벤트를 가져오라는 이야기이다.
abc, kim, kim5라는 세 가지 string 값을 넣고 PushEvent를 작동한다.
따라서 3개의 이벤트가 블록 안에 들어가게 된다.
Click 버튼을 누르면 getEvent 함수가 작동되고 console.log를 통해 이벤트 값들이 출력된다.
numberTracker2는 두 번째와 첫 번째 이벤트만 출력이 되고, numberTracker는 모든 이벤트가 출력될 것이다.
numberTracker2는 두 번째와 첫 번째 이벤트가 출력되는 것을 확인할 수 있고
numberTracker는 indexed 키워드가 쓰이지 않기 때문에 필터를 넣어도 모든 값이 출력된 것을 알 수 있다.
'PBL > 솔리디티' 카테고리의 다른 글
상속4 - super, 상속의 순서 (0) | 2024.06.11 |
---|---|
event1- 정의 (0) | 2024.06.04 |
상속3 - 두개 이상 상속하기 (0) | 2024.05.28 |
상속2 - overriding 오버라이딩 (0) | 2024.05.28 |
상속1 - 정의 (0) | 2024.05.22 |