From 3c6904c9aa2e6cf0a5806cd108262f48fb611b39 Mon Sep 17 00:00:00 2001 From: Sean Date: Wed, 22 Nov 2023 08:44:42 +1100 Subject: [PATCH] new function to get a deployed contract address (#4) --- include/ethyl/provider.hpp | 1 + src/provider.cpp | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/include/ethyl/provider.hpp b/include/ethyl/provider.hpp index 7029f32..d871b22 100644 --- a/include/ethyl/provider.hpp +++ b/include/ethyl/provider.hpp @@ -52,6 +52,7 @@ class Provider { bool transactionSuccessful(const std::string& txHash, int64_t timeout = 320000); uint64_t gasUsed(const std::string& txHash, int64_t timeout = 320000); mpz_class getBalance(const std::string& address); + std::string getContractDeployedInLatestBlock(); FeeData getFeeData(); diff --git a/src/provider.cpp b/src/provider.cpp index 4499cda..a5b1b93 100644 --- a/src/provider.cpp +++ b/src/provider.cpp @@ -322,6 +322,25 @@ mpz_class Provider::getBalance(const std::string& address) { } } +std::string Provider::getContractDeployedInLatestBlock() { + nlohmann::json params = nlohmann::json::array(); + params.push_back("latest"); + params.push_back(true); + auto blockResponse = makeJsonRpcRequest("eth_getBlockByNumber", params); + if (blockResponse.status_code != 200) + throw std::runtime_error("Failed to get the latest block"); + nlohmann::json blockJson = nlohmann::json::parse(blockResponse.text); + + for (const auto& tx : blockJson["result"]["transactions"]) { + std::optional transactionReceipt = getTransactionReceipt(tx["hash"].get()); + if (transactionReceipt.has_value()) + return transactionReceipt->at("contractAddress").get(); + } + + throw std::runtime_error("No contracts deployed in latest block"); +} + + FeeData Provider::getFeeData() { // Get latest block nlohmann::json params = nlohmann::json::array();