Skip to content

Commit

Permalink
Replace Require strings with lambdas (#1755)
Browse files Browse the repository at this point in the history
* Replace Require strings with lambdas

* Capture structured binding by name

* Capture another local binding by name
  • Loading branch information
Bushstar authored Feb 11, 2023
1 parent 13b81fe commit 77b7326
Show file tree
Hide file tree
Showing 23 changed files with 205 additions and 211 deletions.
4 changes: 2 additions & 2 deletions src/amount.h
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ typedef std::map<DCT_ID, CAmount> TAmounts;

inline ResVal<CAmount> 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;
Expand All @@ -101,7 +101,7 @@ inline ResVal<CAmount> SafeAdd(CAmount _a, CAmount _b) {
const uint64_t sum = a + b;
// check overflow

Require((sum - a) == b && (uint64_t)std::numeric_limits<CAmount>::max() >= sum, "overflow");
Require((sum - a) == b && (uint64_t)std::numeric_limits<CAmount>::max() >= sum, []{ return "overflow"; });
return {(CAmount) sum, Res::Ok()};
}

Expand Down
8 changes: 4 additions & 4 deletions src/chainparams.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1189,7 +1189,7 @@ void ClearCheckpoints(CChainParams &params) {

Res UpdateCheckpointsFromFile(CChainParams &params, 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);

Expand All @@ -1201,13 +1201,13 @@ Res UpdateCheckpointsFromFile(CChainParams &params, 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;
}
Expand Down
8 changes: 4 additions & 4 deletions src/masternodes/accounts.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ uint32_t CAccountsView::GetBalancesHeight(const CScript &owner) {
}

Res CAccountsView::StoreFuturesUserValues(const CFuturesUserKey &key, const CFuturesUserValue &futures) {
Require(WriteBy<ByFuturesSwapKey>(key, futures), "Failed to store futures");
Require(WriteBy<ByFuturesSwapKey>(key, futures), []{ return "Failed to store futures"; });
return Res::Ok();
}

Expand All @@ -91,12 +91,12 @@ void CAccountsView::ForEachFuturesUserValues(
}

Res CAccountsView::EraseFuturesUserValues(const CFuturesUserKey &key) {
Require(EraseBy<ByFuturesSwapKey>(key), "Failed to erase futures");
Require(EraseBy<ByFuturesSwapKey>(key), [=]{ return "Failed to erase futures"; });
return Res::Ok();
}

Res CAccountsView::StoreFuturesDUSD(const CFuturesUserKey &key, const CAmount &amount) {
Require(WriteBy<ByFuturesDUSDKey>(key, amount), "Failed to store futures");
Require(WriteBy<ByFuturesDUSDKey>(key, amount), []{ return "Failed to store futures"; });
return Res::Ok();
}

Expand All @@ -106,6 +106,6 @@ void CAccountsView::ForEachFuturesDUSD(std::function<bool(const CFuturesUserKey
}

Res CAccountsView::EraseFuturesDUSD(const CFuturesUserKey &key) {
Require(EraseBy<ByFuturesDUSDKey>(key), "Failed to erase futures");
Require(EraseBy<ByFuturesDUSDKey>(key), []{ return "Failed to erase futures"; });
return Res::Ok();
}
152 changes: 76 additions & 76 deletions src/masternodes/govvariables/attributes.cpp

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion src/masternodes/govvariables/icx_takerfee_per_btc.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}

Expand Down
2 changes: 1 addition & 1 deletion src/masternodes/govvariables/loan_daily_reward.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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.");
}

Expand Down
4 changes: 2 additions & 2 deletions src/masternodes/govvariables/loan_liquidation_penalty.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand Down
14 changes: 7 additions & 7 deletions src/masternodes/govvariables/loan_splits.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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();
}
Expand Down
2 changes: 1 addition & 1 deletion src/masternodes/govvariables/lp_daily_dfi_reward.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand Down
10 changes: 4 additions & 6 deletions src/masternodes/govvariables/lp_splits.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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));
[amount=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();
}
Expand Down
6 changes: 3 additions & 3 deletions src/masternodes/govvariables/oracle_block_interval.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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();
}
Expand Down
4 changes: 2 additions & 2 deletions src/masternodes/govvariables/oracle_deviation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand Down
2 changes: 1 addition & 1 deletion src/masternodes/gv.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ std::shared_ptr<GovVariable> CGovView::GetVariable(const std::string &name) cons

Res CGovView::SetStoredVariables(const std::set<std::shared_ptr<GovVariable>> &govVars, const uint32_t height) {
for (auto &item : govVars)
Require(WriteBy<ByHeightVars>(GovVarKey{height, item->GetName()}, *item), "Cannot write to DB");
Require(WriteBy<ByHeightVars>(GovVarKey{height, item->GetName()}, *item), []{ return "Cannot write to DB"; });

return Res::Ok();
}
Expand Down
6 changes: 3 additions & 3 deletions src/masternodes/incentivefunding.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<ById>(static_cast<unsigned char>(account), amount);
return Res::Ok();
}
Expand All @@ -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);
}
31 changes: 16 additions & 15 deletions src/masternodes/loan.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@ std::optional<CLoanView::CLoanSetCollateralTokenImpl> 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<LoanSetCollateralTokenCreationTx>(collToken.creationTx, collToken);

Expand Down Expand Up @@ -57,7 +58,7 @@ std::optional<CLoanView::CLoanSetLoanTokenImpl> 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<LoanSetLoanTokenKey>(id, loanToken);
WriteBy<LoanSetLoanTokenCreationTx>(loanToken.creationTx, id);
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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<LoanTokenAmount>(vaultId, amounts);
Expand All @@ -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<LoanTokenAmount>(vaultId);
Expand Down
Loading

0 comments on commit 77b7326

Please sign in to comment.