Skip to content

Instantly share code, notes, and snippets.

@bitcoinwarrior1
Created March 12, 2020 05:21
Show Gist options
  • Save bitcoinwarrior1/4d1f031d5cf6ac724e7946b48f1cf44c to your computer and use it in GitHub Desktop.
Save bitcoinwarrior1/4d1f031d5cf6ac724e7946b48f1cf44c to your computer and use it in GitHub Desktop.
Snippet for filtering events in web3j
public static void main(String[] args) throws IOException {
List<TypeReference<?>> eventParamTypes = new ArrayList<>();
eventParamTypes.add(new TypeReference<Utf8String>(false) {});
eventParamTypes.add(new TypeReference<Bytes32>(true) {});
eventParamTypes.add(new TypeReference<Address>(true) {});
eventParamTypes.add(new TypeReference<Uint>(false) {});
eventParamTypes.add(new TypeReference<Uint>(false) {});
Event event = new Event("NameRegistered", eventParamTypes);
List<EthLog.LogResult> results = getFilteredEventLogs(
event,
"0xF0AD5cAd05e10572EfcEB849f6Ff0c68f9700455",
1,
"0x4e19170565065d892c3ef9fdbd0b783a22f9b5de31d8ef18ddc35afe4615741b"
);
System.out.println(results);
}
public static List<EthLog.LogResult> getFilteredEventLogs(
Event event,
String contractAddress,
int chainId,
String ... optionalTopics
) throws IOException {
String eventHash = EventEncoder.encode(event);
EthFilter filter = new EthFilter(
DefaultBlockParameterName.EARLIEST, // From block 0
DefaultBlockParameterName.LATEST, // To latest
contractAddress) // Unique Smart Contract
.addSingleTopic(eventHash)
.addOptionalTopics(optionalTopics);
EthLog response = getWeb3jService(chainId).ethGetLogs(filter).send();
return response.getLogs();
}
@bitcoinwarrior1
Copy link
Author

Output:

Log{removed=false, logIndex='0x2b', transactionIndex='0xb', transactionHash='0x4de8e88a5cbf341852ea2ec4a58abcf5f059bb67966c6d3aec37a890fe4b5070', blockHash='0x55def974961a8e200de4daabeb6ad334e6ac05c7e14f17c019dd6e53d2fea26c', blockNumber='0x7f5835', address='0xf0ad5cad05e10572efceb849f6ff0c68f9700455', data='0x000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000aadc6d59d74fce000000000000000000000000000000000000000000000000000000006115c9c2000000000000000000000000000000000000000000000000000000000000000b7361746f73686972696368000000000000000000000000000000000000000000', type='null', topics=[0xca6abbe9d7f11422cb6ca7629fbf6fe9efb1c621f71ce8f02b9f2a230097404f, 0x4e19170565065d892c3ef9fdbd0b783a22f9b5de31d8ef18ddc35afe4615741b, 0x000000000000000000000000f8bf2546b61a4b7a277d118290dc9dcbb34d29a6]}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment