Skip to content

Commit

Permalink
[Code refactoring] - Use ExchangeNameEnum instead of string_view in E…
Browse files Browse the repository at this point in the history
…xchangePublic
  • Loading branch information
sjanel committed Nov 12, 2024
1 parent bf09e2b commit defaff8
Show file tree
Hide file tree
Showing 14 changed files with 67 additions and 58 deletions.
10 changes: 7 additions & 3 deletions src/api/common/include/exchangepublicapi.hpp
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
#pragma once

#include <cstdint>
#include <memory>
#include <mutex>
#include <optional>
#include <string_view>

#include "cache-file-updator-interface.hpp"
#include "cct_const.hpp"
#include "commonapi.hpp"
#include "currencycode.hpp"
#include "currencycodeset.hpp"
Expand Down Expand Up @@ -117,8 +119,10 @@ class ExchangePublic : public CacheFileUpdatorInterface {

CurrencyCodeSet queryFiats() { return _commonApi.queryFiats(); }

ExchangeNameEnum exchangeNameEnum() const { return _exchangeNameEnum; }

/// Get the name of the exchange in lower case.
std::string_view name() const { return _name; }
std::string_view name() const { return kSupportedExchanges[static_cast<int>(_exchangeNameEnum)]; }

/// Retrieve the shortest array of markets that can convert 'fromCurrencyCode' to 'toCurrencyCode' (shortest in terms
/// of number of conversions) of 'fromCurrencyCode' to 'toCurrencyCode'.
Expand Down Expand Up @@ -192,7 +196,7 @@ class ExchangePublic : public CacheFileUpdatorInterface {
MarketOrderBookVector pullMarketOrderBooksForReplay(Market market, TimeWindow timeWindow);

protected:
ExchangePublic(std::string_view name, FiatConverter &fiatConverter, CommonAPI &commonApi,
ExchangePublic(ExchangeNameEnum exchangeNameEnum, FiatConverter &fiatConverter, CommonAPI &commonApi,
const CoincenterInfo &coincenterInfo);

/// Retrieve the order book of given market.
Expand All @@ -206,7 +210,7 @@ class ExchangePublic : public CacheFileUpdatorInterface {

friend class ExchangePrivate;

std::string_view _name;
ExchangeNameEnum _exchangeNameEnum;
CachedResultVault _cachedResultVault;
FiatConverter &_fiatConverter;
CommonAPI &_commonApi;
Expand Down
11 changes: 6 additions & 5 deletions src/api/common/src/exchangepublicapi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
#include <utility>

#include "cct_allocator.hpp"
#include "cct_const.hpp"
#include "cct_exception.hpp"
#include "cct_flatset.hpp"
#include "cct_log.hpp"
Expand Down Expand Up @@ -60,14 +61,14 @@ using MarketDataDeserializer = DummyMarketDataDeserializer;
using MarketDataSerializer = DummyMarketDataSerializer;
#endif

ExchangePublic::ExchangePublic(std::string_view name, FiatConverter &fiatConverter, CommonAPI &commonApi,
ExchangePublic::ExchangePublic(ExchangeNameEnum exchangeNameEnum, FiatConverter &fiatConverter, CommonAPI &commonApi,
const CoincenterInfo &coincenterInfo)
: _name(name),
: _exchangeNameEnum(exchangeNameEnum),
_fiatConverter(fiatConverter),
_commonApi(commonApi),
_coincenterInfo(coincenterInfo),
_exchangeConfig(coincenterInfo.exchangeConfig(name)),
_marketDataDeserializerPtr(new MarketDataDeserializer(coincenterInfo.dataDir(), name)) {}
_exchangeConfig(coincenterInfo.exchangeConfig(name())),
_marketDataDeserializerPtr(new MarketDataDeserializer(coincenterInfo.dataDir(), name())) {}

ExchangePublic::~ExchangePublic() = default;

Expand Down Expand Up @@ -244,7 +245,7 @@ MarketsPath ExchangePublic::findMarketsPath(CurrencyCode fromCurrency, CurrencyC
std::lock_guard<std::recursive_mutex> guard(_publicRequestsMutex);
markets = queryTradableMarkets();
if (markets.empty()) {
log::error("No markets retrieved for {}", _name);
log::error("No markets retrieved for {}", name());
return ret;
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/api/common/test/exchangeprivateapi_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ class ExchangePrivateTest : public ::testing::Test {
CommonAPI commonAPI{coincenterInfo, Duration::max()};
FiatConverter fiatConverter{coincenterInfo, Duration::max(), Reader()}; // max to avoid real Fiat converter queries

MockExchangePublic exchangePublic{kSupportedExchanges[0], fiatConverter, commonAPI, coincenterInfo};
MockExchangePublic exchangePublic{ExchangeNameEnum::binance, fiatConverter, commonAPI, coincenterInfo};
APIKey key{"test", "testUser", "", "", ""};
MockExchangePrivate exchangePrivate{exchangePublic, coincenterInfo, key};

Expand Down Expand Up @@ -455,7 +455,7 @@ class ExchangePrivateWithdrawTest : public ExchangePrivateTest {
protected:
MonetaryAmount grossAmount{"2.5ETH"};
CurrencyCode cur{grossAmount.currencyCode()};
MockExchangePublic destinationExchangePublic{"kraken", fiatConverter, commonAPI, coincenterInfo};
MockExchangePublic destinationExchangePublic{ExchangeNameEnum::kraken, fiatConverter, commonAPI, coincenterInfo};
MockExchangePrivate destinationExchangePrivate{destinationExchangePublic, coincenterInfo, key};
Wallet receivingWallet{
destinationExchangePrivate.exchangeName(), cur, "TestAddress", "TestTag", WalletCheck(), AccountOwner()};
Expand Down Expand Up @@ -545,7 +545,7 @@ TEST_F(ExchangePrivateWithdrawSimulationTest, SimulatedWithdrawalShouldNotCallLa
TEST_F(ExchangePrivateTest, WithdrawAsynchronous) {
MonetaryAmount grossAmount("2.5ETH");
CurrencyCode cur = grossAmount.currencyCode();
MockExchangePublic destinationExchangePublic("bithumb", fiatConverter, commonAPI, coincenterInfo);
MockExchangePublic destinationExchangePublic(ExchangeNameEnum::bithumb, fiatConverter, commonAPI, coincenterInfo);
MockExchangePrivate destinationExchangePrivate(destinationExchangePublic, coincenterInfo, key);
Wallet receivingWallet(destinationExchangePrivate.exchangeName(), cur, "TestAddress", "TestTag", WalletCheck(),
AccountOwner("SmithJohn", "스미스존"));
Expand Down
2 changes: 1 addition & 1 deletion src/api/common/test/exchangepublicapi_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ class ExchangePublicTest : public ::testing::Test {
MonitoringInfo(), Reader(), StableCoinReader()};
CommonAPI commonAPI{coincenterInfo, Duration::max()};
FiatConverter fiatConverter{coincenterInfo, Duration::max(), FiatConverterReader()};
MockExchangePublic exchangePublic{kSupportedExchanges[0], fiatConverter, commonAPI, coincenterInfo};
MockExchangePublic exchangePublic{ExchangeNameEnum::binance, fiatConverter, commonAPI, coincenterInfo};

MarketSet markets{{"BTC", "EUR"}, {"XLM", "EUR"}, {"ETH", "EUR"}, {"ETH", "BTC"}, {"BTC", "KRW"},
{"USD", "EOS"}, {"SHIB", "ICP"}, {"AVAX", "ICP"}, {"AVAX", "USDT"}};
Expand Down
5 changes: 3 additions & 2 deletions src/api/common/test/include/exchangepublicapi_mock.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

#include <optional>

#include "cct_const.hpp"
#include "commonapi.hpp"
#include "exchangepublicapi.hpp"
#include "exchangepublicapitypes.hpp"
Expand All @@ -14,9 +15,9 @@
namespace cct::api {
class MockExchangePublic : public ExchangePublic {
public:
MockExchangePublic(std::string_view name, FiatConverter &fiatConverter, CommonAPI &commonApi,
MockExchangePublic(ExchangeNameEnum exchangeNameEnum, FiatConverter &fiatConverter, CommonAPI &commonApi,
const CoincenterInfo &config)
: ExchangePublic(name, fiatConverter, commonApi, config) {}
: ExchangePublic(exchangeNameEnum, fiatConverter, commonApi, config) {}

MOCK_METHOD(bool, healthCheck, (), (override));
MOCK_METHOD(CurrencyExchangeFlatSet, queryTradableCurrencies, (), (override));
Expand Down
5 changes: 1 addition & 4 deletions src/api/exchanges/include/bithumbpublicapi.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ class CommonAPI;

class BithumbPublic : public ExchangePublic {
public:
static constexpr std::string_view kExchangeName = "bithumb";
static constexpr auto kStatusOK = 0;
static constexpr auto kStatusUnexpectedError = -1;
static constexpr auto kStatusNotPresentError = -2;
Expand All @@ -46,9 +45,7 @@ class BithumbPublic : public ExchangePublic {

MarketPriceMap queryAllPrices() override { return MarketPriceMapFromMarketOrderBookMap(_allOrderBooksCache.get()); }

MonetaryAmountByCurrencySet queryWithdrawalFees() override {
return _commonApi.tryQueryWithdrawalFees(kExchangeName);
}
MonetaryAmountByCurrencySet queryWithdrawalFees() override { return _commonApi.tryQueryWithdrawalFees(name()); }

std::optional<MonetaryAmount> queryWithdrawalFee(CurrencyCode currencyCode) override;

Expand Down
9 changes: 5 additions & 4 deletions src/api/exchanges/src/binancepublicapi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#include "apiquerytypeenum.hpp"
#include "binance-common-api.hpp"
#include "cachedresult.hpp"
#include "cct_const.hpp"
#include "cct_exception.hpp"
#include "cct_json-container.hpp"
#include "cct_log.hpp"
Expand Down Expand Up @@ -86,7 +87,7 @@ VolAndPriNbDecimals QueryVolAndPriNbDecimals(const ExchangeInfoDataByMarket& exc

BinancePublic::BinancePublic(const CoincenterInfo& coincenterInfo, FiatConverter& fiatConverter,
api::CommonAPI& commonAPI)
: ExchangePublic("binance", fiatConverter, commonAPI, coincenterInfo),
: ExchangePublic(ExchangeNameEnum::binance, fiatConverter, commonAPI, coincenterInfo),
_curlHandle(kURLBases, coincenterInfo.metricGatewayPtr(), permanentCurlOptionsBuilder().build(),
coincenterInfo.getRunMode()),
_commonInfo(_curlHandle, exchangeConfig()),
Expand All @@ -111,11 +112,11 @@ bool BinancePublic::healthCheck() {
json::container result = json::container::parse(
_commonInfo._curlHandle.query("/api/v3/ping", CurlOptions(HttpRequestType::kGet)), nullptr, kAllowExceptions);
if (result.is_discarded()) {
log::error("{} health check response is badly formatted: {}", _name, result.dump());
log::error("{} health check response is badly formatted: {}", name(), result.dump());
return false;
}
if (!result.empty()) {
log::error("{} health check is not empty: {}", _name, result.dump());
log::error("{} health check is not empty: {}", name(), result.dump());
}
return result.empty();
}
Expand Down Expand Up @@ -441,7 +442,7 @@ PublicTradeVector BinancePublic::queryLastTrades(Market mk, int nbTrades) {
static constexpr int kMaxNbLastTrades = 1000;

if (nbTrades > kMaxNbLastTrades) {
log::warn("{} is larger than maximum number of last trades of {} on {}", nbTrades, kMaxNbLastTrades, _name);
log::warn("{} is larger than maximum number of last trades of {} on {}", nbTrades, kMaxNbLastTrades, name());
nbTrades = kMaxNbLastTrades;
}

Expand Down
11 changes: 6 additions & 5 deletions src/api/exchanges/src/bithumbpublicapi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

#include "apiquerytypeenum.hpp"
#include "cachedresult.hpp"
#include "cct_const.hpp"
#include "cct_json-container.hpp"
#include "cct_log.hpp"
#include "cct_string.hpp"
Expand Down Expand Up @@ -93,7 +94,7 @@ json::container PublicQuery(CurlHandle& curlHandle, std::string_view endpoint, C
} // namespace

BithumbPublic::BithumbPublic(const CoincenterInfo& config, FiatConverter& fiatConverter, CommonAPI& commonAPI)
: ExchangePublic(kExchangeName, fiatConverter, commonAPI, config),
: ExchangePublic(ExchangeNameEnum::bithumb, fiatConverter, commonAPI, config),
_curlHandle(kUrlBase, config.metricGatewayPtr(), permanentCurlOptionsBuilder().build(), config.getRunMode()),
_tradableCurrenciesCache(
CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kCurrencies), _cachedResultVault), config,
Expand Down Expand Up @@ -128,11 +129,11 @@ bool BithumbPublic::healthCheck() {
const json::container jsonResponse = json::container::parse(
_curlHandle.query("/public/assetsstatus/BTC", CurlOptions(HttpRequestType::kGet)), nullptr, kAllowExceptions);
if (jsonResponse.is_discarded()) {
log::error("{} health check response is badly formatted", _name);
log::error("{} health check response is badly formatted", name());
return false;
}
const auto statusCode = BithumbPublic::StatusCodeFromJsonResponse(jsonResponse);
log::info("{} status code: {}", _name, statusCode);
log::info("{} status code: {}", name(), statusCode);
return statusCode == kStatusOK;
}

Expand All @@ -150,14 +151,14 @@ MarketSet BithumbPublic::queryTradableMarkets() {
}

std::optional<MonetaryAmount> BithumbPublic::queryWithdrawalFee(CurrencyCode currencyCode) {
return _commonApi.tryQueryWithdrawalFee(kExchangeName, currencyCode);
return _commonApi.tryQueryWithdrawalFee(name(), currencyCode);
}

MonetaryAmount BithumbPublic::queryLastPrice(Market mk) {
// Bithumb does not have a REST API endpoint for last price, let's compute it from the orderbook
std::optional<MonetaryAmount> avgPrice = getOrderBook(mk).averagePrice();
if (!avgPrice) {
log::error("Empty order book for {} on {} cannot compute average price", mk, _name);
log::error("Empty order book for {} on {} cannot compute average price", mk, name());
return MonetaryAmount(0, mk.quote());
}
return *avgPrice;
Expand Down
21 changes: 11 additions & 10 deletions src/api/exchanges/src/huobipublicapi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

#include "apiquerytypeenum.hpp"
#include "cachedresult.hpp"
#include "cct_const.hpp"
#include "cct_json-container.hpp"
#include "cct_log.hpp"
#include "cct_string.hpp"
Expand Down Expand Up @@ -84,7 +85,7 @@ json::container PublicQuery(CurlHandle& curlHandle, std::string_view endpoint,
} // namespace

HuobiPublic::HuobiPublic(const CoincenterInfo& config, FiatConverter& fiatConverter, api::CommonAPI& commonAPI)
: ExchangePublic("huobi", fiatConverter, commonAPI, config),
: ExchangePublic(ExchangeNameEnum::huobi, fiatConverter, commonAPI, config),
_curlHandle(kURLBases, config.metricGatewayPtr(), permanentCurlOptionsBuilder().build(), config.getRunMode()),
_healthCheckCurlHandle(
kHealthCheckBaseUrl, config.metricGatewayPtr(),
Expand Down Expand Up @@ -112,21 +113,21 @@ bool HuobiPublic::healthCheck() {
json::container::parse(_healthCheckCurlHandle.query("/api/v2/summary.json", CurlOptions(HttpRequestType::kGet)),
nullptr, kAllowExceptions);
if (result.is_discarded()) {
log::error("{} health check response is badly formatted", _name);
log::error("{} health check response is badly formatted", name());
return false;
}
auto statusIt = result.find("status");
if (statusIt == result.end()) {
log::error("Unexpected answer from {} status: {}", _name, result.dump());
log::error("Unexpected answer from {} status: {}", name(), result.dump());
return false;
}
auto descriptionIt = statusIt->find("description");
if (descriptionIt == statusIt->end()) {
log::error("Unexpected answer from {} status: {}", _name, statusIt->dump());
log::error("Unexpected answer from {} status: {}", name(), statusIt->dump());
return false;
}
std::string_view statusStr = descriptionIt->get<std::string_view>();
log::info("{} status: {}", _name, statusStr);
log::info("{} status: {}", name(), statusStr);
auto incidentsIt = result.find("incidents");
return incidentsIt != result.end() && incidentsIt->empty();
}
Expand Down Expand Up @@ -291,13 +292,13 @@ MonetaryAmountByCurrencySet HuobiPublic::queryWithdrawalFees() {
if (withdrawFeeTypeStr == "fixed") {
std::string_view withdrawFeeStr = chainDetail["transactFeeWithdraw"].get<std::string_view>();
MonetaryAmount withdrawFee(withdrawFeeStr, cur);
log::trace("Retrieved {} withdrawal fee {}", _name, withdrawFee);
log::trace("Retrieved {} withdrawal fee {}", name(), withdrawFee);
fees.push_back(withdrawFee);
} else if (withdrawFeeTypeStr == "rate") {
log::debug("Unsupported rate withdraw fee for {}", _name);
log::debug("Unsupported rate withdraw fee for {}", name());
fees.emplace_back(0, cur);
} else if (withdrawFeeTypeStr == "circulated") {
log::debug("Unsupported circulated withdraw fee for {}", _name);
log::debug("Unsupported circulated withdraw fee for {}", name());
fees.emplace_back(0, cur);
}
}
Expand All @@ -306,11 +307,11 @@ MonetaryAmountByCurrencySet HuobiPublic::queryWithdrawalFees() {
break;
}
if (!foundChainWithSameName) {
log::debug("Cannot find '{}' main chain in {}, discarding currency", curStr, _name);
log::debug("Cannot find '{}' main chain in {}, discarding currency", curStr, name());
}
}

log::info("Retrieved {} withdrawal fees for {} coins", _name, fees.size());
log::info("Retrieved {} withdrawal fees for {} coins", name(), fees.size());
return MonetaryAmountByCurrencySet(std::move(fees));
}

Expand Down
11 changes: 6 additions & 5 deletions src/api/exchanges/src/krakenpublicapi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

#include "apiquerytypeenum.hpp"
#include "cachedresult.hpp"
#include "cct_const.hpp"
#include "cct_exception.hpp"
#include "cct_json-container.hpp"
#include "cct_log.hpp"
Expand Down Expand Up @@ -98,7 +99,7 @@ bool CheckCurrencyExchange(std::string_view krakenEntryCurrencyCode, std::string
} // namespace

KrakenPublic::KrakenPublic(const CoincenterInfo& config, FiatConverter& fiatConverter, CommonAPI& commonAPI)
: ExchangePublic(kExchangeName, fiatConverter, commonAPI, config),
: ExchangePublic(ExchangeNameEnum::kraken, fiatConverter, commonAPI, config),
_curlHandle(kUrlBase, config.metricGatewayPtr(), permanentCurlOptionsBuilder().build(), config.getRunMode()),
_tradableCurrenciesCache(
CachedResultOptions(exchangeConfig().getAPICallUpdateFrequency(kCurrencies), _cachedResultVault), config,
Expand All @@ -120,21 +121,21 @@ bool KrakenPublic::healthCheck() {
json::container::parse(_curlHandle.query("/public/SystemStatus", CurlOptions(HttpRequestType::kGet)));
auto errorIt = result.find("error");
if (errorIt != result.end() && !errorIt->empty()) {
log::error("Error in {} status: {}", _name, errorIt->dump());
log::error("Error in {} status: {}", name(), errorIt->dump());
return false;
}
auto resultIt = result.find("result");
if (resultIt == result.end()) {
log::error("Unexpected answer from {} status: {}", _name, result.dump());
log::error("Unexpected answer from {} status: {}", name(), result.dump());
return false;
}
auto statusIt = resultIt->find("status");
if (statusIt == resultIt->end()) {
log::error("Unexpected answer from {} status: {}", _name, resultIt->dump());
log::error("Unexpected answer from {} status: {}", name(), resultIt->dump());
return false;
}
std::string_view statusStr = statusIt->get<std::string_view>();
log::info("{} status: {}", _name, statusStr);
log::info("{} status: {}", name(), statusStr);
return statusStr == "online";
}

Expand Down
Loading

0 comments on commit defaff8

Please sign in to comment.