MCPcopy Create free account
hub / github.com/QuipNetwork/cpp-sdk / getChainId

Function getChainId

src/common.cpp:70–137  ·  view source on GitHub ↗

Get chain ID from RPC endpoint

Source from the content-addressed store, hash-verified

68
69// Get chain ID from RPC endpoint
70uint64_t getChainId(const std::string &rpc_url) {
71 CURL *curl = curl_easy_init();
72 if (!curl) {
73 throw std::runtime_error("Failed to initialize CURL");
74 }
75
76 // Create JSON-RPC request for eth_chainId
77 std::string request = R"({"jsonrpc":"2.0","id":1,"method":"eth_chainId","params":[]})";
78 std::string response_string;
79
80 curl_easy_setopt(curl, CURLOPT_URL, rpc_url.c_str());
81 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request.c_str());
82 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
83 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_string);
84
85 // Add headers
86 struct curl_slist *headers = NULL;
87 headers = curl_slist_append(headers, "Content-Type: application/json");
88 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
89
90 CURLcode res = curl_easy_perform(curl);
91 curl_easy_cleanup(curl);
92 curl_slist_free_all(headers);
93
94 if (res != CURLE_OK) {
95 std::cerr << "Warning: Failed to get chain ID from RPC: "
96 << curl_easy_strerror(res) << std::endl;
97 return 31337; // Default to Hardhat
98 }
99
100 try {
101 // Parse JSON response
102 size_t json_start = response_string.find('{');
103 if (json_start == std::string::npos) {
104 throw std::runtime_error("Invalid JSON response");
105 }
106
107 std::string json_response = response_string.substr(json_start);
108
109 // Simple JSON parsing for the result field
110 size_t result_pos = json_response.find("\"result\"");
111 if (result_pos == std::string::npos) {
112 throw std::runtime_error("No result in response");
113 }
114
115 size_t quote_start = json_response.find("\"0x", result_pos);
116 if (quote_start == std::string::npos) {
117 throw std::runtime_error("Invalid chain ID format");
118 }
119
120 size_t quote_end = json_response.find("\"", quote_start + 1);
121 if (quote_end == std::string::npos) {
122 throw std::runtime_error("Invalid chain ID format");
123 }
124
125 std::string chain_id_hex = json_response.substr(quote_start + 1, quote_end - quote_start - 1);
126
127 // Convert hex to decimal

Callers 6

changePqOwnerMethod · 0.85
getChainIdMethod · 0.85
depositToWinternitzMethod · 0.85
getChainIdMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected