From 225ba7d4b302750ecf32fdfb11604797333b0a2d Mon Sep 17 00:00:00 2001 From: Bushstar Date: Fri, 10 Feb 2023 13:31:59 +0000 Subject: [PATCH 1/3] Replace Require strings with lambdas --- src/amount.h | 4 +- src/chainparams.cpp | 8 +- src/masternodes/accounts.cpp | 8 +- src/masternodes/govvariables/attributes.cpp | 152 +++++++++--------- .../govvariables/icx_takerfee_per_btc.cpp | 2 +- .../govvariables/loan_daily_reward.cpp | 2 +- .../govvariables/loan_liquidation_penalty.cpp | 4 +- src/masternodes/govvariables/loan_splits.cpp | 14 +- .../govvariables/lp_daily_dfi_reward.cpp | 2 +- src/masternodes/govvariables/lp_splits.cpp | 10 +- .../govvariables/oracle_block_interval.cpp | 6 +- .../govvariables/oracle_deviation.cpp | 4 +- src/masternodes/gv.cpp | 2 +- src/masternodes/incentivefunding.cpp | 6 +- src/masternodes/loan.cpp | 31 ++-- src/masternodes/masternodes.cpp | 28 ++-- src/masternodes/oracles.cpp | 36 ++--- src/masternodes/poolpairs.cpp | 43 +++-- src/masternodes/rpc_oracles.cpp | 4 +- src/masternodes/tokens.cpp | 34 ++-- src/masternodes/validation.cpp | 8 +- src/masternodes/vault.cpp | 6 +- src/rpc/rawtransaction_util.cpp | 2 +- 23 files changed, 205 insertions(+), 211 deletions(-) diff --git a/src/amount.h b/src/amount.h index aba91174928..b8451eece57 100644 --- a/src/amount.h +++ b/src/amount.h @@ -92,7 +92,7 @@ typedef std::map TAmounts; inline ResVal SafeAdd(CAmount _a, CAmount _b) { // check limits - Require(_a >= 0 && _b >= 0, "negative amount"); + Require(_a >= 0 && _b >= 0, []{ return "negative amount"; }); // convert to unsigned, because signed overflow is UB const uint64_t a = (uint64_t) _a; @@ -101,7 +101,7 @@ inline ResVal SafeAdd(CAmount _a, CAmount _b) { const uint64_t sum = a + b; // check overflow - Require((sum - a) == b && (uint64_t)std::numeric_limits::max() >= sum, "overflow"); + Require((sum - a) == b && (uint64_t)std::numeric_limits::max() >= sum, []{ return "overflow"; }); return {(CAmount) sum, Res::Ok()}; } diff --git a/src/chainparams.cpp b/src/chainparams.cpp index ca5e9084a1d..b99efd22696 100644 --- a/src/chainparams.cpp +++ b/src/chainparams.cpp @@ -1189,7 +1189,7 @@ void ClearCheckpoints(CChainParams ¶ms) { Res UpdateCheckpointsFromFile(CChainParams ¶ms, const std::string &fileName) { std::ifstream file(fileName); - Require(file.good(), "Could not read %s. Ensure it exists and has read permissions", fileName); + Require(file.good(), [=]{ return strprintf("Could not read %s. Ensure it exists and has read permissions", fileName); }); ClearCheckpoints(params); @@ -1201,13 +1201,13 @@ Res UpdateCheckpointsFromFile(CChainParams ¶ms, const std::string &fileName) std::istringstream iss(trimmed); std::string hashStr, heightStr; - Require((iss >> heightStr >> hashStr), "Error parsing line %s", trimmed); + Require((iss >> heightStr >> hashStr), [=]{ return strprintf("Error parsing line %s", trimmed); }); uint256 hash; - Require(ParseHashStr(hashStr, hash), "Invalid hash: %s", hashStr); + Require(ParseHashStr(hashStr, hash), [=]{ return strprintf("Invalid hash: %s", hashStr); }); int32_t height; - Require(ParseInt32(heightStr, &height), "Invalid height: %s", heightStr); + Require(ParseInt32(heightStr, &height), [=]{ return strprintf("Invalid height: %s", heightStr); }); params.checkpointData.mapCheckpoints[height] = hash; } diff --git a/src/masternodes/accounts.cpp b/src/masternodes/accounts.cpp index df00f43a36b..36f331682e0 100644 --- a/src/masternodes/accounts.cpp +++ b/src/masternodes/accounts.cpp @@ -80,7 +80,7 @@ uint32_t CAccountsView::GetBalancesHeight(const CScript &owner) { } Res CAccountsView::StoreFuturesUserValues(const CFuturesUserKey &key, const CFuturesUserValue &futures) { - Require(WriteBy(key, futures), "Failed to store futures"); + Require(WriteBy(key, futures), []{ return "Failed to store futures"; }); return Res::Ok(); } @@ -91,12 +91,12 @@ void CAccountsView::ForEachFuturesUserValues( } Res CAccountsView::EraseFuturesUserValues(const CFuturesUserKey &key) { - Require(EraseBy(key), "Failed to erase futures"); + Require(EraseBy(key), [=]{ return "Failed to erase futures"; }); return Res::Ok(); } Res CAccountsView::StoreFuturesDUSD(const CFuturesUserKey &key, const CAmount &amount) { - Require(WriteBy(key, amount), "Failed to store futures"); + Require(WriteBy(key, amount), []{ return "Failed to store futures"; }); return Res::Ok(); } @@ -106,6 +106,6 @@ void CAccountsView::ForEachFuturesDUSD(std::function(key), "Failed to erase futures"); + Require(EraseBy(key), []{ return "Failed to erase futures"; }); return Res::Ok(); } diff --git a/src/masternodes/govvariables/attributes.cpp b/src/masternodes/govvariables/attributes.cpp index 91b3f2f798d..889d5b4e721 100644 --- a/src/masternodes/govvariables/attributes.cpp +++ b/src/masternodes/govvariables/attributes.cpp @@ -309,13 +309,13 @@ const std::map> &ATTRIBUTES::displayKeys static ResVal VerifyInt32(const std::string &str) { int32_t int32; - Require(ParseInt32(str, &int32), "Value must be an integer"); + Require(ParseInt32(str, &int32), []{ return "Value must be an integer"; }); return {int32, Res::Ok()}; } static ResVal VerifyPositiveInt32(const std::string &str) { int32_t int32; - Require(ParseInt32(str, &int32) && int32 >= 0, "Value must be a positive integer"); + Require(ParseInt32(str, &int32) && int32 >= 0, []{ return "Value must be a positive integer"; }); return {int32, Res::Ok()}; } @@ -329,19 +329,19 @@ static ResVal VerifyUInt32(const std::string &str) { static ResVal VerifyInt64(const std::string &str) { CAmount int64; - Require(ParseInt64(str, &int64) && int64 >= 0, "Value must be a positive integer"); + Require(ParseInt64(str, &int64) && int64 >= 0, []{ return "Value must be a positive integer"; }); return {int64, Res::Ok()}; } static ResVal VerifyFloat(const std::string &str) { CAmount amount = 0; - Require(ParseFixedPoint(str, 8, &amount), "Amount must be a valid number"); + Require(ParseFixedPoint(str, 8, &amount), []{ return "Amount must be a valid number"; }); return {amount, Res::Ok()}; } ResVal VerifyPositiveFloat(const std::string &str) { CAmount amount = 0; - Require(ParseFixedPoint(str, 8, &amount) && amount >= 0, "Amount must be a positive value"); + Require(ParseFixedPoint(str, 8, &amount) && amount >= 0, []{ return "Amount must be a positive value"; }); return {amount, Res::Ok()}; } @@ -382,13 +382,13 @@ static ResVal VerifyBool(const std::string &str) { static ResVal VerifySplit(const std::string &str) { OracleSplits splits; const auto pairs = KeyBreaker(str); - Require(pairs.size() == 2, "Two int values expected for split in id/mutliplier"); + Require(pairs.size() == 2, []{ return "Two int values expected for split in id/mutliplier"; }); const auto resId = VerifyPositiveInt32(pairs[0]); Require(resId); const auto resMultiplier = VerifyInt32(pairs[1]); Require(resMultiplier); - Require(*resMultiplier != 0, "Mutliplier cannot be zero"); + Require(*resMultiplier != 0, []{ return "Mutliplier cannot be zero"; }); splits[*resId] = *resMultiplier; @@ -435,11 +435,11 @@ static ResVal VerifyMember(const UniValue &array) { static ResVal VerifyCurrencyPair(const std::string &str) { const auto value = KeyBreaker(str); - Require(value.size() == 2, "Exactly two entires expected for currency pair"); + Require(value.size() == 2, []{ return "Exactly two entires expected for currency pair"; }); auto token = trim_all_ws(value[0]).substr(0, CToken::MAX_TOKEN_SYMBOL_LENGTH); auto currency = trim_all_ws(value[1]).substr(0, CToken::MAX_TOKEN_SYMBOL_LENGTH); - Require(!token.empty() && !currency.empty(), "Empty token / currency"); + Require(!token.empty() && !currency.empty(), []{ return "Empty token / currency"; }); return { CTokenCurrencyPair{token, currency}, Res::Ok() @@ -451,7 +451,7 @@ static std::set dirSet{"both", "in", "out"}; static ResVal VerifyFeeDirection(const std::string &str) { auto lowerStr = ToLower(str); const auto it = dirSet.find(lowerStr); - Require(it != dirSet.end(), "Fee direction value must be both, in or out"); + Require(it != dirSet.end(), []{ return "Fee direction value must be both, in or out"; }); return {CFeeDir{static_cast(std::distance(dirSet.begin(), it))}, Res::Ok()}; } @@ -666,41 +666,41 @@ void TrackLiveBalances(CCustomCSView &mnview, const CBalances &balances, const u Res ATTRIBUTES::ProcessVariable(const std::string &key, const std::optional &value, std::function applyVariable) { - Require(key.size() <= 128, "Identifier exceeds maximum length (128)"); + Require(key.size() <= 128, []{ return "Identifier exceeds maximum length (128)"; }); const auto keys = KeyBreaker(key); - Require(!keys.empty() && !keys[0].empty(), "Empty version"); + Require(!keys.empty() && !keys[0].empty(), []{ return "Empty version"; }); auto iver = allowedVersions().find(keys[0]); - Require(iver != allowedVersions().end(), "Unsupported version"); + Require(iver != allowedVersions().end(), []{ return "Unsupported version"; }); auto version = iver->second; - Require(version == VersionTypes::v0, "Unsupported version"); + Require(version == VersionTypes::v0, []{ return "Unsupported version"; }); Require(keys.size() >= 4 && !keys[1].empty() && !keys[2].empty() && !keys[3].empty(), - "Incorrect key for . Object of ['//ID/','value'] expected"); + []{ return "Incorrect key for . Object of ['//ID/','value'] expected"; }); auto itype = allowedTypes().find(keys[1]); - Require(itype != allowedTypes().end(), ::ShowError("type", allowedTypes())); + Require(itype != allowedTypes().end(), [=]{ return ::ShowError("type", allowedTypes()); }); const auto type = itype->second; uint32_t typeId{0}; if (type == AttributeTypes::Param) { auto id = allowedParamIDs().find(keys[2]); - Require(id != allowedParamIDs().end(), ::ShowError("param", allowedParamIDs())); + Require(id != allowedParamIDs().end(), [=]{ return ::ShowError("param", allowedParamIDs()); }); typeId = id->second; } else if (type == AttributeTypes::Locks) { auto id = allowedLocksIDs().find(keys[2]); - Require(id != allowedLocksIDs().end(), ::ShowError("locks", allowedLocksIDs())); + Require(id != allowedLocksIDs().end(), [=]{ return ::ShowError("locks", allowedLocksIDs()); }); typeId = id->second; } else if (type == AttributeTypes::Oracles) { auto id = allowedOracleIDs().find(keys[2]); - Require(id != allowedOracleIDs().end(), ::ShowError("oracles", allowedOracleIDs())); + Require(id != allowedOracleIDs().end(), [=]{ return ::ShowError("oracles", allowedOracleIDs()); }); typeId = id->second; } else if (type == AttributeTypes::Governance) { auto id = allowedGovernanceIDs().find(keys[2]); - Require(id != allowedGovernanceIDs().end(), ::ShowError("governance", allowedGovernanceIDs())); + Require(id != allowedGovernanceIDs().end(), [=]{ return ::ShowError("governance", allowedGovernanceIDs()); }); typeId = id->second; } else { auto id = VerifyInt32(keys[2]); @@ -723,7 +723,7 @@ Res ATTRIBUTES::ProcessVariable(const std::string &key, } } else { auto ikey = allowedKeys().find(type); - Require(ikey != allowedKeys().end(), "Unsupported type {%d}", type); + Require(ikey != allowedKeys().end(), [=]{ return strprintf("Unsupported type {%d}", type); }); // Alias of reward_pct in Export. if (keys[3] == "fee_pct") { @@ -731,7 +731,7 @@ Res ATTRIBUTES::ProcessVariable(const std::string &key, } itype = ikey->second.find(keys[3]); - Require(itype != ikey->second.end(), ::ShowError("key", ikey->second)); + Require(itype != ikey->second.end(), [=]{ return ::ShowError("key", ikey->second); }); typeKey = itype->second; @@ -755,8 +755,8 @@ Res ATTRIBUTES::ProcessVariable(const std::string &key, } } else if (typeId == ParamIDs::DFIP2206A) { Require(typeKey == DFIPKeys::DUSDInterestBurn || typeKey == DFIPKeys::DUSDLoanBurn, - "Unsupported type for DFIP2206A {%d}", - typeKey); + [=]{ return strprintf("Unsupported type for DFIP2206A {%d}", + typeKey); }); } else if (typeId == ParamIDs::Feature) { if (typeKey != DFIPKeys::GovUnset && typeKey != DFIPKeys::GovFoundation && typeKey != DFIPKeys::MNSetRewardAddress && typeKey != DFIPKeys::MNSetOperatorAddress && @@ -790,12 +790,12 @@ Res ATTRIBUTES::ProcessVariable(const std::string &key, } if (attrV0.IsExtendedSize()) { - Require(keys.size() == 5 && !keys[4].empty(), "Exact 5 keys are required {%d}", keys.size()); + Require(keys.size() == 5 && !keys[4].empty(), [=]{ return strprintf("Exact 5 keys are required {%d}", keys.size()); }); auto id = VerifyInt32(keys[4]); Require(id); attrV0.keyId = *id.val; } else { - Require(keys.size() == 4, "Exact 4 keys are required {%d}", keys.size()); + Require(keys.size() == 4, [=]{ return strprintf("Exact 4 keys are required {%d}", keys.size()); }); } if (!value) { @@ -951,7 +951,7 @@ Res ATTRIBUTES::RefundFuturesDUSD(CCustomCSView &mnview, const uint32_t height) } Res ATTRIBUTES::Import(const UniValue &val) { - Require(val.isObject(), "Object of values expected"); + Require(val.isObject(), []{ return "Object of values expected"; }); std::map objMap; val.getObjMap(objMap); @@ -1231,72 +1231,72 @@ UniValue ATTRIBUTES::Export() const { Res ATTRIBUTES::Validate(const CCustomCSView &view) const { Require(view.GetLastHeight() >= Params().GetConsensus().FortCanningHillHeight, - "Cannot be set before FortCanningHill"); + []{ return "Cannot be set before FortCanningHill"; }); for (const auto &[key, value] : attributes) { const auto attrV0 = std::get_if(&key); - Require(attrV0, "Unsupported version"); + Require(attrV0, []{ return "Unsupported version"; }); switch (attrV0->type) { case AttributeTypes::Token: switch (attrV0->key) { case TokenKeys::LoanPaybackCollateral: Require(view.GetLastHeight() >= Params().GetConsensus().FortCanningEpilogueHeight, - "Cannot be set before FortCanningEpilogue"); + []{ return "Cannot be set before FortCanningEpilogue"; }); [[fallthrough]]; case TokenKeys::PaybackDFI: case TokenKeys::PaybackDFIFeePCT: - Require(view.GetLoanTokenByID({attrV0->typeId}), "No such loan token (%d)", attrV0->typeId); + Require(view.GetLoanTokenByID({attrV0->typeId}), [=]{ return strprintf("No such loan token (%d)", attrV0->typeId); }); break; case TokenKeys::LoanPayback: case TokenKeys::LoanPaybackFeePCT: Require(view.GetLastHeight() >= Params().GetConsensus().FortCanningRoadHeight, - "Cannot be set before FortCanningRoad"); + []{ return "Cannot be set before FortCanningRoad"; }); Require( view.GetLoanTokenByID(DCT_ID{attrV0->typeId}), "No such loan token (%d)", attrV0->typeId); - Require(view.GetToken(DCT_ID{attrV0->keyId}), "No such token (%d)", attrV0->keyId); + Require(view.GetToken(DCT_ID{attrV0->keyId}), [=]{ return strprintf("No such token (%d)", attrV0->keyId); }); break; case TokenKeys::DexInFeePct: case TokenKeys::DexOutFeePct: Require(view.GetLastHeight() >= Params().GetConsensus().FortCanningRoadHeight, - "Cannot be set before FortCanningRoad"); - Require(view.GetToken(DCT_ID{attrV0->typeId}), "No such token (%d)", attrV0->typeId); + []{ return "Cannot be set before FortCanningRoad"; }); + Require(view.GetToken(DCT_ID{attrV0->typeId}), [=]{ return strprintf("No such token (%d)", attrV0->typeId); }); break; case TokenKeys::LoanCollateralFactor: if (view.GetLastHeight() < Params().GetConsensus().FortCanningEpilogueHeight) { const auto amount = std::get_if(&value); if (amount) - Require(*amount <= COIN, "Percentage exceeds 100%%"); + Require(*amount <= COIN, []{ return "Percentage exceeds 100%%"; }); } [[fallthrough]]; case TokenKeys::LoanMintingInterest: if (view.GetLastHeight() < Params().GetConsensus().FortCanningGreatWorldHeight) { const auto amount = std::get_if(&value); if (amount) - Require(*amount >= 0, "Amount must be a positive value"); + Require(*amount >= 0, []{ return "Amount must be a positive value"; }); } [[fallthrough]]; case TokenKeys::LoanCollateralEnabled: case TokenKeys::LoanMintingEnabled: { Require(view.GetLastHeight() >= Params().GetConsensus().FortCanningCrunchHeight, - "Cannot be set before FortCanningCrunch"); - Require(VerifyToken(view, attrV0->typeId), "No such token (%d)", attrV0->typeId); + []{ return "Cannot be set before FortCanningCrunch"; }); + Require(VerifyToken(view, attrV0->typeId), [=]{ return strprintf("No such token (%d)", attrV0->typeId); }); CDataStructureV0 intervalPriceKey{ AttributeTypes::Token, attrV0->typeId, TokenKeys::FixedIntervalPriceId}; Require(!(GetValue(intervalPriceKey, CTokenCurrencyPair{}) == CTokenCurrencyPair{}), - "Fixed interval price currency pair must be set first"); + []{ return "Fixed interval price currency pair must be set first"; }); break; } case TokenKeys::FixedIntervalPriceId: Require(view.GetLastHeight() >= Params().GetConsensus().FortCanningCrunchHeight, - "Cannot be set before FortCanningCrunch"); - Require(VerifyToken(view, attrV0->typeId), "No such token (%d)", attrV0->typeId); + []{ return "Cannot be set before FortCanningCrunch"; }); + Require(VerifyToken(view, attrV0->typeId), [=]{ return strprintf("No such token (%d)", attrV0->typeId); }); break; case TokenKeys::DFIP2203Enabled: Require(view.GetLastHeight() >= Params().GetConsensus().FortCanningRoadHeight, - "Cannot be set before FortCanningRoad"); + []{ return "Cannot be set before FortCanningRoad"; }); Require( - view.GetLoanTokenByID(DCT_ID{attrV0->typeId}), "No such loan token (%d)", attrV0->typeId); + view.GetLoanTokenByID(DCT_ID{attrV0->typeId}), [=]{ return strprintf("No such loan token (%d)", attrV0->typeId); }); break; case TokenKeys::Ascendant: case TokenKeys::Descendant: @@ -1355,19 +1355,19 @@ Res ATTRIBUTES::Validate(const CCustomCSView &view) const { case AttributeTypes::Oracles: Require(view.GetLastHeight() >= Params().GetConsensus().FortCanningCrunchHeight, - "Cannot be set before FortCanningCrunch"); + []{ return "Cannot be set before FortCanningCrunch"; }); if (attrV0->typeId == OracleIDs::Splits) { const auto splitMap = std::get_if(&value); - Require(splitMap, "Unsupported value"); + Require(splitMap, []{ return "Unsupported value"; }); for (const auto &[tokenId, multipler] : *splitMap) { - Require(tokenId != 0, "Tokenised DFI cannot be split"); - Require(!view.HasPoolPair(DCT_ID{tokenId}), "Pool tokens cannot be split"); + Require(tokenId != 0, []{ return "Tokenised DFI cannot be split"; }); + Require(!view.HasPoolPair(DCT_ID{tokenId}), []{ return "Pool tokens cannot be split"; }); const auto token = view.GetToken(DCT_ID{tokenId}); - Require(token, "Token (%d) does not exist", tokenId); - Require(token->IsDAT(), "Only DATs can be split"); + Require(token, [tokenId=tokenId]{ return strprintf("Token (%d) does not exist", tokenId); }); + Require(token->IsDAT(), []{ return "Only DATs can be split"; }); Require( - view.GetLoanTokenByID(DCT_ID{tokenId}).has_value(), "No loan token with id (%d)", tokenId); + view.GetLoanTokenByID(DCT_ID{tokenId}).has_value(), [tokenId=tokenId]{ return strprintf("No loan token with id (%d)", tokenId); }); } } else { return Res::Err("Unsupported key"); @@ -1378,13 +1378,13 @@ Res ATTRIBUTES::Validate(const CCustomCSView &view) const { switch (attrV0->key) { case PoolKeys::TokenAFeePCT: case PoolKeys::TokenBFeePCT: - Require(view.GetPoolPair({attrV0->typeId}), "No such pool (%d)", attrV0->typeId); + Require(view.GetPoolPair({attrV0->typeId}), [=]{ return strprintf("No such pool (%d)", attrV0->typeId); }); break; case PoolKeys::TokenAFeeDir: case PoolKeys::TokenBFeeDir: Require(view.GetLastHeight() >= Params().GetConsensus().FortCanningSpringHeight, - "Cannot be set before FortCanningSpringHeight"); - Require(view.GetPoolPair({attrV0->typeId}), "No such pool (%d)", attrV0->typeId); + []{ return "Cannot be set before FortCanningSpringHeight"; }); + Require(view.GetPoolPair({attrV0->typeId}), [=]{ return strprintf("No such pool (%d)", attrV0->typeId); }); break; default: return Res::Err("Unsupported key"); @@ -1412,7 +1412,7 @@ Res ATTRIBUTES::Validate(const CCustomCSView &view) const { } } else if (attrV0->typeId == ParamIDs::DFIP2203) { Require(view.GetLastHeight() >= Params().GetConsensus().FortCanningRoadHeight, - "Cannot be set before FortCanningRoadHeight"); + []{ return "Cannot be set before FortCanningRoadHeight"; }); } else if (attrV0->typeId != ParamIDs::DFIP2201) { return Res::Err("Unrecognised param id"); } @@ -1458,11 +1458,11 @@ Res ATTRIBUTES::Apply(CCustomCSView &mnview, const uint32_t height) { if (attrV0->key == PoolKeys::TokenAFeePCT || attrV0->key == PoolKeys::TokenBFeePCT) { auto poolId = DCT_ID{attrV0->typeId}; auto pool = mnview.GetPoolPair(poolId); - Require(pool, "No such pool (%d)", poolId.v); + Require(pool, [=]{ return strprintf("No such pool (%d)", poolId.v); }); auto tokenId = attrV0->key == PoolKeys::TokenAFeePCT ? pool->idTokenA : pool->idTokenB; const auto valuePct = std::get_if(&attribute.second); - Require(valuePct, "Unexpected type"); + Require(valuePct, []{ return "Unexpected type"; }); if (auto res = mnview.SetDexFeePct(poolId, tokenId, *valuePct); !res) { return res; } @@ -1474,7 +1474,7 @@ Res ATTRIBUTES::Apply(CCustomCSView &mnview, const uint32_t height) { std::swap(tokenA, tokenB); } const auto valuePct = std::get_if(&attribute.second); - Require(valuePct, "Unexpected type"); + Require(valuePct, []{ return "Unexpected type"; }); if (auto res = mnview.SetDexFeePct(tokenA, tokenB, *valuePct); !res) { return res; } @@ -1504,14 +1504,14 @@ Res ATTRIBUTES::Apply(CCustomCSView &mnview, const uint32_t height) { } } else if (attrV0->key == TokenKeys::DFIP2203Enabled) { const auto value = std::get_if(&attribute.second); - Require(value, "Unexpected type"); + Require(value, []{ return "Unexpected type"; }); if (*value) { continue; } const auto token = mnview.GetLoanTokenByID(DCT_ID{attrV0->typeId}); - Require(token, "No such loan token (%d)", attrV0->typeId); + Require(token, [=]{ return strprintf("No such loan token (%d)", attrV0->typeId); }); // Special case: DUSD will be used as a source for swaps but will // be set as disabled for Future swap destination. @@ -1524,7 +1524,7 @@ Res ATTRIBUTES::Apply(CCustomCSView &mnview, const uint32_t height) { if (height >= static_cast(Params().GetConsensus().FortCanningGreatWorldHeight) && interestTokens.count(attrV0->typeId)) { const auto tokenInterest = std::get_if(&attribute.second); - Require(tokenInterest, "Unexpected type"); + Require(tokenInterest, []{ return "Unexpected type"; }); std::set affectedVaults; mnview.ForEachLoanTokenAmount([&](const CVaultId &vaultId, const CBalances &balances) { @@ -1565,10 +1565,10 @@ Res ATTRIBUTES::Apply(CCustomCSView &mnview, const uint32_t height) { } } else { const auto factor = std::get_if(&attribute.second); - Require(factor, "Unexpected type"); - Require(*factor < *ratio.begin() * CENT, + Require(factor, []{ return "Unexpected type"; }); + Require(*factor < *ratio.begin() * CENT, [=]{ return strprintf( "Factor cannot be more than or equal to the lowest scheme rate of %d\n", - GetDecimaleString(*ratio.begin() * CENT)); + GetDecimaleString(*ratio.begin() * CENT)); }); } } } @@ -1576,7 +1576,7 @@ Res ATTRIBUTES::Apply(CCustomCSView &mnview, const uint32_t height) { if (attrV0->typeId == ParamIDs::DFIP2203) { if (attrV0->key == DFIPKeys::Active) { const auto value = std::get_if(&attribute.second); - Require(value, "Unexpected type"); + Require(value, []{ return "Unexpected type"; }); if (*value) { continue; @@ -1591,12 +1591,12 @@ Res ATTRIBUTES::Apply(CCustomCSView &mnview, const uint32_t height) { } CDataStructureV0 activeKey{AttributeTypes::Param, ParamIDs::DFIP2203, DFIPKeys::Active}; - Require(!GetValue(activeKey, false), "Cannot set block period while DFIP2203 is active"); + Require(!GetValue(activeKey, false), []{ return "Cannot set block period while DFIP2203 is active"; }); } } else if (attrV0->typeId == ParamIDs::DFIP2206F) { if (attrV0->key == DFIPKeys::Active) { const auto value = std::get_if(&attribute.second); - Require(value, "Unexpected type"); + Require(value, []{ return "Unexpected type"; }); if (*value) { continue; @@ -1611,19 +1611,19 @@ Res ATTRIBUTES::Apply(CCustomCSView &mnview, const uint32_t height) { } CDataStructureV0 activeKey{AttributeTypes::Param, ParamIDs::DFIP2206F, DFIPKeys::Active}; - Require(!GetValue(activeKey, false), "Cannot set block period while DFIP2206F is active"); + Require(!GetValue(activeKey, false), []{ return "Cannot set block period while DFIP2206F is active"; }); } } } else if (attrV0->type == AttributeTypes::Oracles && attrV0->typeId == OracleIDs::Splits) { const auto value = std::get_if(&attribute.second); - Require(value, "Unsupported value"); + Require(value, []{ return "Unsupported value"; }); for (const auto split : tokenSplits) { if (auto it{value->find(split)}; it == value->end()) { continue; } - Require(attrV0->key > height, "Cannot be set at or below current height"); + Require(attrV0->key > height, []{ return "Cannot be set at or below current height"; }); CDataStructureV0 lockKey{AttributeTypes::Locks, ParamIDs::TokenID, split}; if (GetValue(lockKey, false)) { @@ -1631,15 +1631,15 @@ Res ATTRIBUTES::Apply(CCustomCSView &mnview, const uint32_t height) { } Require( - mnview.GetLoanTokenByID(DCT_ID{split}).has_value(), "Auto lock. No loan token with id (%d)", split); + mnview.GetLoanTokenByID(DCT_ID{split}).has_value(), [=]{ return strprintf("Auto lock. No loan token with id (%d)", split); }); const auto startHeight = attrV0->key - Params().GetConsensus().blocksPerDay() / 2; if (height < startHeight) { auto var = GovVariable::Create("ATTRIBUTES"); - Require(var, "Failed to create Gov var for lock"); + Require(var, []{ return "Failed to create Gov var for lock"; }); auto govVar = std::dynamic_pointer_cast(var); - Require(govVar, "Failed to cast Gov var to ATTRIBUTES"); + Require(govVar, []{ return "Failed to cast Gov var to ATTRIBUTES"; }); govVar->attributes[lockKey] = true; CGovernanceHeightMessage lock; @@ -1664,12 +1664,12 @@ Res ATTRIBUTES::Erase(CCustomCSView &mnview, uint32_t, const std::vectortype != AttributeTypes::Live, "Live attribute cannot be deleted"); - Require(EraseKey(attribute), "Attribute {%d} not exists", attrV0->type); + Require(attrV0->type != AttributeTypes::Live, []{ return "Live attribute cannot be deleted"; }); + Require(EraseKey(attribute), [=]{ return strprintf("Attribute {%d} not exists", attrV0->type); }); if (attrV0->type == AttributeTypes::Poolpairs) { auto poolId = DCT_ID{attrV0->typeId}; auto pool = mnview.GetPoolPair(poolId); - Require(pool, "No such pool (%d)", poolId.v); + Require(pool, [=]{ return strprintf("No such pool (%d)", poolId.v); }); auto tokenId = attrV0->key == PoolKeys::TokenAFeePCT ? pool->idTokenA : pool->idTokenB; return mnview.EraseDexFeePct(poolId, tokenId); diff --git a/src/masternodes/govvariables/icx_takerfee_per_btc.cpp b/src/masternodes/govvariables/icx_takerfee_per_btc.cpp index a11f7b1ece8..8319d6c4efc 100644 --- a/src/masternodes/govvariables/icx_takerfee_per_btc.cpp +++ b/src/masternodes/govvariables/icx_takerfee_per_btc.cpp @@ -21,7 +21,7 @@ UniValue ICX_TAKERFEE_PER_BTC::Export() const { } Res ICX_TAKERFEE_PER_BTC::Validate(const CCustomCSView &mnview) const { - Require(takerFeePerBTC > 0, "takerFeePerBTC cannot be 0 or less"); + Require(takerFeePerBTC > 0, []{ return "takerFeePerBTC cannot be 0 or less"; }); return Res::Ok(); } diff --git a/src/masternodes/govvariables/loan_daily_reward.cpp b/src/masternodes/govvariables/loan_daily_reward.cpp index ce3889d97b9..a1553d736ea 100644 --- a/src/masternodes/govvariables/loan_daily_reward.cpp +++ b/src/masternodes/govvariables/loan_daily_reward.cpp @@ -22,7 +22,7 @@ UniValue LP_DAILY_LOAN_TOKEN_REWARD::Export() const { } Res LP_DAILY_LOAN_TOKEN_REWARD::Validate(const CCustomCSView &view) const { - Require(view.GetLastHeight() >= Params().GetConsensus().FortCanningHeight, "Cannot be set before FortCanning"); + Require(view.GetLastHeight() >= Params().GetConsensus().FortCanningHeight, []{ return "Cannot be set before FortCanning"; }); return Res::Err("Cannot be set manually."); } diff --git a/src/masternodes/govvariables/loan_liquidation_penalty.cpp b/src/masternodes/govvariables/loan_liquidation_penalty.cpp index abf78871c51..a5f7cfc5f35 100644 --- a/src/masternodes/govvariables/loan_liquidation_penalty.cpp +++ b/src/masternodes/govvariables/loan_liquidation_penalty.cpp @@ -22,8 +22,8 @@ UniValue LOAN_LIQUIDATION_PENALTY::Export() const { } Res LOAN_LIQUIDATION_PENALTY::Validate(const CCustomCSView &view) const { - Require(view.GetLastHeight() >= Params().GetConsensus().FortCanningHeight, "Cannot be set before FortCanning"); - Require(penalty >= COIN / 100, "Penalty cannot be less than 0.01 DFI"); + Require(view.GetLastHeight() >= Params().GetConsensus().FortCanningHeight, []{ return "Cannot be set before FortCanning"; }); + Require(penalty >= COIN / 100, []{ return "Penalty cannot be less than 0.01 DFI"; }); return Res::Ok(); } diff --git a/src/masternodes/govvariables/loan_splits.cpp b/src/masternodes/govvariables/loan_splits.cpp index 4fb6592bce6..6691b4d86b5 100644 --- a/src/masternodes/govvariables/loan_splits.cpp +++ b/src/masternodes/govvariables/loan_splits.cpp @@ -13,7 +13,7 @@ bool LP_LOAN_TOKEN_SPLITS::IsEmpty() const { } Res LP_LOAN_TOKEN_SPLITS::Import(const UniValue &val) { - Require(val.isObject(), "object of {poolId: rate,... } expected"); + Require(val.isObject(), []{ return "object of {poolId: rate,... } expected"; }); for (const std::string &key : val.getKeys()) { auto id = DCT_ID::FromString(key); @@ -32,20 +32,20 @@ UniValue LP_LOAN_TOKEN_SPLITS::Export() const { } Res LP_LOAN_TOKEN_SPLITS::Validate(const CCustomCSView &mnview) const { - Require(mnview.GetLastHeight() >= Params().GetConsensus().FortCanningHeight, "Cannot be set before FortCanning"); + Require(mnview.GetLastHeight() >= Params().GetConsensus().FortCanningHeight, []{ return "Cannot be set before FortCanning"; }); CAmount total{0}; for (const auto &kv : splits) { - Require(mnview.HasPoolPair(kv.first), "pool with id=%s not found", kv.first.ToString()); + Require(mnview.HasPoolPair(kv.first), [=]{ return strprintf("pool with id=%s not found", kv.first.ToString()); }); Require(kv.second >= 0 && kv.second <= COIN, - "wrong percentage for pool with id=%s, value = %s", - kv.first.ToString(), - std::to_string(kv.second)); + [=]{ return strprintf("wrong percentage for pool with id=%s, value = %s", + kv.first.ToString(), + std::to_string(kv.second)); }); total += kv.second; } - Require(total == COIN, "total = %d vs expected %d", total, COIN); + Require(total == COIN, [=]{ return strprintf("total = %d vs expected %d", total, COIN); }); return Res::Ok(); } diff --git a/src/masternodes/govvariables/lp_daily_dfi_reward.cpp b/src/masternodes/govvariables/lp_daily_dfi_reward.cpp index 955e864aefd..9f4e8d8f5d6 100644 --- a/src/masternodes/govvariables/lp_daily_dfi_reward.cpp +++ b/src/masternodes/govvariables/lp_daily_dfi_reward.cpp @@ -22,7 +22,7 @@ UniValue LP_DAILY_DFI_REWARD::Export() const { } Res LP_DAILY_DFI_REWARD::Validate(const CCustomCSView &view) const { - Require(view.GetLastHeight() < Params().GetConsensus().EunosHeight, "Cannot be set manually after Eunos hard fork"); + Require(view.GetLastHeight() < Params().GetConsensus().EunosHeight, []{ return "Cannot be set manually after Eunos hard fork"; }); // nothing to do return Res::Ok(); } diff --git a/src/masternodes/govvariables/lp_splits.cpp b/src/masternodes/govvariables/lp_splits.cpp index 1b113ecc61e..e99e10a9322 100644 --- a/src/masternodes/govvariables/lp_splits.cpp +++ b/src/masternodes/govvariables/lp_splits.cpp @@ -14,7 +14,7 @@ bool LP_SPLITS::IsEmpty() const { Res LP_SPLITS::Import(const UniValue &val) { Require(val.isObject(), - "object of {poolId: rate,... } expected"); /// throw here? cause "AmountFromValue" can throw! + []{ return "object of {poolId: rate,... } expected"; }); /// throw here? cause "AmountFromValue" can throw! for (const std::string &key : val.getKeys()) { auto id = DCT_ID::FromString(key); @@ -35,16 +35,14 @@ UniValue LP_SPLITS::Export() const { Res LP_SPLITS::Validate(const CCustomCSView &mnview) const { CAmount total{0}; for (const auto &[poolId, amount] : splits) { - Require(mnview.HasPoolPair(poolId), "pool with id=%s not found", poolId.ToString()); + Require(mnview.HasPoolPair(poolId), [poolId=poolId]{ return strprintf("pool with id=%s not found", poolId.ToString()); }); Require(amount >= 0 && amount <= COIN, - "wrong percentage for pool with id=%s, value = %s", - poolId.ToString(), - std::to_string(amount)); + [=, poolId=poolId]{ return strprintf("wrong percentage for pool with id=%s, value = %s", poolId.ToString(), std::to_string(amount)); }); total += amount; } - Require(total == COIN, "total = %d vs expected %d", total, COIN); + Require(total == COIN, [=]{ return strprintf("total = %d vs expected %d", total, COIN); }); return Res::Ok(); } diff --git a/src/masternodes/govvariables/oracle_block_interval.cpp b/src/masternodes/govvariables/oracle_block_interval.cpp index eef339da81f..ed4beba4ad2 100644 --- a/src/masternodes/govvariables/oracle_block_interval.cpp +++ b/src/masternodes/govvariables/oracle_block_interval.cpp @@ -13,7 +13,7 @@ bool ORACLE_BLOCK_INTERVAL::IsEmpty() const { } Res ORACLE_BLOCK_INTERVAL::Import(const UniValue &val) { - Require(val.isNum(), "Block interval amount is not a number"); + Require(val.isNum(), []{ return "Block interval amount is not a number"; }); blockInterval = val.get_int(); return Res::Ok(); @@ -24,8 +24,8 @@ UniValue ORACLE_BLOCK_INTERVAL::Export() const { } Res ORACLE_BLOCK_INTERVAL::Validate(const CCustomCSView &view) const { - Require(view.GetLastHeight() >= Params().GetConsensus().FortCanningHeight, "Cannot be set before FortCanning"); - Require(blockInterval > 0, "Block interval cannot be less than 1"); + Require(view.GetLastHeight() >= Params().GetConsensus().FortCanningHeight, []{ return "Cannot be set before FortCanning"; }); + Require(blockInterval > 0, []{ return "Block interval cannot be less than 1"; }); return Res::Ok(); } diff --git a/src/masternodes/govvariables/oracle_deviation.cpp b/src/masternodes/govvariables/oracle_deviation.cpp index cf28b8a2159..3156f059a76 100644 --- a/src/masternodes/govvariables/oracle_deviation.cpp +++ b/src/masternodes/govvariables/oracle_deviation.cpp @@ -22,8 +22,8 @@ UniValue ORACLE_DEVIATION::Export() const { } Res ORACLE_DEVIATION::Validate(const CCustomCSView &view) const { - Require(view.GetLastHeight() >= Params().GetConsensus().FortCanningHeight, "Cannot be set before FortCanning"); - Require(deviation >= COIN / 100, "Deviation cannot be less than 1 percent"); + Require(view.GetLastHeight() >= Params().GetConsensus().FortCanningHeight, []{ return "Cannot be set before FortCanning"; }); + Require(deviation >= COIN / 100, []{ return "Deviation cannot be less than 1 percent"; }); return Res::Ok(); } diff --git a/src/masternodes/gv.cpp b/src/masternodes/gv.cpp index b91af7126ca..02375a9f101 100644 --- a/src/masternodes/gv.cpp +++ b/src/masternodes/gv.cpp @@ -56,7 +56,7 @@ std::shared_ptr CGovView::GetVariable(const std::string &name) cons Res CGovView::SetStoredVariables(const std::set> &govVars, const uint32_t height) { for (auto &item : govVars) - Require(WriteBy(GovVarKey{height, item->GetName()}, *item), "Cannot write to DB"); + Require(WriteBy(GovVarKey{height, item->GetName()}, *item), []{ return "Cannot write to DB"; }); return Res::Ok(); } diff --git a/src/masternodes/incentivefunding.cpp b/src/masternodes/incentivefunding.cpp index 99705bc4dd5..204c7db110b 100644 --- a/src/masternodes/incentivefunding.cpp +++ b/src/masternodes/incentivefunding.cpp @@ -15,7 +15,7 @@ CAmount CCommunityBalancesView::GetCommunityBalance(CommunityAccountType account Res CCommunityBalancesView::SetCommunityBalance(CommunityAccountType account, CAmount amount) { // deny negative values on db level! - Require(amount >= 0, "negative amount"); + Require(amount >= 0, []{ return "negative amount"; }); WriteBy(static_cast(account), amount); return Res::Ok(); } @@ -42,8 +42,8 @@ Res CCommunityBalancesView::SubCommunityBalance(CommunityAccountType account, CA if (amount == 0) { return Res::Ok(); } - Require(amount > 0, "negative amount"); + Require(amount > 0, []{ return "negative amount"; }); CAmount oldBalance = GetCommunityBalance(account); - Require(oldBalance >= amount, "Amount %d is less than %d", oldBalance, amount); + Require(oldBalance >= amount, [=]{ return strprintf("Amount %d is less than %d", oldBalance, amount); }); return SetCommunityBalance(account, oldBalance - amount); } diff --git a/src/masternodes/loan.cpp b/src/masternodes/loan.cpp index beca57c2b22..714ab21c282 100644 --- a/src/masternodes/loan.cpp +++ b/src/masternodes/loan.cpp @@ -13,11 +13,12 @@ std::optional CLoanView::GetLoanCollater Res CLoanView::CreateLoanCollateralToken(const CLoanSetCollateralTokenImpl &collToken) { // this should not happen, but for sure Require(!GetLoanCollateralToken(collToken.creationTx), - "setCollateralToken with creation tx %s already exists!", - collToken.creationTx.GetHex()); + [=]{ return strprintf("setCollateralToken with creation tx %s already exists!", + collToken.creationTx.GetHex()); }); Require( - collToken.factor <= COIN, "setCollateralToken factor must be lower or equal than %s!", GetDecimaleString(COIN)); - Require(collToken.factor >= 0, "setCollateralToken factor must not be negative!"); + collToken.factor <= COIN, [=]{ return strprintf("setCollateralToken factor must be lower or equal than %s!", + GetDecimaleString(COIN)); }); + Require(collToken.factor >= 0, []{ return "setCollateralToken factor must not be negative!"; }); WriteBy(collToken.creationTx, collToken); @@ -57,7 +58,7 @@ std::optional CLoanView::GetLoanToken(const ui Res CLoanView::SetLoanToken(const CLoanSetLoanTokenImpl &loanToken, DCT_ID const &id) { // this should not happen, but for sure - Require(!GetLoanTokenByID(id), "setLoanToken with creation tx %s already exists!", loanToken.creationTx.GetHex()); + Require(!GetLoanTokenByID(id), [=]{ return strprintf("setLoanToken with creation tx %s already exists!", loanToken.creationTx.GetHex()); }); WriteBy(id, loanToken); WriteBy(loanToken.creationTx, id); @@ -285,16 +286,16 @@ Res CLoanView::IncreaseInterest(const uint32_t height, const CAmount tokenInterest, const CAmount loanIncreased) { const auto scheme = GetLoanScheme(loanSchemeID); - Require(scheme, "No such scheme id %s", loanSchemeID); + Require(scheme, [=]{ return strprintf("No such scheme id %s", loanSchemeID); }); auto token = GetLoanTokenByID(id); - Require(token, "No such loan token id %s", id.ToString()); + Require(token, [=]{ return strprintf("No such loan token id %s", id.ToString()); }); CInterestRateV3 rate{}; if (auto readRate = GetInterestRate(vaultId, id, height)) rate = *readRate; - Require(height >= rate.height, "Cannot store height in the past"); + Require(height >= rate.height, []{ return "Cannot store height in the past"; }); rate.interestToHeight = TotalInterestCalculation(rate, height); rate.height = height; @@ -333,18 +334,18 @@ Res CLoanView::DecreaseInterest(const uint32_t height, const CAmount loanDecreased, const CAmount interestDecreased) { const auto scheme = GetLoanScheme(loanSchemeID); - Require(scheme, "No such scheme id %s", loanSchemeID); + Require(scheme, [=]{ return strprintf("No such scheme id %s", loanSchemeID); }); auto token = GetLoanTokenByID(id); - Require(token, "No such loan token id %s", id.ToString()); + Require(token, [=]{ return strprintf("No such loan token id %s", id.ToString()); }); CInterestRateV3 rate{}; if (auto readRate = GetInterestRate(vaultId, id, height)) rate = *readRate; - Require(height >= rate.height, "Cannot store height in the past"); + Require(height >= rate.height, []{ return "Cannot store height in the past"; }); - Require(rate.height != 0, "Data mismatch height == 0"); + Require(rate.height != 0, []{ return "Data mismatch height == 0"; }); const auto interestToHeight = TotalInterestCalculation(rate, height); const auto interestDecreasedHP = ToHigherPrecision(interestDecreased, height); @@ -526,7 +527,7 @@ void CLoanView::MigrateInterestRateToV3(CVaultView &view, uint32_t height) { } Res CLoanView::AddLoanToken(const CVaultId &vaultId, CTokenAmount amount) { - Require(GetLoanTokenByID(amount.nTokenId), "No such loan token id %s", amount.nTokenId.ToString()); + Require(GetLoanTokenByID(amount.nTokenId), [=]{ return strprintf("No such loan token id %s", amount.nTokenId.ToString()); }); CBalances amounts; ReadBy(vaultId, amounts); @@ -539,10 +540,10 @@ Res CLoanView::AddLoanToken(const CVaultId &vaultId, CTokenAmount amount) { } Res CLoanView::SubLoanToken(const CVaultId &vaultId, CTokenAmount amount) { - Require(GetLoanTokenByID(amount.nTokenId), "No such loan token id %s", amount.nTokenId.ToString()); + Require(GetLoanTokenByID(amount.nTokenId), [=]{ return strprintf("No such loan token id %s", amount.nTokenId.ToString()); }); auto amounts = GetLoanTokens(vaultId); - Require(amounts && amounts->Sub(amount), "Loan token for vault <%s> not found", vaultId.GetHex()); + Require(amounts && amounts->Sub(amount), [=]{ return strprintf("Loan token for vault <%s> not found", vaultId.GetHex()); }); if (amounts->balances.empty()) EraseBy(vaultId); diff --git a/src/masternodes/masternodes.cpp b/src/masternodes/masternodes.cpp index 375277ca7fb..7c12bf2483e 100644 --- a/src/masternodes/masternodes.cpp +++ b/src/masternodes/masternodes.cpp @@ -320,7 +320,7 @@ Res CMasternodesView::CreateMasternode(const uint256 &nodeId, const CMasternode Res CMasternodesView::ResignMasternode(CMasternode &node, const uint256 &nodeId, const uint256 &txid, int height) { auto state = node.GetState(height, *this); if (height >= Params().GetConsensus().EunosPayaHeight) { - Require(state == CMasternode::ENABLED, "node %s state is not 'ENABLED'", nodeId.ToString()); + Require(state == CMasternode::ENABLED, [=]{ return strprintf("node %s state is not 'ENABLED'", nodeId.ToString()); }); } else if ((state != CMasternode::PRE_ENABLED && state != CMasternode::ENABLED)) { return Res::Err("node %s state is not 'PRE_ENABLED' or 'ENABLED'", nodeId.ToString()); } @@ -329,7 +329,7 @@ Res CMasternodesView::ResignMasternode(CMasternode &node, const uint256 &nodeId, if (!timelock) { return Res::Err("Failed to get timelock for masternode"); } - Require(timelock.value() == CMasternode::ZEROYEAR, "Trying to resign masternode before timelock expiration."); + Require(timelock.value() == CMasternode::ZEROYEAR, [=]{ return "Trying to resign masternode before timelock expiration."; }); node.resignTx = txid; node.resignHeight = height; @@ -990,9 +990,9 @@ ResVal CCustomCSView::GetAmountInCurrency(CAmount amount, auto amountInCurrency = MultiplyAmounts(price, amount); if (price > COIN) Require(amountInCurrency >= amount, - "Value/price too high (%s/%s)", - GetDecimaleString(amount), - GetDecimaleString(price)); + [=]{ return strprintf("Value/price too high (%s/%s)", + GetDecimaleString(amount), + GetDecimaleString(price)); }); return {amountInCurrency, Res::Ok()}; } @@ -1004,7 +1004,7 @@ ResVal CCustomCSView::GetLoanCollaterals(const CVaultId &vault bool useNextPrice, bool requireLivePrice) { const auto vault = GetVault(vaultId); - Require(vault && !vault->isUnderLiquidation, "Vault is under liquidation"); + Require(vault && !vault->isUnderLiquidation, []{ return "Vault is under liquidation";} ); CCollateralLoans result{}; Require(PopulateLoansData(result, vaultId, height, blockTime, useNextPrice, requireLivePrice)); @@ -1030,11 +1030,11 @@ ResVal CCustomCSView::GetValidatedIntervalPrice(const CTokenCurrencyPai Require(priceFeed); if (requireLivePrice) - Require(priceFeed->isLive(GetPriceDeviation()), "No live fixed prices for %s/%s", tokenSymbol, currency); + Require(priceFeed->isLive(GetPriceDeviation()), [=]{ return strprintf("No live fixed prices for %s/%s", tokenSymbol, currency); }); auto priceRecordIndex = useNextPrice ? 1 : 0; auto price = priceFeed.val->priceRecord[priceRecordIndex]; - Require(price > 0, "Negative price (%s/%s)", tokenSymbol, currency); + Require(price > 0, [=]{ return strprintf("Negative price (%s/%s)", tokenSymbol, currency); }); return {price, Res::Ok()}; } @@ -1051,12 +1051,12 @@ Res CCustomCSView::PopulateLoansData(CCollateralLoans &result, for (const auto &[loanTokenId, loanTokenAmount] : loanTokens->balances) { const auto token = GetLoanTokenByID(loanTokenId); - Require(token, "Loan token with id (%s) does not exist!", loanTokenId.ToString()); + Require(token, [=]{ return strprintf("Loan token with id (%s) does not exist!", loanTokenId.ToString()); }); const auto rate = GetInterestRate(vaultId, loanTokenId, height); - Require(rate, "Cannot get interest rate for token (%s)!", token->symbol); + Require(rate, [=]{ return strprintf("Cannot get interest rate for token (%s)!", token->symbol); }); - Require(height >= rate->height, "Trying to read loans in the past"); + Require(height >= rate->height, []{ return "Trying to read loans in the past"; }); auto totalAmount = loanTokenAmount + TotalInterest(*rate, height); if (totalAmount < 0) { @@ -1070,7 +1070,7 @@ Res CCustomCSView::PopulateLoansData(CCollateralLoans &result, auto prevLoans = result.totalLoans; result.totalLoans += *amountInCurrency.val; - Require(prevLoans <= result.totalLoans, "Exceeded maximum loans"); + Require(prevLoans <= result.totalLoans, []{ return "Exceeded maximum loans"; }); result.loans.push_back({loanTokenId, amountInCurrency}); } @@ -1089,7 +1089,7 @@ Res CCustomCSView::PopulateCollateralData(CCollateralLoans &result, auto tokenAmount = col.second; auto token = HasLoanCollateralToken({tokenId, height}); - Require(token, "Collateral token with id (%s) does not exist!", tokenId.ToString()); + Require(token, [=]{ return strprintf("Collateral token with id (%s) does not exist!", tokenId.ToString()); }); auto amountInCurrency = GetAmountInCurrency(tokenAmount, token->fixedIntervalPriceId, useNextPrice, requireLivePrice); @@ -1100,7 +1100,7 @@ Res CCustomCSView::PopulateCollateralData(CCollateralLoans &result, auto prevCollaterals = result.totalCollaterals; result.totalCollaterals += amountFactor; - Require(prevCollaterals <= result.totalCollaterals, "Exceeded maximum collateral"); + Require(prevCollaterals <= result.totalCollaterals, []{ return "Exceeded maximum collateral"; }); result.collaterals.push_back({tokenId, amountInCurrency}); } diff --git a/src/masternodes/oracles.cpp b/src/masternodes/oracles.cpp index d7aef45a500..cd7f7c6e724 100644 --- a/src/masternodes/oracles.cpp +++ b/src/masternodes/oracles.cpp @@ -13,7 +13,7 @@ bool COracle::SupportsPair(const std::string &token, const std::string ¤cy } Res COracle::SetTokenPrice(const std::string &token, const std::string ¤cy, CAmount amount, int64_t timestamp) { - Require(SupportsPair(token, currency), "token <%s> - currency <%s> is not allowed", token, currency); + Require(SupportsPair(token, currency), [=]{ return strprintf("token <%s> - currency <%s> is not allowed", token, currency); }); tokenPrices[token][currency] = std::make_pair(amount, timestamp); @@ -21,22 +21,22 @@ Res COracle::SetTokenPrice(const std::string &token, const std::string ¤cy } ResVal COracle::GetTokenPrice(const std::string &token, const std::string ¤cy) { - Require(SupportsPair(token, currency), "token <%s> - currency <%s> is not allowed", token, currency); + Require(SupportsPair(token, currency), [=]{ return strprintf("token <%s> - currency <%s> is not allowed", token, currency); }); return ResVal(tokenPrices[token][currency].first, Res::Ok()); } Res COracleView::AppointOracle(const COracleId &oracleId, const COracle &oracle) { - Require(WriteBy(oracleId, oracle), "failed to appoint the new oracle <%s>", oracleId.GetHex()); + Require(WriteBy(oracleId, oracle), [=]{ return strprintf("failed to appoint the new oracle <%s>", oracleId.GetHex()); }); return Res::Ok(); } Res COracleView::UpdateOracle(const COracleId &oracleId, COracle &&newOracle) { COracle oracle; - Require(ReadBy(oracleId, oracle), "oracle <%s> not found", oracleId.GetHex()); + Require(ReadBy(oracleId, oracle), [=]{ return strprintf("oracle <%s> not found", oracleId.GetHex()); }); - Require(newOracle.tokenPrices.empty(), "oracle <%s> has token prices on update", oracleId.GetHex()); + Require(newOracle.tokenPrices.empty(), [=]{ return strprintf("oracle <%s> has token prices on update", oracleId.GetHex()); }); oracle.weightage = newOracle.weightage; oracle.oracleAddress = std::move(newOracle.oracleAddress); @@ -57,23 +57,23 @@ Res COracleView::UpdateOracle(const COracleId &oracleId, COracle &&newOracle) { oracle.availablePairs = std::move(newOracle.availablePairs); // no need to update oracles list - Require(WriteBy(oracleId, oracle), "failed to save oracle <%s>", oracleId.GetHex()); + Require(WriteBy(oracleId, oracle), [=]{ return strprintf("failed to save oracle <%s>", oracleId.GetHex()); }); return Res::Ok(); } Res COracleView::RemoveOracle(const COracleId &oracleId) { - Require(ExistsBy(oracleId), "oracle <%s> not found", oracleId.GetHex()); + Require(ExistsBy(oracleId), [=]{ return strprintf("oracle <%s> not found", oracleId.GetHex()); }); // remove oracle - Require(EraseBy(oracleId), "failed to remove oracle <%s>", oracleId.GetHex()); + Require(EraseBy(oracleId), [=]{ return strprintf("failed to remove oracle <%s>", oracleId.GetHex()); }); return Res::Ok(); } Res COracleView::SetOracleData(const COracleId &oracleId, int64_t timestamp, const CTokenPrices &tokenPrices) { COracle oracle; - Require(ReadBy(oracleId, oracle), "failed to read oracle %s from database", oracleId.GetHex()); + Require(ReadBy(oracleId, oracle), [=]{ return strprintf("failed to read oracle %s from database", oracleId.GetHex()); }); for (const auto &tokenPrice : tokenPrices) { const auto &token = tokenPrice.first; @@ -83,13 +83,13 @@ Res COracleView::SetOracleData(const COracleId &oracleId, int64_t timestamp, con } } - Require(WriteBy(oracleId, oracle), "failed to store oracle %s to database", oracleId.GetHex()); + Require(WriteBy(oracleId, oracle), [=]{ return strprintf("failed to store oracle %s to database", oracleId.GetHex()); }); return Res::Ok(); } ResVal COracleView::GetOracleData(const COracleId &oracleId) const { COracle oracle; - Require(ReadBy(oracleId, oracle), "oracle <%s> not found", oracleId.GetHex()); + Require(ReadBy(oracleId, oracle), [=]{ return strprintf("oracle <%s> not found", oracleId.GetHex()); }); return ResVal(oracle, Res::Ok()); } @@ -106,9 +106,9 @@ bool CFixedIntervalPrice::isLive(const CAmount deviationThreshold) const { Res COracleView::SetFixedIntervalPrice(const CFixedIntervalPrice &fixedIntervalPrice) { Require(WriteBy(fixedIntervalPrice.priceFeedId, fixedIntervalPrice), - "failed to set new price feed <%s/%s>", - fixedIntervalPrice.priceFeedId.first, - fixedIntervalPrice.priceFeedId.second); + [=]{ return strprintf("failed to set new price feed <%s/%s>", + fixedIntervalPrice.priceFeedId.first, + fixedIntervalPrice.priceFeedId.second); }); LogPrint(BCLog::ORACLE, "%s(): %s/%s, active - %lld, next - %lld\n", @@ -124,9 +124,9 @@ Res COracleView::SetFixedIntervalPrice(const CFixedIntervalPrice &fixedIntervalP ResVal COracleView::GetFixedIntervalPrice(const CTokenCurrencyPair &fixedIntervalPriceId) { CFixedIntervalPrice fixedIntervalPrice; Require(ReadBy(fixedIntervalPriceId, fixedIntervalPrice), - "fixedIntervalPrice with id <%s/%s> not found", - fixedIntervalPriceId.first, - fixedIntervalPriceId.second); + [=]{ return strprintf("fixedIntervalPrice with id <%s/%s> not found", + fixedIntervalPriceId.first, + fixedIntervalPriceId.second); }); DCT_ID firstID{}, secondID{}; const auto firstToken = GetTokenGuessId(fixedIntervalPriceId.first, firstID); @@ -141,7 +141,7 @@ ResVal COracleView::GetFixedIntervalPrice(const CTokenCurre loanTokens.insert(secondID.v); } - Require(!AreTokensLocked(loanTokens), "Fixed interval price currently disabled due to locked token"); + Require(!AreTokensLocked(loanTokens), []{ return "Fixed interval price currently disabled due to locked token"; }); LogPrint(BCLog::ORACLE, "%s(): %s/%s, active - %lld, next - %lld\n", diff --git a/src/masternodes/poolpairs.cpp b/src/masternodes/poolpairs.cpp index b5954e17019..c3f8fe98a11 100644 --- a/src/masternodes/poolpairs.cpp +++ b/src/masternodes/poolpairs.cpp @@ -69,12 +69,12 @@ ReturnType ReadValueAt(CPoolPairView *poolView, const PoolHeightKey &poolKey) { } Res CPoolPairView::SetPoolPair(DCT_ID const &poolId, uint32_t height, const CPoolPair &pool) { - Require(pool.idTokenA != pool.idTokenB, "Error: tokens IDs are the same."); + Require(pool.idTokenA != pool.idTokenB, []{ return "Error: tokens IDs are the same."; }); auto poolPairByID = GetPoolPair(poolId); auto poolIdByTokens = ReadBy(ByPairKey{pool.idTokenA, pool.idTokenB}); auto mismatch = (!poolPairByID && poolIdByTokens) || (poolPairByID && !poolIdByTokens); - Require(!mismatch, "Error, there is already a poolpair with same tokens, but different poolId"); + Require(!mismatch, []{ return "Error, there is already a poolpair with same tokens, but different poolId"; }); // create new if (!poolPairByID && !poolIdByTokens) { @@ -85,7 +85,7 @@ Res CPoolPairView::SetPoolPair(DCT_ID const &poolId, uint32_t height, const CPoo return Res::Ok(); } - Require(poolId == *poolIdByTokens, "Error, PoolID is incorrect"); + Require(poolId == *poolIdByTokens, []{ return "Error, PoolID is incorrect"; }); auto poolPairByTokens = ReadBy(poolId); assert(poolPairByTokens); @@ -116,7 +116,7 @@ Res CPoolPairView::UpdatePoolPair(DCT_ID const &poolId, const CScript &ownerAddress, const CBalances &rewards) { auto poolPair = GetPoolPair(poolId); - Require(poolPair, "Pool with poolId %s does not exist", poolId.ToString()); + Require(poolPair, [=]{ return strprintf("Pool with poolId %s does not exist", poolId.ToString()); }); CPoolPair &pool = poolPair.value(); @@ -125,7 +125,7 @@ Res CPoolPairView::UpdatePoolPair(DCT_ID const &poolId, } if (commission >= 0) { // default/not set is -1 - Require(commission <= COIN, "commission > 100%%"); + Require(commission <= COIN, []{ return "commission > 100%%"; }); pool.commission = commission; } @@ -340,14 +340,14 @@ Res CPoolPair::AddLiquidity(CAmount amountA, std::function onMint, bool slippageProtection) { // instead of assertion due to tests - Require(amountA > 0 && amountB > 0, "amounts should be positive"); + Require(amountA > 0 && amountB > 0, []{ return "amounts should be positive"; }); CAmount liquidity{0}; if (totalLiquidity == 0) { liquidity = (arith_uint256(amountA) * amountB) .sqrt() .GetLow64(); // sure this is below std::numeric_limits::max() due to sqrt natue - Require(liquidity > MINIMUM_LIQUIDITY, "liquidity too low"); + Require(liquidity > MINIMUM_LIQUIDITY, []{ return "liquidity too low"; }); liquidity -= MINIMUM_LIQUIDITY; // MINIMUM_LIQUIDITY is a hack for non-zero division totalLiquidity = MINIMUM_LIQUIDITY; @@ -356,23 +356,23 @@ Res CPoolPair::AddLiquidity(CAmount amountA, CAmount liqB = (arith_uint256(amountB) * arith_uint256(totalLiquidity) / reserveB).GetLow64(); liquidity = std::min(liqA, liqB); - Require(liquidity > 0, "amounts too low, zero liquidity"); + Require(liquidity > 0, []{ return "amounts too low, zero liquidity"; }); if (slippageProtection) { Require((std::max(liqA, liqB) - liquidity) * 100 / liquidity < 3, - "Exceeds max ratio slippage protection of 3%%"); + []{ return "Exceeds max ratio slippage protection of 3%%"; }); } } // increasing totalLiquidity auto resTotal = SafeAdd(totalLiquidity, liquidity); - Require(resTotal, "can't add %d to totalLiquidity: %s", liquidity, resTotal.msg); + Require(resTotal, [=]{ return strprintf("can't add %d to totalLiquidity: %s", liquidity, resTotal.msg); }); totalLiquidity = resTotal; // increasing reserves auto resA = SafeAdd(reserveA, amountA); auto resB = SafeAdd(reserveB, amountB); - Require(resA && resB, "overflow when adding to reserves"); + Require(resA && resB, []{ return "overflow when adding to reserves"; }); reserveA = resA; reserveB = resB; @@ -384,7 +384,7 @@ Res CPoolPair::RemoveLiquidity(CAmount liqAmount, std::function 0 && liqAmount < totalLiquidity, "incorrect liquidity"); + Require(liqAmount > 0 && liqAmount < totalLiquidity, []{ return "incorrect liquidity"; }); CAmount resAmountA, resAmountB; resAmountA = (arith_uint256(liqAmount) * arith_uint256(reserveA) / totalLiquidity).GetLow64(); @@ -404,10 +404,9 @@ Res CPoolPair::Swap(CTokenAmount in, std::function onTransfer, int height) { Require(in.nTokenId == idTokenA || in.nTokenId == idTokenB, - "Error, input token ID (" + in.nTokenId.ToString() + ") doesn't match pool tokens (" + idTokenA.ToString() + - "," + idTokenB.ToString() + ")"); + [=]{ return strprintf("Error, input token ID (%s) doesn't match pool tokens (%s,%s)", in.nTokenId.ToString(), idTokenA.ToString(), idTokenB.ToString()); }); - Require(status, "Pool trading is turned off!"); + Require(status, []{ return "Pool trading is turned off!"; }); const bool forward = in.nTokenId == idTokenA; auto &reserveF = forward ? reserveA : reserveB; @@ -415,14 +414,14 @@ Res CPoolPair::Swap(CTokenAmount in, // it is important that reserves are at least SLOPE_SWAP_RATE (1000) to be able to slide, otherwise it can lead to // underflow - Require(reserveA >= SLOPE_SWAP_RATE && reserveB >= SLOPE_SWAP_RATE, "Lack of liquidity."); + Require(reserveA >= SLOPE_SWAP_RATE && reserveB >= SLOPE_SWAP_RATE, []{ return "Lack of liquidity."; }); const auto maxPrice256 = arith_uint256(maxPrice.integer) * PRECISION + maxPrice.fraction; // NOTE it has a bug prior Dakota hardfork const auto price = height < Params().GetConsensus().DakotaHeight ? arith_uint256(reserveT) * PRECISION / reserveF : arith_uint256(reserveF) * PRECISION / reserveT; - Require(price <= maxPrice256, "Price is higher than indicated."); + Require(price <= maxPrice256, []{ return "Price is higher than indicated."; }); // claim trading fee if (commission) { const CAmount tradeFee = MultiplyAmounts(in.nValue, commission); @@ -437,12 +436,12 @@ Res CPoolPair::Swap(CTokenAmount in, CTokenAmount dexfeeInAmount{in.nTokenId, 0}; if (dexfeeInPct > 0 && poolInFee(forward, asymmetricFee)) { - Require(dexfeeInPct <= COIN, "Dex fee input percentage over 100%%"); + Require(dexfeeInPct <= COIN, []{ return "Dex fee input percentage over 100%%"; }); dexfeeInAmount.nValue = MultiplyAmounts(in.nValue, dexfeeInPct); in.nValue -= dexfeeInAmount.nValue; } - Require(SafeAdd(reserveF, in.nValue), "Swapping will lead to pool's reserve overflow"); + Require(SafeAdd(reserveF, in.nValue), []{ return "Swapping will lead to pool's reserve overflow"; }); CAmount result = slopeSwap(in.nValue, reserveF, reserveT, height); @@ -651,7 +650,7 @@ inline CAmount PoolRewardPerBlock(CAmount dailyReward, CAmount rewardPct) { } Res CPoolPairView::SetRewardPct(DCT_ID const &poolId, uint32_t height, CAmount rewardPct) { - Require(HasPoolPair(poolId), "No such pool pair"); + Require(HasPoolPair(poolId), []{ return "No such pool pair"; }); WriteBy(poolId, rewardPct); if (auto dailyReward = ReadBy(DCT_ID{})) { WriteBy(PoolHeightKey{poolId, height}, PoolRewardPerBlock(*dailyReward, rewardPct)); @@ -660,7 +659,7 @@ Res CPoolPairView::SetRewardPct(DCT_ID const &poolId, uint32_t height, CAmount r } Res CPoolPairView::SetRewardLoanPct(DCT_ID const &poolId, uint32_t height, CAmount rewardLoanPct) { - Require(HasPoolPair(poolId), "No such pool pair"); + Require(HasPoolPair(poolId), []{ return "No such pool pair"; }); WriteBy(poolId, rewardLoanPct); if (auto dailyReward = ReadBy(DCT_ID{})) { WriteBy(PoolHeightKey{poolId, height}, PoolRewardPerBlock(*dailyReward, rewardLoanPct)); @@ -714,7 +713,7 @@ void CPoolPairView::ForEachPoolShare(std::function= 0 && feePct <= COIN, "Token dex fee should be in percentage"); + Require(feePct >= 0 && feePct <= COIN, []{ return "Token dex fee should be in percentage"; }); WriteBy(std::make_pair(poolId, tokenId), uint32_t(feePct)); return Res::Ok(); } diff --git a/src/masternodes/rpc_oracles.cpp b/src/masternodes/rpc_oracles.cpp index 95827037ac0..9a3defc9f14 100644 --- a/src/masternodes/rpc_oracles.cpp +++ b/src/masternodes/rpc_oracles.cpp @@ -853,8 +853,8 @@ ResVal GetAggregatePrice(CCustomCSView& view, const std::string& token, }); static const uint64_t minimumLiveOracles = Params().NetworkIDString() == CBaseChainParams::REGTEST ? 1 : 2; - Require(numLiveOracles >= minimumLiveOracles, "no live oracles for specified request"); - Require(sumWeights > 0, "all live oracles which meet specified request, have zero weight"); + Require(numLiveOracles >= minimumLiveOracles, []{ return "no live oracles for specified request"; }); + Require(sumWeights > 0, []{ return "all live oracles which meet specified request, have zero weight"; }); ResVal res((weightedSum / arith_uint256(sumWeights)).GetLow64(), Res::Ok()); diff --git a/src/masternodes/tokens.cpp b/src/masternodes/tokens.cpp index e70a54bd0a2..6c8db2c7033 100644 --- a/src/masternodes/tokens.cpp +++ b/src/masternodes/tokens.cpp @@ -64,14 +64,14 @@ Res CTokensView::CreateDFIToken() { ResVal CTokensView::CreateToken(const CTokensView::CTokenImpl &token, bool isPreBayfront) { // this should not happen, but for sure Require(!GetTokenByCreationTx(token.creationTx), - "token with creation tx %s already exists!", - token.creationTx.ToString()); + [=]{ return strprintf("token with creation tx %s already exists!", + token.creationTx.ToString()); }); Require(token.IsValidSymbol()); DCT_ID id{0}; if (token.IsDAT()) { - Require(!GetToken(token.symbol), "token '%s' already exists!", token.symbol); + Require(!GetToken(token.symbol), [=]{ return strprintf("token '%s' already exists!", token.symbol); }); ForEachToken( [&](DCT_ID const ¤tId, CLazySerialize) { @@ -81,14 +81,10 @@ ResVal CTokensView::CreateToken(const CTokensView::CTokenImpl &token, bo }, id); if (id == DCT_ID_START) { + // asserted before BayfrontHeight, keep it for strict sameness Require( !isPreBayfront, - "Critical fault: trying to create DCT_ID same as DCT_ID_START for Foundation owner\n"); // asserted - // before - // BayfrontHeight, - // keep it for - // strict - // sameness + []{ return "Critical fault: trying to create DCT_ID same as DCT_ID_START for Foundation owner\n"; }); id = IncrementLastDctId(); LogPrintf("Warning! Range CTokensView::CreateToken(const CTokensView::CTokenImpl &token, bo Res CTokensView::UpdateToken(const CTokenImpl &newToken, bool isPreBayfront, const bool tokenSplitUpdate) { auto pair = GetTokenByCreationTx(newToken.creationTx); - Require(pair, "token with creationTx %s does not exist!", newToken.creationTx.ToString()); + Require(pair, [=]{ return strprintf("token with creationTx %s does not exist!", newToken.creationTx.ToString()); }); DCT_ID id = pair->first; CTokenImpl &oldToken = pair->second; @@ -116,7 +112,7 @@ Res CTokensView::UpdateToken(const CTokenImpl &newToken, bool isPreBayfront, con if (!isPreBayfront) // for compatibility, in potential case when someone cheat and create finalized token with old node (and then // alter dat for ex.) - Require(!oldToken.IsFinalized(), "can't alter 'Finalized' tokens"); + Require(!oldToken.IsFinalized(), []{ return "can't alter 'Finalized' tokens"; }); // 'name' and 'symbol' were trimmed in 'Apply' oldToken.name = newToken.name; @@ -132,7 +128,7 @@ Res CTokensView::UpdateToken(const CTokenImpl &newToken, bool isPreBayfront, con // create keys with regard of new flag std::string oldSymbolKey = oldToken.CreateSymbolKey(id); std::string newSymbolKey = newToken.CreateSymbolKey(id); - Require(!GetToken(newSymbolKey), "token with key '%s' already exists!", newSymbolKey); + Require(!GetToken(newSymbolKey), [=]{ return strprintf("token with key '%s' already exists!", newSymbolKey); }); EraseBy(oldSymbolKey); WriteBy(newSymbolKey, id); @@ -197,10 +193,10 @@ Res CTokensView::BayfrontFlagsCleanup() { Res CTokensView::AddMintedTokens(DCT_ID const &id, const CAmount &amount) { auto tokenImpl = GetToken(id); - Require(tokenImpl, "token with id %d does not exist!", id.v); + Require(tokenImpl, [=]{ return strprintf("token with id %d does not exist!", id.v); }); auto resMinted = SafeAdd(tokenImpl->minted, amount); - Require(resMinted, "overflow when adding to minted"); + Require(resMinted, []{ return "overflow when adding to minted"; }); tokenImpl->minted = resMinted; @@ -210,10 +206,10 @@ Res CTokensView::AddMintedTokens(DCT_ID const &id, const CAmount &amount) { Res CTokensView::SubMintedTokens(DCT_ID const &id, const CAmount &amount) { auto tokenImpl = GetToken(id); - Require(tokenImpl, "token with id %d does not exist!", id.v); + Require(tokenImpl, [=]{ return strprintf("token with id %d does not exist!", id.v); }); auto resMinted = tokenImpl->minted - amount; - Require(resMinted >= 0, "not enough tokens exist to subtract this amount"); + Require(resMinted >= 0, []{ return "not enough tokens exist to subtract this amount"; }); tokenImpl->minted = resMinted; @@ -240,10 +236,10 @@ std::optional CTokensView::ReadLastDctId() const { } inline Res CTokenImplementation::IsValidSymbol() const { - Require(!symbol.empty() && !IsDigit(symbol[0]), "token symbol should be non-empty and starts with a letter"); - Require(symbol.find('#') == std::string::npos, "token symbol should not contain '#'"); + Require(!symbol.empty() && !IsDigit(symbol[0]), []{ return "token symbol should be non-empty and starts with a letter"; }); + Require(symbol.find('#') == std::string::npos, []{ return "token symbol should not contain '#'"; }); if (creationHeight >= Params().GetConsensus().FortCanningCrunchHeight) { - Require(symbol.find('/') == std::string::npos, "token symbol should not contain '/'"); + Require(symbol.find('/') == std::string::npos, []{ return "token symbol should not contain '/'"; }); } return Res::Ok(); } diff --git a/src/masternodes/validation.cpp b/src/masternodes/validation.cpp index 2d8d9da8aa3..e4447d04536 100644 --- a/src/masternodes/validation.cpp +++ b/src/masternodes/validation.cpp @@ -1483,7 +1483,7 @@ static Res VaultSplits(CCustomCSView& view, ATTRIBUTES& attributes, const DCT_ID }); } - Require(failedVault == CVaultId{}, "Failed to get vault data for: %s", failedVault.ToString()); + Require(failedVault == CVaultId{}, [=]{ return strprintf("Failed to get vault data for: %s", failedVault.ToString()); }); attributes.EraseKey(CDataStructureV0{AttributeTypes::Locks, ParamIDs::TokenID, oldTokenId.v}); attributes.SetValue(CDataStructureV0{AttributeTypes::Locks, ParamIDs::TokenID, newTokenId.v}, true); @@ -1514,7 +1514,7 @@ static Res VaultSplits(CCustomCSView& view, ATTRIBUTES& attributes, const DCT_ID } const auto loanToken = view.GetLoanTokenByID(newTokenId); - Require(loanToken, "Failed to get loan token."); + Require(loanToken, []{ return "Failed to get loan token."; }); // Pre-populate to save repeated calls to get loan scheme std::map loanSchemes; @@ -1649,10 +1649,10 @@ static Res GetTokenSuffix(const CCustomCSView& view, const ATTRIBUTES& attribute if (attributes.CheckKey(ascendantKey)) { const auto& [previousID, str] = attributes.GetValue(ascendantKey, AscendantValue{std::numeric_limits::max(), ""}); auto previousToken = view.GetToken(DCT_ID{previousID}); - Require(previousToken, "Previous token %d not found\n", id); + Require(previousToken, [=]{ return strprintf("Previous token %d not found\n", id); }); const auto found = previousToken->symbol.find(newSuffix); - Require(found != std::string::npos, "Previous token name not valid: %s\n", previousToken->symbol); + Require(found != std::string::npos, [=]{ return strprintf("Previous token name not valid: %s\n", previousToken->symbol); }); const auto versionNumber = previousToken->symbol.substr(found + newSuffix.size()); uint32_t previousVersion{}; diff --git a/src/masternodes/vault.cpp b/src/masternodes/vault.cpp index 57d1d13e998..91109dd68ca 100644 --- a/src/masternodes/vault.cpp +++ b/src/masternodes/vault.cpp @@ -23,7 +23,7 @@ Res CVaultView::StoreVault(const CVaultId &vaultId, const CVaultData &vault) { Res CVaultView::EraseVault(const CVaultId &vaultId) { auto vault = GetVault(vaultId); - Require(vault, "Vault <%s> not found", vaultId.GetHex()); + Require(vault, [=]{ return strprintf("Vault <%s> not found", vaultId.GetHex()); }); EraseBy(vaultId); EraseBy(vaultId); @@ -37,7 +37,7 @@ std::optional CVaultView::GetVault(const CVaultId &vaultId) const { Res CVaultView::UpdateVault(const CVaultId &vaultId, const CVaultMessage &newVault) { auto vault = GetVault(vaultId); - Require(vault, "Vault <%s> not found", vaultId.GetHex()); + Require(vault, [=]{ return strprintf("Vault <%s> not found", vaultId.GetHex()); }); EraseBy(std::make_pair(vault->ownerAddress, vaultId)); @@ -73,7 +73,7 @@ Res CVaultView::AddVaultCollateral(const CVaultId &vaultId, CTokenAmount amount) Res CVaultView::SubVaultCollateral(const CVaultId &vaultId, CTokenAmount amount) { auto amounts = GetVaultCollaterals(vaultId); - Require(amounts && amounts->Sub(amount), "Collateral for vault <%s> not found", vaultId.GetHex()); + Require(amounts && amounts->Sub(amount), [=]{ return strprintf("Collateral for vault <%s> not found", vaultId.GetHex()); }); if (amounts->balances.empty()) { EraseBy(vaultId); diff --git a/src/rpc/rawtransaction_util.cpp b/src/rpc/rawtransaction_util.cpp index eeb57137078..427da3ccc47 100644 --- a/src/rpc/rawtransaction_util.cpp +++ b/src/rpc/rawtransaction_util.cpp @@ -61,7 +61,7 @@ ResVal GuessTokenAmount(interfaces::Chain const & chain, std::stri } catch (...) { // assuming it's token symbol, read DCT_ID from DB auto token = chain.existTokenGuessId(parsed.val->second, tokenId); - Require(token, "Invalid Defi token: %s", parsed.val->second); + Require(token, [=]{ return strprintf("Invalid Defi token: %s", parsed.val->second); }); return {{tokenId, parsed.val->first}, Res::Ok()}; } } From 36e05afcc35333d36bd68a9754e865d0b3036f66 Mon Sep 17 00:00:00 2001 From: Bushstar Date: Fri, 10 Feb 2023 14:00:02 +0000 Subject: [PATCH 2/3] Capture structured binding by name --- src/masternodes/masternodes.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/masternodes/masternodes.cpp b/src/masternodes/masternodes.cpp index 7c12bf2483e..ad1b8a7f366 100644 --- a/src/masternodes/masternodes.cpp +++ b/src/masternodes/masternodes.cpp @@ -1051,7 +1051,7 @@ Res CCustomCSView::PopulateLoansData(CCollateralLoans &result, for (const auto &[loanTokenId, loanTokenAmount] : loanTokens->balances) { const auto token = GetLoanTokenByID(loanTokenId); - Require(token, [=]{ return strprintf("Loan token with id (%s) does not exist!", loanTokenId.ToString()); }); + Require(token, [loanTokenId=loanTokenId]{ return strprintf("Loan token with id (%s) does not exist!", loanTokenId.ToString()); }); const auto rate = GetInterestRate(vaultId, loanTokenId, height); Require(rate, [=]{ return strprintf("Cannot get interest rate for token (%s)!", token->symbol); }); From 8245ca5f9162c5ba390b8bb5605fa67c0d7a3337 Mon Sep 17 00:00:00 2001 From: Bushstar Date: Fri, 10 Feb 2023 14:31:54 +0000 Subject: [PATCH 3/3] Capture another local binding by name --- src/masternodes/govvariables/lp_splits.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/masternodes/govvariables/lp_splits.cpp b/src/masternodes/govvariables/lp_splits.cpp index e99e10a9322..33ff6ba67ff 100644 --- a/src/masternodes/govvariables/lp_splits.cpp +++ b/src/masternodes/govvariables/lp_splits.cpp @@ -38,7 +38,7 @@ Res LP_SPLITS::Validate(const CCustomCSView &mnview) const { Require(mnview.HasPoolPair(poolId), [poolId=poolId]{ return strprintf("pool with id=%s not found", poolId.ToString()); }); Require(amount >= 0 && amount <= COIN, - [=, poolId=poolId]{ return strprintf("wrong percentage for pool with id=%s, value = %s", poolId.ToString(), std::to_string(amount)); }); + [amount=amount, poolId=poolId]{ return strprintf("wrong percentage for pool with id=%s, value = %s", poolId.ToString(), std::to_string(amount)); }); total += amount; }