diff --git a/.clang-tidy b/.clang-tidy index 2d72eae701..e09d326916 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -153,7 +153,7 @@ Checks: "-*, readability-use-std-min-max " # --- -# readability-inconsistent-declaration-parameter-name, # in this codebase this check will break a lot of arg names +# readability-inconsistent-declaration-parameter-name, # In this codebase this check will break a lot of arg names # readability-static-accessed-through-instance, # this check is probably unnecessary. It makes the code less readable # --- diff --git a/.github/workflows/reusable-build-test-config.yml b/.github/workflows/reusable-build-test-config.yml index d53cf97a39..8cb5f8c46a 100644 --- a/.github/workflows/reusable-build-test-config.yml +++ b/.github/workflows/reusable-build-test-config.yml @@ -82,7 +82,7 @@ jobs: name: ${{ inputs.config_name }} runs-on: ${{ fromJSON(inputs.runs_on) }} container: ${{ inputs.image != '' && inputs.image || null }} - timeout-minutes: ${{ inputs.sanitizers != '' && 360 || 60 }} + timeout-minutes: ${{ inputs.sanitizers != '' && 360 || 90 }} env: # Use a namespace to keep the objects separate for each configuration. CCACHE_NAMESPACE: ${{ inputs.config_name }} diff --git a/BUILD.md b/BUILD.md index 1d3fc8f774..662ba0d33d 100644 --- a/BUILD.md +++ b/BUILD.md @@ -45,14 +45,14 @@ found here](./docs/build/environment.md). It is possible to build with Conan 1.60+, but the instructions are significantly different, which is why we are not recommending it. -`xrpld` is written in the C++20 dialect and includes the `` header. -The [minimum compiler versions][2] required are: +`xrpld` is written in the C++23 dialect and includes the `` header. +The [tested compiler versions][2] are: | Compiler | Version | | ----------- | --------- | -| GCC | 12 | -| Clang | 16 | -| Apple Clang | 16 | +| GCC | 15 | +| Clang | 22 | +| Apple Clang | 17 | | MSVC | 19.44[^3] | ### Linux @@ -232,11 +232,11 @@ name and then creating a new `default` profile for a different compiler. #### Select language The default profile created by Conan will typically select different C++ dialect -than C++20 used by this project. You should set `20` in the profile line +than C++23 used by this project. You should set `23` in the profile line starting with `compiler.cppstd=`. For example: ```bash -sed -i.bak -e 's|^compiler\.cppstd=.*$|compiler.cppstd=20|' $(conan config home)/profiles/default +sed -i.bak -e 's|^compiler\.cppstd=.*$|compiler.cppstd=23|' $(conan config home)/profiles/default ``` #### Select standard library in Linux diff --git a/CMakeLists.txt b/CMakeLists.txt index d315a5dcec..3dbe60a220 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -15,7 +15,7 @@ list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") project(xrpl) set(CMAKE_CXX_EXTENSIONS OFF) -set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD 23) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) diff --git a/conan/lockfile/linux.profile b/conan/lockfile/linux.profile index 25ad5988c5..ea9f66de69 100644 --- a/conan/lockfile/linux.profile +++ b/conan/lockfile/linux.profile @@ -2,7 +2,7 @@ arch=x86_64 build_type=Release compiler=gcc -compiler.cppstd=20 +compiler.cppstd=23 compiler.libcxx=libstdc++11 compiler.version=13 os=Linux diff --git a/conan/lockfile/macos.profile b/conan/lockfile/macos.profile index 332a0c143d..f223627c26 100644 --- a/conan/lockfile/macos.profile +++ b/conan/lockfile/macos.profile @@ -2,7 +2,7 @@ arch=armv8 build_type=Release compiler=apple-clang -compiler.cppstd=20 +compiler.cppstd=23 compiler.libcxx=libc++ compiler.version=17.0 os=Macos diff --git a/conan/lockfile/windows.profile b/conan/lockfile/windows.profile index 4bb266a62e..b3a8fed4f3 100644 --- a/conan/lockfile/windows.profile +++ b/conan/lockfile/windows.profile @@ -2,7 +2,7 @@ arch=x86_64 build_type=Release compiler=msvc -compiler.cppstd=20 +compiler.cppstd=23 compiler.runtime=dynamic compiler.runtime_type=Release compiler.version=194 diff --git a/conan/profiles/default b/conan/profiles/default index cde59f7f3b..e0a88ebca1 100644 --- a/conan/profiles/default +++ b/conan/profiles/default @@ -12,7 +12,7 @@ arch={{ arch }} build_type=Debug compiler={{compiler}} compiler.version={{ compiler_version }} -compiler.cppstd=20 +compiler.cppstd=23 {% if os == "Windows" %} compiler.runtime=static {% else %} diff --git a/include/xrpl/basics/Expected.h b/include/xrpl/basics/Expected.h deleted file mode 100644 index 3796151777..0000000000 --- a/include/xrpl/basics/Expected.h +++ /dev/null @@ -1,248 +0,0 @@ -#pragma once - -#include - -#include - -#include - -namespace xrpl { - -/** Expected is an approximation of std::expected (hoped for in C++23) - - See: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p0323r10.html - - The implementation is entirely based on boost::outcome_v2::result. -*/ - -// Exception thrown by an invalid access to Expected. -struct BadExpectedAccess : public std::runtime_error -{ - BadExpectedAccess() : runtime_error("bad expected access") - { - } -}; - -namespace detail { - -// Custom policy for Expected. Always throw on an invalid access. -struct ThrowPolicy : public boost::outcome_v2::policy::base -{ - template - static constexpr void - // NOLINTNEXTLINE(readability-identifier-naming) - wide_value_check(Impl&& self) - { - if (!base::_has_value(std::forward(self))) - Throw(); - } - - template - static constexpr void - // NOLINTNEXTLINE(readability-identifier-naming) - wide_error_check(Impl&& self) - { - if (!base::_has_error(std::forward(self))) - Throw(); - } - - template - static constexpr void - // NOLINTNEXTLINE(readability-identifier-naming) - wide_exception_check(Impl&& self) - { - if (!base::_has_exception(std::forward(self))) - Throw(); - } -}; - -} // namespace detail - -// Definition of Unexpected, which is used to construct the unexpected -// return type of an Expected. -template -class Unexpected -{ -public: - static_assert(!std::is_same_v, "E must not be void"); - - Unexpected() = delete; - - constexpr explicit Unexpected(E const& e) : val_(e) - { - } - - constexpr explicit Unexpected(E&& e) : val_(std::move(e)) - { - } - - [[nodiscard]] constexpr E const& - value() const& - { - return val_; - } - - constexpr E& - value() & - { - return val_; - } - - constexpr E&& - value() && - { - return std::move(val_); - } - - [[nodiscard]] constexpr E const&& - value() const&& - { - return std::move(val_); - } - -private: - E val_; -}; - -// Unexpected deduction guide that converts array to const*. -template -Unexpected(E (&)[N]) -> Unexpected; - -// Definition of Expected. All of the machinery comes from boost::result. -template -class [[nodiscard]] Expected : private boost::outcome_v2::result -{ - using Base = boost::outcome_v2::result; - -public: - template - requires std::convertible_to - constexpr Expected(U&& r) : Base(boost::outcome_v2::in_place_type_t{}, std::forward(r)) - { - } - - template - requires std::convertible_to && (!std::is_reference_v) - constexpr Expected(Unexpected e) - : Base(boost::outcome_v2::in_place_type_t{}, std::move(e.value())) - { - } - - [[nodiscard]] constexpr bool - // NOLINTNEXTLINE(readability-identifier-naming) - has_value() const - { - return Base::has_value(); - } - - [[nodiscard]] constexpr T const& - value() const - { - return Base::value(); - } - - constexpr T& - value() - { - return Base::value(); - } - - [[nodiscard]] constexpr E const& - error() const& - { - return Base::error(); - } - - [[nodiscard]] constexpr E& - error() & - { - return Base::error(); - } - - [[nodiscard]] constexpr E&& - error() && - { - return std::move(Base::error()); - } - - constexpr explicit - operator bool() const - { - return has_value(); - } - - // Add operator* and operator-> so the Expected API looks a bit more like - // what std::expected is likely to look like. See: - // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p0323r10.html - [[nodiscard]] constexpr T& - operator*() - { - return this->value(); - } - - [[nodiscard]] constexpr T const& - operator*() const - { - return this->value(); - } - - [[nodiscard]] constexpr T* - operator->() - { - return &this->value(); - } - - [[nodiscard]] constexpr T const* - operator->() const - { - return &this->value(); - } -}; - -// Specialization of Expected. Allows returning either success -// (without a value) or the reason for the failure. -template -class [[nodiscard]] -Expected : private boost::outcome_v2::result -{ - using Base = boost::outcome_v2::result; - -public: - // The default constructor makes a successful Expected. - // This aligns with std::expected behavior proposed in P0323R10. - constexpr Expected() : Base(boost::outcome_v2::success()) - { - } - - template - requires std::convertible_to && (!std::is_reference_v) - constexpr Expected(Unexpected e) : Base(E(std::move(e.value()))) - { - } - - [[nodiscard]] constexpr E const& - error() const& - { - return Base::error(); - } - - [[nodiscard]] constexpr E& - error() & - { - return Base::error(); - } - - [[nodiscard]] constexpr E&& - error() && - { - return std::move(Base::error()); - } - - constexpr explicit - operator bool() const - { - return Base::has_value(); - } -}; - -} // namespace xrpl diff --git a/include/xrpl/basics/base_uint.h b/include/xrpl/basics/base_uint.h index 93a9ced15e..93520ff699 100644 --- a/include/xrpl/basics/base_uint.h +++ b/include/xrpl/basics/base_uint.h @@ -5,7 +5,6 @@ #pragma once -#include #include #include #include @@ -20,6 +19,7 @@ #include #include #include +#include #include namespace xrpl { @@ -177,7 +177,7 @@ private: BadChar, }; - constexpr Expected + constexpr std::expected parseFromStringView(std::string_view sv) noexcept { // Local lambda that converts a single hex char to four bits and @@ -216,7 +216,7 @@ private: } if (sv.size() != size() * 2) - return Unexpected(ParseResult::BadLength); + return std::unexpected(ParseResult::BadLength); std::size_t i = 0u; auto in = sv.begin(); @@ -227,7 +227,7 @@ private: { if (auto const result = hexCharToUInt(*in++, shift, accum); result != ParseResult::Okay) - return Unexpected(result); + return std::unexpected(result); } ret[i++] = accum; } diff --git a/include/xrpl/beast/hash/xxhasher.h b/include/xrpl/beast/hash/xxhasher.h index 95a67dede0..978bbc6917 100644 --- a/include/xrpl/beast/hash/xxhasher.h +++ b/include/xrpl/beast/hash/xxhasher.h @@ -7,8 +7,11 @@ #include #include #include +#include +#include #include #include +#include namespace beast { diff --git a/include/xrpl/ledger/helpers/AMMHelpers.h b/include/xrpl/ledger/helpers/AMMHelpers.h index 61d6e9d2fb..d21e50e7cb 100644 --- a/include/xrpl/ledger/helpers/AMMHelpers.h +++ b/include/xrpl/ledger/helpers/AMMHelpers.h @@ -1,6 +1,5 @@ #pragma once -#include #include #include #include @@ -18,6 +17,8 @@ #include #include +#include + namespace xrpl { namespace detail { @@ -741,7 +742,7 @@ ammPoolHolds( * provided then they are used as the AMM token pair issues. * Otherwise the missing issues are fetched from ammSle. */ -Expected, TER> +std::expected, TER> ammHolds( ReadView const& view, SLE const& ammSle, @@ -801,14 +802,14 @@ initializeFeeAuctionVote( * otherwise. Return tecINTERNAL if encountered an unexpected condition, * for instance Liquidity Provider has more than one LPToken trustline. */ -Expected +std::expected isOnlyLiquidityProvider(ReadView const& view, Issue const& ammIssue, AccountID const& lpAccount); /** Due to rounding, the LPTokenBalance of the last LP might * not match the LP's trustline balance. If it's within the tolerance, * update LPTokenBalance to match the LP's trustline balance. */ -Expected +std::expected verifyAndAdjustLPTokenBalance( Sandbox& sb, STAmount const& lpTokens, diff --git a/include/xrpl/ledger/helpers/AccountRootHelpers.h b/include/xrpl/ledger/helpers/AccountRootHelpers.h index c02cad98d8..cf6082d533 100644 --- a/include/xrpl/ledger/helpers/AccountRootHelpers.h +++ b/include/xrpl/ledger/helpers/AccountRootHelpers.h @@ -1,6 +1,5 @@ #pragma once -#include #include #include #include @@ -9,6 +8,7 @@ #include #include +#include #include #include @@ -91,7 +91,7 @@ isPseudoAccount( * before using a field. The amendment check is **not** performed in * createPseudoAccount. */ -[[nodiscard]] Expected +[[nodiscard]] std::expected createPseudoAccount(ApplyView& view, uint256 const& pseudoOwnerKey, SField const& ownerField); /** Checks the destination and tag. diff --git a/include/xrpl/ledger/helpers/LendingHelpers.h b/include/xrpl/ledger/helpers/LendingHelpers.h index 32f94ee277..8de945233b 100644 --- a/include/xrpl/ledger/helpers/LendingHelpers.h +++ b/include/xrpl/ledger/helpers/LendingHelpers.h @@ -4,6 +4,7 @@ #include #include +#include #include namespace xrpl { @@ -397,7 +398,7 @@ struct LoanStateDeltas nonNegative(); }; -Expected, TER> +std::expected, TER> tryOverpayment( Rules const& rules, Asset const& asset, @@ -523,7 +524,7 @@ isRounded(Asset const& asset, Number const& value, std::int32_t scale); // potential extra work at the end. enum class LoanPaymentType { Regular = 0, Late, Full, Overpayment }; -Expected +std::expected loanMakePayment( Asset const& asset, ApplyView& view, diff --git a/include/xrpl/protocol/STTx.h b/include/xrpl/protocol/STTx.h index 4deedfafb7..659fede31d 100644 --- a/include/xrpl/protocol/STTx.h +++ b/include/xrpl/protocol/STTx.h @@ -1,6 +1,5 @@ #pragma once -#include #include #include #include @@ -11,6 +10,7 @@ #include +#include #include namespace xrpl { @@ -108,10 +108,10 @@ public: @param rules The current ledger rules. @return `true` if valid signature. If invalid, the error message string. */ - Expected + std::expected checkSign(Rules const& rules) const; - Expected + std::expected checkBatchSign(Rules const& rules) const; // SQL Functions with metadata. @@ -138,19 +138,19 @@ private: Will be *this more often than not. @return `true` if valid signature. If invalid, the error message string. */ - Expected + std::expected checkSign(Rules const& rules, STObject const& sigObject) const; - Expected + std::expected checkSingleSign(STObject const& sigObject) const; - Expected + std::expected checkMultiSign(Rules const& rules, STObject const& sigObject) const; - Expected + std::expected checkBatchSingleSign(STObject const& batchSigner) const; - Expected + std::expected checkBatchMultiSign(STObject const& batchSigner, Rules const& rules) const; STBase* diff --git a/include/xrpl/protocol/XChainAttestations.h b/include/xrpl/protocol/XChainAttestations.h index 993f478b5e..457af727a2 100644 --- a/include/xrpl/protocol/XChainAttestations.h +++ b/include/xrpl/protocol/XChainAttestations.h @@ -1,7 +1,6 @@ #pragma once #include -#include #include #include #include @@ -15,6 +14,7 @@ #include #include +#include #include #include diff --git a/include/xrpl/protocol/detail/STVar.h b/include/xrpl/protocol/detail/STVar.h index 98a0b8dcd2..71077d4b33 100644 --- a/include/xrpl/protocol/detail/STVar.h +++ b/include/xrpl/protocol/detail/STVar.h @@ -37,7 +37,7 @@ private: // The largest "small object" we can accommodate static constexpr std::size_t kMaxSize = 72; - std::aligned_storage::type d_ = {}; + alignas(std::max_align_t) std::byte d_[kMaxSize] = {}; STBase* p_ = nullptr; public: diff --git a/include/xrpl/protocol/tokens.h b/include/xrpl/protocol/tokens.h index 125cfe8583..67cb25c7fb 100644 --- a/include/xrpl/protocol/tokens.h +++ b/include/xrpl/protocol/tokens.h @@ -1,10 +1,10 @@ #pragma once -#include #include #include #include +#include #include #include #include @@ -13,7 +13,7 @@ namespace xrpl { template -using B58Result = Expected; +using B58Result = std::expected; enum class TokenType : std::uint8_t { None = 1, // unused diff --git a/include/xrpl/tx/SignerEntries.h b/include/xrpl/tx/SignerEntries.h index 91fc4bd030..af0c9b9d28 100644 --- a/include/xrpl/tx/SignerEntries.h +++ b/include/xrpl/tx/SignerEntries.h @@ -1,11 +1,11 @@ #pragma once -#include // #include // beast::Journal #include // temMALFORMED #include // AccountID #include // NotTEC +#include #include #include @@ -60,7 +60,7 @@ public: // obj Contains a SignerEntries field that is an STArray. // journal For reporting error conditions. // annotation Source of SignerEntries, like "ledger" or "transaction". - static Expected, NotTEC> + static std::expected, NotTEC> deserialize(STObject const& obj, beast::Journal journal, std::string_view annotation); }; diff --git a/include/xrpl/tx/transactors/token/MPTokenIssuanceCreate.h b/include/xrpl/tx/transactors/token/MPTokenIssuanceCreate.h index a706c71e18..d946587e32 100644 --- a/include/xrpl/tx/transactors/token/MPTokenIssuanceCreate.h +++ b/include/xrpl/tx/transactors/token/MPTokenIssuanceCreate.h @@ -1,9 +1,10 @@ #pragma once -#include #include #include +#include + namespace xrpl { // NOLINTBEGIN(readability-redundant-member-init) @@ -61,7 +62,7 @@ public: ReadView const& view, beast::Journal const& j) override; - static Expected + static std::expected create(ApplyView& view, beast::Journal journal, MPTCreateArgs const& args); }; diff --git a/include/xrpl/tx/transactors/vault/VaultClawback.h b/include/xrpl/tx/transactors/vault/VaultClawback.h index b8032809ee..2ff97abca2 100644 --- a/include/xrpl/tx/transactors/vault/VaultClawback.h +++ b/include/xrpl/tx/transactors/vault/VaultClawback.h @@ -2,6 +2,8 @@ #include +#include + namespace xrpl { class VaultClawback : public Transactor @@ -34,7 +36,7 @@ public: beast::Journal const& j) override; private: - Expected, TER> + std::expected, TER> assetsToClawback( SLE::ref vault, SLE::const_ref sleShareIssuance, diff --git a/src/libxrpl/ledger/helpers/AMMHelpers.cpp b/src/libxrpl/ledger/helpers/AMMHelpers.cpp index fe6d022490..a59b8e4436 100644 --- a/src/libxrpl/ledger/helpers/AMMHelpers.cpp +++ b/src/libxrpl/ledger/helpers/AMMHelpers.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -34,6 +33,7 @@ #include #include #include +#include #include #include #include @@ -433,7 +433,7 @@ ammPoolHolds( return std::make_pair(assetInBalance, assetOutBalance); } -Expected, TER> +std::expected, TER> ammHolds( ReadView const& view, SLE const& ammSle, @@ -489,7 +489,7 @@ ammHolds( return std::make_optional(std::make_pair(asset1, asset2)); }(); if (!assets) - return Unexpected(tecAMM_INVALID_TOKENS); + return std::unexpected(tecAMM_INVALID_TOKENS); auto const [amount1, amount2] = ammPoolHolds( view, ammSle.getAccountID(sfAccount), @@ -821,7 +821,7 @@ initializeFeeAuctionVote( auctionSlot.makeFieldAbsent(sfAuthAccounts); } -Expected +std::expected isOnlyLiquidityProvider(ReadView const& view, Issue const& ammIssue, AccountID const& lpAccount) { // Liquidity Provider (LP) must have one LPToken trustline @@ -852,18 +852,18 @@ isOnlyLiquidityProvider(ReadView const& view, Issue const& ammIssue, AccountID c { auto const ownerDir = view.read(currentIndex); if (!ownerDir) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE for (auto const& key : ownerDir->getFieldV256(sfIndexes)) { auto const sle = view.read(keylet::child(key)); if (!sle) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE auto const entryType = sle->getFieldU16(sfLedgerEntryType); // Only one AMM object if (entryType == ltAMM) { if (hasAMM) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE hasAMM = true; continue; } @@ -873,7 +873,7 @@ isOnlyLiquidityProvider(ReadView const& view, Issue const& ammIssue, AccountID c continue; } if (entryType != ltRIPPLE_STATE) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE auto const lowLimit = sle->getFieldAmount(sfLowLimit); auto const highLimit = sle->getFieldAmount(sfHighLimit); auto const isLPTrustline = @@ -889,12 +889,12 @@ isOnlyLiquidityProvider(ReadView const& view, Issue const& ammIssue, AccountID c { // LP has exactly one LPToken trustline if (++nLPTokenTrustLines > 1) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE } // AMM account has at most two IOU trustlines else if (++nIOUTrustLines > 2) { - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE } } // Another Liquidity Provider LPToken trustline @@ -905,7 +905,7 @@ isOnlyLiquidityProvider(ReadView const& view, Issue const& ammIssue, AccountID c // AMM account has at most two IOU trustlines else if (++nIOUTrustLines > 2) { - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE } } auto const uNodeNext = ownerDir->getFieldU64(sfIndexNext); @@ -913,15 +913,15 @@ isOnlyLiquidityProvider(ReadView const& view, Issue const& ammIssue, AccountID c { if (nLPTokenTrustLines != 1 || (nIOUTrustLines == 0 && nMPT == 0) || (nIOUTrustLines > 2 || nMPT > 2) || (nIOUTrustLines + nMPT) > 2) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE return true; } currentIndex = keylet::page(root, uNodeNext); } - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE } -Expected +std::expected verifyAndAdjustLPTokenBalance( Sandbox& sb, STAmount const& lpTokens, @@ -931,7 +931,7 @@ verifyAndAdjustLPTokenBalance( auto const res = isOnlyLiquidityProvider(sb, lpTokens.get(), account); if (!res.has_value()) { - return Unexpected(res.error()); + return std::unexpected(res.error()); } if (res.value()) @@ -944,7 +944,7 @@ verifyAndAdjustLPTokenBalance( } else { - return Unexpected(tecAMM_INVALID_TOKENS); + return std::unexpected(tecAMM_INVALID_TOKENS); } } return true; diff --git a/src/libxrpl/ledger/helpers/AccountRootHelpers.cpp b/src/libxrpl/ledger/helpers/AccountRootHelpers.cpp index 1634de93c9..1c4acc7bc4 100644 --- a/src/libxrpl/ledger/helpers/AccountRootHelpers.cpp +++ b/src/libxrpl/ledger/helpers/AccountRootHelpers.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -22,6 +21,7 @@ #include #include +#include #include #include #include @@ -202,7 +202,7 @@ isPseudoAccount(SLE::const_pointer sleAcct, std::set const& pseud }) > 0; } -Expected +std::expected createPseudoAccount(ApplyView& view, uint256 const& pseudoOwnerKey, SField const& ownerField) { [[maybe_unused]] @@ -216,7 +216,7 @@ createPseudoAccount(ApplyView& view, uint256 const& pseudoOwnerKey, SField const auto const accountId = pseudoAccountAddress(view, pseudoOwnerKey); if (accountId == beast::kZero) - return Unexpected(tecDUPLICATE); + return std::unexpected(tecDUPLICATE); // Create pseudo-account. auto account = std::make_shared(keylet::account(accountId)); diff --git a/src/libxrpl/ledger/helpers/CredentialHelpers.cpp b/src/libxrpl/ledger/helpers/CredentialHelpers.cpp index 28b50b51d6..ca5876f88a 100644 --- a/src/libxrpl/ledger/helpers/CredentialHelpers.cpp +++ b/src/libxrpl/ledger/helpers/CredentialHelpers.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -24,6 +23,7 @@ #include #include +#include #include #include #include @@ -43,7 +43,7 @@ checkExpired(SLE const& sleCredential, NetClock::time_point const& closed) } [[nodiscard]] -static Expected +static std::expected removeExpired(ApplyView& view, STVector256 const& arr, beast::Journal const j) { auto const closeTime = view.header().parentCloseTime; @@ -61,7 +61,7 @@ removeExpired(ApplyView& view, STVector256 const& arr, beast::Journal const j) // delete expired credentials even if the transaction failed auto const err = deleteSLE(view, sleCred, j); if (view.rules().enabled(fixCleanup3_1_3) && !isTesSuccess(err)) - return Unexpected(err); + return std::unexpected(err); foundExpired = true; } } diff --git a/src/libxrpl/ledger/helpers/LendingHelpers.cpp b/src/libxrpl/ledger/helpers/LendingHelpers.cpp index 0a195f9cbe..676b473132 100644 --- a/src/libxrpl/ledger/helpers/LendingHelpers.cpp +++ b/src/libxrpl/ledger/helpers/LendingHelpers.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -25,6 +24,7 @@ #include #include #include +#include #include #include @@ -514,7 +514,7 @@ doPayment( * The function preserves accumulated rounding errors across the re-amortization * to ensure the loan state remains consistent with its payment history. */ -Expected, TER> +std::expected, TER> tryOverpayment( Rules const& rules, Asset const& asset, @@ -643,7 +643,7 @@ tryOverpayment( JLOG(j.warn()) << "Principal overpayment would cause the loan to be in " "an invalid state. Ignore the overpayment"; - return Unexpected(tesSUCCESS); + return std::unexpected(tesSUCCESS); } // Validate that all computed properties are reasonable. These checks should @@ -660,7 +660,7 @@ tryOverpayment( << ", PeriodicPayment : " << newLoanProperties.periodicPayment << ", ManagementFeeOwedToBroker: " << newLoanProperties.loanState.managementFeeDue; - return Unexpected(tesSUCCESS); + return std::unexpected(tesSUCCESS); // LCOV_EXCL_STOP } @@ -685,7 +685,7 @@ tryOverpayment( { JLOG(j.warn()) << "Principal overpayment would increase the value of " "the loan. Ignore the overpayment"; - return Unexpected(tesSUCCESS); + return std::unexpected(tesSUCCESS); } return std::make_pair( @@ -718,7 +718,7 @@ tryOverpayment( * gracefully without corrupting the ledger data. */ template -Expected +std::expected doOverpayment( Rules const& rules, Asset const& asset, @@ -760,7 +760,7 @@ doOverpayment( managementFeeRate, j); if (!ret) - return Unexpected(ret.error()); + return std::unexpected(ret.error()); auto const& [loanPaymentParts, newLoanProperties] = *ret; auto const newRoundedLoanState = newLoanProperties.loanState; @@ -774,7 +774,7 @@ doOverpayment( JLOG(j.warn()) << "Overpayment not allowed: principal " << "outstanding did not decrease. Before: " << *principalOutstandingProxy << ". After: " << newRoundedLoanState.principalOutstanding; - return Unexpected(tesSUCCESS); + return std::unexpected(tesSUCCESS); // LCOV_EXCL_STOP } @@ -860,7 +860,7 @@ doOverpayment( * * Implements equation (15) from XLS-66 spec, Section A-2 Equation Glossary */ -Expected +std::expected computeLatePayment( Asset const& asset, ApplyView const& view, @@ -877,7 +877,7 @@ computeLatePayment( // Check if the due date has passed. If not, reject the payment as // being too soon if (!hasExpired(view, nextDueDate)) - return Unexpected(tecTOO_SOON); + return std::unexpected(tecTOO_SOON); // Calculate the penalty interest based on how long the payment is overdue. auto const latePaymentInterest = loanLatePaymentInterest( @@ -929,7 +929,7 @@ computeLatePayment( { JLOG(j.warn()) << "Late loan payment amount is insufficient. Due: " << late.totalDue << ", paid: " << amount; - return Unexpected(tecINSUFFICIENT_PAYMENT); + return std::unexpected(tecINSUFFICIENT_PAYMENT); } return late; @@ -954,7 +954,7 @@ computeLatePayment( * * Implements equation (26) from XLS-66 spec, Section A-2 Equation Glossary */ -Expected +std::expected computeFullPayment( Asset const& asset, ApplyView& view, @@ -979,7 +979,7 @@ computeFullPayment( { // If this is the last payment, it has to be a regular payment JLOG(j.warn()) << "Last payment cannot be a full payment."; - return Unexpected(tecKILLED); + return std::unexpected(tecKILLED); } // Calculate the theoretical principal based on the payment schedule. @@ -1059,7 +1059,7 @@ computeFullPayment( { // If the payment is less than the full payment amount, it's not // sufficient to be a full payment. - return Unexpected(tecINSUFFICIENT_PAYMENT); + return std::unexpected(tecINSUFFICIENT_PAYMENT); } return full; @@ -1780,7 +1780,7 @@ computeLoanProperties( * It is an implementation of the make_payment function from the XLS-66 * spec. Section 3.2.4.4 */ -Expected +std::expected loanMakePayment( Asset const& asset, ApplyView& view, @@ -1800,7 +1800,7 @@ loanMakePayment( // Loan complete this is already checked in LoanPay::preclaim() // LCOV_EXCL_START JLOG(j.warn()) << "Loan is already paid off."; - return Unexpected(tecKILLED); + return std::unexpected(tecKILLED); // LCOV_EXCL_STOP } @@ -1812,7 +1812,7 @@ loanMakePayment( if (*nextDueDateProxy == 0) { JLOG(j.warn()) << "Loan next payment due date is not set."; - return Unexpected(tecINTERNAL); + return std::unexpected(tecINTERNAL); } std::int32_t const loanScale = loan->at(sfLoanScale); @@ -1850,7 +1850,7 @@ loanMakePayment( << startDate << ", prev payment due date is " << prevPaymentDateProxy << ", next payment due date is " << nextDueDateProxy << ", ledger time is " << view.parentCloseTime().time_since_epoch().count(); - return Unexpected(tecEXPIRED); + return std::unexpected(tecEXPIRED); } // ------------------------------------------------------------- @@ -1900,13 +1900,13 @@ loanMakePayment( // error() will be the TER returned if a payment is not made. It // will only evaluate to true if it's unsuccessful. Otherwise, // tesSUCCESS means nothing was done, so continue. - return Unexpected(fullPaymentComponents.error()); + return std::unexpected(fullPaymentComponents.error()); } // LCOV_EXCL_START UNREACHABLE("xrpl::loanMakePayment : invalid full payment result"); JLOG(j.error()) << "Full payment computation failed unexpectedly."; - return Unexpected(tecINTERNAL); + return std::unexpected(tecINTERNAL); // LCOV_EXCL_STOP } @@ -1968,13 +1968,13 @@ loanMakePayment( { // error() will be the TER returned if a payment is not made. It // will only evaluate to true if it's unsuccessful. - return Unexpected(latePaymentComponents.error()); + return std::unexpected(latePaymentComponents.error()); } // LCOV_EXCL_START UNREACHABLE("xrpl::loanMakePayment : invalid late payment result"); JLOG(j.error()) << "Late payment computation failed unexpectedly."; - return Unexpected(tecINTERNAL); + return std::unexpected(tecINTERNAL); // LCOV_EXCL_STOP } @@ -2041,7 +2041,7 @@ loanMakePayment( { JLOG(j.warn()) << "Regular loan payment amount is insufficient. Due: " << periodic.totalDue << ", paid: " << amount; - return Unexpected(tecINSUFFICIENT_PAYMENT); + return std::unexpected(tecINSUFFICIENT_PAYMENT); } XRPL_ASSERT_PARTS( @@ -2127,7 +2127,7 @@ loanMakePayment( // made. It will only evaluate to true if it's unsuccessful. // Otherwise, tesSUCCESS means nothing was done, so // continue. - return Unexpected(overResult.error()); + return std::unexpected(overResult.error()); } } } diff --git a/src/libxrpl/protocol/STTx.cpp b/src/libxrpl/protocol/STTx.cpp index 2777981fd7..55f0ea1289 100644 --- a/src/libxrpl/protocol/STTx.cpp +++ b/src/libxrpl/protocol/STTx.cpp @@ -1,7 +1,6 @@ #include #include -#include #include #include #include @@ -40,6 +39,7 @@ #include #include #include +#include #include #include #include @@ -248,7 +248,7 @@ STTx::sign( tid_ = getHash(HashPrefix::TransactionId); } -Expected +std::expected STTx::checkSign(Rules const& rules, STObject const& sigObject) const { try @@ -263,11 +263,11 @@ STTx::checkSign(Rules const& rules, STObject const& sigObject) const } catch (...) { - return Unexpected("Internal signature check failure."); + return std::unexpected("Internal signature check failure."); } } -Expected +std::expected STTx::checkSign(Rules const& rules) const { if (auto const ret = checkSign(rules, *this); !ret) @@ -277,12 +277,12 @@ STTx::checkSign(Rules const& rules) const { auto const counterSig = getFieldObject(sfCounterpartySignature); if (auto const ret = checkSign(rules, counterSig); !ret) - return Unexpected("Counterparty: " + ret.error()); + return std::unexpected("Counterparty: " + ret.error()); } return {}; } -Expected +std::expected STTx::checkBatchSign(Rules const& rules) const { try @@ -291,7 +291,7 @@ STTx::checkBatchSign(Rules const& rules) const if (getTxnType() != ttBATCH) { JLOG(debugLog().fatal()) << "not a batch transaction"; - return Unexpected("Not a batch transaction."); + return std::unexpected("Not a batch transaction."); } STArray const& signers{getFieldArray(sfBatchSigners)}; for (auto const& signer : signers) @@ -309,7 +309,7 @@ STTx::checkBatchSign(Rules const& rules) const { JLOG(debugLog().error()) << "Batch signature check failed: " << e.what(); } - return Unexpected("Internal batch signature check failure."); + return std::unexpected("Internal batch signature check failure."); } json::Value @@ -389,14 +389,14 @@ STTx::getMetaSQL( safeCast(status) % rTxn % escapedMetaData); } -static Expected +static std::expected singleSignHelper(STObject const& sigObject, Slice const& data) { // We don't allow both a non-empty sfSigningPubKey and an sfSigners. // That would allow the transaction to be signed two ways. So if both // fields are present the signature is invalid. if (sigObject.isFieldPresent(sfSigners)) - return Unexpected("Cannot both single- and multi-sign."); + return std::unexpected("Cannot both single- and multi-sign."); bool validSig = false; try @@ -414,19 +414,19 @@ singleSignHelper(STObject const& sigObject, Slice const& data) } if (!validSig) - return Unexpected("Invalid signature."); + return std::unexpected("Invalid signature."); return {}; } -Expected +std::expected STTx::checkSingleSign(STObject const& sigObject) const { auto const data = getSigningData(*this); return singleSignHelper(sigObject, makeSlice(data)); } -Expected +std::expected STTx::checkBatchSingleSign(STObject const& batchSigner) const { Serializer msg; @@ -434,7 +434,7 @@ STTx::checkBatchSingleSign(STObject const& batchSigner) const return singleSignHelper(batchSigner, msg.slice()); } -Expected +std::expected multiSignHelper( STObject const& sigObject, std::optional txnAccountID, @@ -444,18 +444,18 @@ multiSignHelper( // Make sure the MultiSigners are present. Otherwise they are not // attempting multi-signing and we just have a bad SigningPubKey. if (!sigObject.isFieldPresent(sfSigners)) - return Unexpected("Empty SigningPubKey."); + return std::unexpected("Empty SigningPubKey."); // We don't allow both an sfSigners and an sfTxnSignature. Both fields // being present would indicate that the transaction is signed both ways. if (sigObject.isFieldPresent(sfTxnSignature)) - return Unexpected("Cannot both single- and multi-sign."); + return std::unexpected("Cannot both single- and multi-sign."); STArray const& signers{sigObject.getFieldArray(sfSigners)}; // There are well known bounds that the number of signers must be within. if (signers.size() < STTx::kMinMultiSigners || signers.size() > STTx::kMaxMultiSigners) - return Unexpected("Invalid Signers array size."); + return std::unexpected("Invalid Signers array size."); // Signers must be in sorted order by AccountID. AccountID lastAccountID(beast::kZero); @@ -468,15 +468,15 @@ multiSignHelper( // If they can, txnAccountID will be unseated, which is not equal to any // value. if (txnAccountID == accountID) - return Unexpected("Invalid multisigner."); + return std::unexpected("Invalid multisigner."); // No duplicate signers allowed. if (lastAccountID == accountID) - return Unexpected("Duplicate Signers not allowed."); + return std::unexpected("Duplicate Signers not allowed."); // Accounts must be in order by account ID. No duplicates allowed. if (lastAccountID > accountID) - return Unexpected("Unsorted Signers array."); + return std::unexpected("Unsorted Signers array."); // The next signature must be greater than this one. lastAccountID = accountID; @@ -502,7 +502,7 @@ multiSignHelper( } if (!validSig) { - return Unexpected( + return std::unexpected( std::string("Invalid signature on account ") + toBase58(accountID) + errorWhat.value_or("") + "."); } @@ -511,7 +511,7 @@ multiSignHelper( return {}; } -Expected +std::expected STTx::checkBatchMultiSign(STObject const& batchSigner, Rules const& rules) const { // We can ease the computational load inside the loop a bit by @@ -530,7 +530,7 @@ STTx::checkBatchMultiSign(STObject const& batchSigner, Rules const& rules) const rules); } -Expected +std::expected STTx::checkMultiSign(Rules const& rules, STObject const& sigObject) const { // Used inside the loop in multiSignHelper to enforce that diff --git a/src/libxrpl/protocol/tokens.cpp b/src/libxrpl/protocol/tokens.cpp index a43cbd9c85..fcd822a747 100644 --- a/src/libxrpl/protocol/tokens.cpp +++ b/src/libxrpl/protocol/tokens.cpp @@ -9,7 +9,6 @@ #include -#include #include #include #include @@ -23,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -353,7 +353,7 @@ b256ToB58Be(std::span input, std::span out) // (33 bytes for nodepublic + 1 byte token + 4 bytes checksum) if (input.size() > 38) { - return Unexpected(TokenCodecErrc::InputTooLarge); + return std::unexpected(TokenCodecErrc::InputTooLarge); }; auto countLeadingZeros = [](std::span const& col) -> std::size_t { @@ -441,7 +441,7 @@ b256ToB58Be(std::span input, std::span out) static constexpr std::uint64_t kB5810 = 430804206899405824; // 58^10; if (base5810Coeff[i] >= kB5810) { - return Unexpected(TokenCodecErrc::InputTooLarge); + return std::unexpected(TokenCodecErrc::InputTooLarge); } std::array const b58Be = xrpl::b58_fast::detail::b5810ToB58Be(base5810Coeff[i]); @@ -453,7 +453,7 @@ b256ToB58Be(std::span input, std::span out) skipZeros = false; if (out.size() < ((i + 1) * 10) - toSkip) { - return Unexpected(TokenCodecErrc::OutputTooSmall); + return std::unexpected(TokenCodecErrc::OutputTooSmall); } } for (auto b58Coeff : b58BeS.subspan(toSkip)) @@ -476,11 +476,11 @@ b58ToB256Be(std::string_view input, std::span out) // log(2^(38*8),58) ~= 51.9 if (input.size() > 52) { - return Unexpected(TokenCodecErrc::InputTooLarge); + return std::unexpected(TokenCodecErrc::InputTooLarge); }; if (out.size() < 8) { - return Unexpected(TokenCodecErrc::OutputTooSmall); + return std::unexpected(TokenCodecErrc::OutputTooSmall); } auto countLeadingZeros = [&](auto const& col) -> std::size_t { @@ -513,7 +513,7 @@ b58ToB256Be(std::string_view input, std::span out) auto curVal = ::xrpl::kAlphabetReverse[c]; if (curVal < 0) { - return Unexpected(TokenCodecErrc::InvalidEncodingChar); + return std::unexpected(TokenCodecErrc::InvalidEncodingChar); } b5810Coeff[0] *= 58; b5810Coeff[0] += curVal; @@ -526,7 +526,7 @@ b58ToB256Be(std::string_view input, std::span out) auto curVal = ::xrpl::kAlphabetReverse[c]; if (curVal < 0) { - return Unexpected(TokenCodecErrc::InvalidEncodingChar); + return std::unexpected(TokenCodecErrc::InvalidEncodingChar); } b5810Coeff[numPartialCoeffs + j] *= 58; b5810Coeff[numPartialCoeffs + j] += curVal; @@ -548,7 +548,7 @@ b58ToB256Be(std::string_view input, std::span out) std::span(&result[0], curResultSize + 1), kB5810); if (code != TokenCodecErrc::Success) { - return Unexpected(code); + return std::unexpected(code); } } { @@ -556,7 +556,7 @@ b58ToB256Be(std::string_view input, std::span out) std::span(&result[0], curResultSize + 1), c); if (code != TokenCodecErrc::Success) { - return Unexpected(code); + return std::unexpected(code); } } if (result[curResultSize] != 0) @@ -589,7 +589,7 @@ b58ToB256Be(std::string_view input, std::span out) } if ((curOutI + (8 * (curResultSize - 1))) > out.size()) { - return Unexpected(TokenCodecErrc::OutputTooSmall); + return std::unexpected(TokenCodecErrc::OutputTooSmall); } for (int i = curResultSize - 2; i >= 0; --i) @@ -614,11 +614,11 @@ encodeBase58Token( std::array buf{}; if (input.size() > kTmpBufSize - 5) { - return Unexpected(TokenCodecErrc::InputTooLarge); + return std::unexpected(TokenCodecErrc::InputTooLarge); } if (input.empty()) { - return Unexpected(TokenCodecErrc::InputTooSmall); + return std::unexpected(TokenCodecErrc::InputTooSmall); } // buf[0] = static_cast(tokenType); @@ -648,23 +648,23 @@ decodeBase58Token(TokenType type, std::string_view s, std::span ou // Reject zero length tokens if (ret.size() < 6) - return Unexpected(TokenCodecErrc::InputTooSmall); + return std::unexpected(TokenCodecErrc::InputTooSmall); // The type must match. if (type != static_cast(static_cast(ret[0]))) - return Unexpected(TokenCodecErrc::MismatchedTokenType); + return std::unexpected(TokenCodecErrc::MismatchedTokenType); // And the checksum must as well. std::array guard{}; checksum(guard.data(), ret.data(), ret.size() - guard.size()); if (!std::equal(guard.rbegin(), guard.rend(), ret.rbegin())) { - return Unexpected(TokenCodecErrc::MismatchedChecksum); + return std::unexpected(TokenCodecErrc::MismatchedChecksum); } std::size_t const outSize = ret.size() - 1 - guard.size(); if (outBuf.size() < outSize) - return Unexpected(TokenCodecErrc::OutputTooSmall); + return std::unexpected(TokenCodecErrc::OutputTooSmall); // Skip the leading type byte and the trailing checksum. std::copy(ret.begin() + 1, ret.begin() + outSize + 1, outBuf.begin()); return outBuf.subspan(0, outSize); diff --git a/src/libxrpl/tx/SignerEntries.cpp b/src/libxrpl/tx/SignerEntries.cpp index 7251b8260f..943b66292e 100644 --- a/src/libxrpl/tx/SignerEntries.cpp +++ b/src/libxrpl/tx/SignerEntries.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -12,19 +11,20 @@ #include #include +#include #include #include #include namespace xrpl { -Expected, NotTEC> +std::expected, NotTEC> SignerEntries::deserialize(STObject const& obj, beast::Journal journal, std::string_view annotation) { if (!obj.isFieldPresent(sfSignerEntries)) { JLOG(journal.trace()) << "Malformed " << annotation << ": Need signer entry array."; - return Unexpected(temMALFORMED); + return std::unexpected(temMALFORMED); } std::vector accountVec; @@ -37,7 +37,7 @@ SignerEntries::deserialize(STObject const& obj, beast::Journal journal, std::str if (sEntry.getFName() != sfSignerEntry) { JLOG(journal.trace()) << "Malformed " << annotation << ": Expected SignerEntry."; - return Unexpected(temMALFORMED); + return std::unexpected(temMALFORMED); } // Extract SignerEntry fields. diff --git a/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp b/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp index 7c9c9d95dc..273beaea0f 100644 --- a/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp +++ b/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -40,6 +39,7 @@ #include #include +#include #include #include #include @@ -186,7 +186,7 @@ checkAttestationPublicKey( enum class CheckDst { Check, Ignore }; template -Expected, TER> +std::expected, TER> claimHelper( XChainAttestationsBase& attestations, ReadView const& view, @@ -233,7 +233,7 @@ claimHelper( if (weight >= quorum) return rewardAccounts; - return Unexpected(tecXCHAIN_CLAIM_NO_QUORUM); + return std::unexpected(tecXCHAIN_CLAIM_NO_QUORUM); } /** @@ -337,7 +337,7 @@ onNewAttestations( // Check if there is a quorum of attestations for the given amount and // chain. If so return the reward accounts, if not return the tec code (most // likely tecXCHAIN_CLAIM_NO_QUORUM) -Expected, TER> +std::expected, TER> onClaim( XChainClaimAttestations& attestations, ReadView const& view, @@ -847,14 +847,14 @@ applyClaimAttestations( AccountID cidOwner; }; - auto const scopeResult = [&]() -> Expected { + auto const scopeResult = [&]() -> std::expected { // This lambda is ugly - admittedly. The purpose of this lambda is to // limit the scope of sles so they don't overlap with // `finalizeClaimHelper`. Since `finalizeClaimHelper` can create child // views, it's important that the sle's lifetime doesn't overlap. auto const sleClaimID = psb.peek(claimIDKeylet); if (!sleClaimID) - return Unexpected(tecXCHAIN_NO_CLAIM_ID); + return std::unexpected(tecXCHAIN_NO_CLAIM_ID); // Add claims that are part of the signer's list to the "claims" vector std::vector atts; @@ -868,13 +868,13 @@ applyClaimAttestations( if (atts.empty()) { - return Unexpected(tecXCHAIN_PROOF_UNKNOWN_KEY); + return std::unexpected(tecXCHAIN_PROOF_UNKNOWN_KEY); } AccountID const otherChainSource = (*sleClaimID)[sfOtherChainSource]; if (attBegin->sendingAccount != otherChainSource) { - return Unexpected(tecXCHAIN_SENDING_ACCOUNT_MISMATCH); + return std::unexpected(tecXCHAIN_SENDING_ACCOUNT_MISMATCH); } { @@ -885,7 +885,7 @@ applyClaimAttestations( if (attDstChain != dstChain) { - return Unexpected(tecXCHAIN_WRONG_CHAIN); + return std::unexpected(tecXCHAIN_WRONG_CHAIN); } } @@ -964,10 +964,10 @@ applyCreateAccountAttestations( PaymentSandbox psb(&view); - auto const claimCountResult = [&]() -> Expected { + auto const claimCountResult = [&]() -> std::expected { auto const sleBridge = psb.peek(bridgeK); if (!sleBridge) - return Unexpected(tecINTERNAL); + return std::unexpected(tecINTERNAL); return (*sleBridge)[sfXChainAccountClaimCount]; }(); @@ -1009,7 +1009,7 @@ applyCreateAccountAttestations( XChainCreateAccountAttestations curAtts; }; - auto const scopeResult = [&]() -> Expected { + auto const scopeResult = [&]() -> std::expected { // This lambda is ugly - admittedly. The purpose of this lambda is to // limit the scope of sles so they don't overlap with // `finalizeClaimHelper`. Since `finalizeClaimHelper` can create child @@ -1025,14 +1025,14 @@ applyCreateAccountAttestations( auto const sleDoor = psb.peek(doorK); if (!sleDoor) - return Unexpected(tecINTERNAL); + return std::unexpected(tecINTERNAL); // Check reserve auto const balance = (*sleDoor)[sfBalance]; auto const reserve = psb.fees().accountReserve((*sleDoor)[sfOwnerCount] + 1); if (balance < reserve) - return Unexpected(tecINSUFFICIENT_RESERVE); + return std::unexpected(tecINSUFFICIENT_RESERVE); } std::vector atts; @@ -1045,7 +1045,7 @@ applyCreateAccountAttestations( } if (atts.empty()) { - return Unexpected(tecXCHAIN_PROOF_UNKNOWN_KEY); + return std::unexpected(tecXCHAIN_PROOF_UNKNOWN_KEY); } XChainCreateAccountAttestations curAtts = [&] { @@ -1071,7 +1071,7 @@ applyCreateAccountAttestations( // Modify the object before it's potentially deleted, so the meta // data will include the new attestations if (!sleClaimID) - return Unexpected(tecINTERNAL); + return std::unexpected(tecINTERNAL); sleClaimID->setFieldArray(sfXChainCreateAccountAttestations, curAtts.toSTArray()); psb.update(sleClaimID); } @@ -1244,7 +1244,7 @@ attestationDoApply(ApplyContext& ctx) Keylet bridgeK; }; - auto const scopeResult = [&]() -> Expected { + auto const scopeResult = [&]() -> std::expected { // This lambda is ugly - admittedly. The purpose of this lambda is to // limit the scope of sles so they don't overlap with // `finalizeClaimHelper`. Since `finalizeClaimHelper` can create child @@ -1252,7 +1252,7 @@ attestationDoApply(ApplyContext& ctx) auto sleBridge = readBridge(ctx.view(), bridgeSpec); if (!sleBridge) { - return Unexpected(tecNO_ENTRY); + return std::unexpected(tecNO_ENTRY); } Keylet const bridgeK{ltBRIDGE, sleBridge->key()}; AccountID const thisDoor = (*sleBridge)[sfAccount]; @@ -1269,7 +1269,7 @@ attestationDoApply(ApplyContext& ctx) } else { - return Unexpected(tecINTERNAL); + return std::unexpected(tecINTERNAL); } } STXChainBridge::ChainType const srcChain = STXChainBridge::otherChain(dstChain); @@ -1279,7 +1279,7 @@ attestationDoApply(ApplyContext& ctx) getSignersListAndQuorum(ctx.view(), *sleBridge, ctx.journal); if (!isTesSuccess(slTer)) - return Unexpected(slTer); + return std::unexpected(slTer); return ScopeResult{srcChain, std::move(signersList), quorum, thisDoor, bridgeK}; }(); @@ -1721,7 +1721,7 @@ XChainClaim::doApply() STAmount signatureReward; }; - auto const scopeResult = [&]() -> Expected { + auto const scopeResult = [&]() -> std::expected { // This lambda is ugly - admittedly. The purpose of this lambda is to // limit the scope of sles so they don't overlap with // `finalizeClaimHelper`. Since `finalizeClaimHelper` can create child @@ -1732,7 +1732,7 @@ XChainClaim::doApply() auto const sleClaimID = psb.peek(claimIDKeylet); if (!(sleBridge && sleClaimID && sleAcct)) - return Unexpected(tecINTERNAL); + return std::unexpected(tecINTERNAL); AccountID const thisDoor = (*sleBridge)[sfAccount]; @@ -1748,7 +1748,7 @@ XChainClaim::doApply() } else { - return Unexpected(tecINTERNAL); + return std::unexpected(tecINTERNAL); } } STXChainBridge::ChainType const srcChain = STXChainBridge::otherChain(dstChain); @@ -1763,7 +1763,7 @@ XChainClaim::doApply() getSignersListAndQuorum(ctx_.view(), *sleBridge, ctx_.journal); if (!isTesSuccess(slTer)) - return Unexpected(slTer); + return std::unexpected(slTer); XChainClaimAttestations curAtts{sleClaimID->getFieldArray(sfXChainClaimAttestations)}; @@ -1776,7 +1776,7 @@ XChainClaim::doApply() signersList, ctx_.journal); if (!claimR.has_value()) - return Unexpected(claimR.error()); + return std::unexpected(claimR.error()); return ScopeResult{ .rewardAccounts = claimR.value(), diff --git a/src/libxrpl/tx/transactors/dex/AMMBid.cpp b/src/libxrpl/tx/transactors/dex/AMMBid.cpp index a98f439d0a..83432fa0d0 100644 --- a/src/libxrpl/tx/transactors/dex/AMMBid.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMBid.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -27,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -266,7 +266,7 @@ applyBid(ApplyContext& ctx, Sandbox& sb, AccountID const& account, beast::Journa auto const bidMin = ctx.tx[~sfBidMin]; auto const bidMax = ctx.tx[~sfBidMax]; - auto getPayPrice = [&](Number const& computedPrice) -> Expected { + auto getPayPrice = [&](Number const& computedPrice) -> std::expected { auto const payPrice = [&]() -> std::optional { // Both min/max bid price are defined if (bidMin && bidMax) @@ -295,11 +295,11 @@ applyBid(ApplyContext& ctx, Sandbox& sb, AccountID const& account, beast::Journa }(); if (!payPrice) { - return Unexpected(tecAMM_FAILED); + return std::unexpected(tecAMM_FAILED); } if (payPrice > lpTokens) { - return Unexpected(tecAMM_INVALID_TOKENS); + return std::unexpected(tecAMM_INVALID_TOKENS); } return *payPrice; }; diff --git a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp index 0e1a4b3a3d..041bf73abf 100644 --- a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -28,6 +27,7 @@ #include #include +#include #include #include @@ -83,7 +83,7 @@ LoanBrokerCoverClawback::preflight(PreflightContext const& ctx) return tesSUCCESS; } -Expected +std::expected determineBrokerID(ReadView const& view, STTx const& tx) { // If the broker ID was provided in the transaction, that's all we @@ -96,7 +96,7 @@ determineBrokerID(ReadView const& view, STTx const& tx) // because that should have been rejected in preflight(). auto const dstAmount = tx[~sfAmount]; if (!dstAmount || !dstAmount->holds()) - return Unexpected{tecINTERNAL}; // LCOV_EXCL_LINE + return std::unexpected{tecINTERNAL}; // LCOV_EXCL_LINE // Every trust line is bidirectional. Both sides are simultaneously // issuer and holder. For this transaction, the Account is acting as @@ -112,7 +112,7 @@ determineBrokerID(ReadView const& view, STTx const& tx) // If the account was not found, the transaction can't go further. if (!sle) - return Unexpected{tecNO_ENTRY}; + return std::unexpected{tecNO_ENTRY}; // If the account was found, and has a LoanBrokerID (and therefore // is a pseudo-account), that's the @@ -122,11 +122,11 @@ determineBrokerID(ReadView const& view, STTx const& tx) // If the account does not have a LoanBrokerID, the transaction // can't go further, even if it's a different type of Pseudo-account. - return Unexpected{tecOBJECT_NOT_FOUND}; + return std::unexpected{tecOBJECT_NOT_FOUND}; // Or tecWRONG_ASSET? } -Expected +std::expected determineAsset( ReadView const& view, AccountID const& account, @@ -153,10 +153,10 @@ determineAsset( return Issue{amount.get().currency, account}; } - return Unexpected(tecWRONG_ASSET); + return std::unexpected(tecWRONG_ASSET); } -Expected +std::expected determineClawAmount( SLE const& sleBroker, Asset const& vaultAsset, @@ -182,7 +182,7 @@ determineClawAmount( return sleBroker[sfCoverAvailable] - minRequiredCover; }(); if (maxClawAmount <= beast::kZero) - return Unexpected(tecINSUFFICIENT_FUNDS); + return std::unexpected(tecINSUFFICIENT_FUNDS); // Use the vaultAsset here, because it will be the right type in all // circumstances. The amount may be an IOU indicating the pseudo-account's diff --git a/src/libxrpl/tx/transactors/lending/LoanPay.cpp b/src/libxrpl/tx/transactors/lending/LoanPay.cpp index a0a1479bdb..5c0b46de42 100644 --- a/src/libxrpl/tx/transactors/lending/LoanPay.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanPay.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -29,6 +28,7 @@ #include #include #include +#include #include namespace xrpl { @@ -380,7 +380,7 @@ LoanPay::doApply() return LoanPaymentType::Regular; }(); - Expected const paymentParts = + std::expected const paymentParts = loanMakePayment(asset, view, loanSle, brokerSle, amount, paymentType, j_); if (!paymentParts) diff --git a/src/libxrpl/tx/transactors/nft/NFTokenMint.cpp b/src/libxrpl/tx/transactors/nft/NFTokenMint.cpp index bd7413d50b..d8e5a7b235 100644 --- a/src/libxrpl/tx/transactors/nft/NFTokenMint.cpp +++ b/src/libxrpl/tx/transactors/nft/NFTokenMint.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -26,6 +25,7 @@ #include #include #include +#include #include // IWYU pragma: keep #include @@ -223,12 +223,12 @@ NFTokenMint::doApply() { auto const issuer = ctx_.tx[~sfIssuer].value_or(accountID_); - auto const tokenSeq = [this, &issuer]() -> Expected { + auto const tokenSeq = [this, &issuer]() -> std::expected { auto const root = view().peek(keylet::account(issuer)); if (root == nullptr) { // Should not happen. Checked in preclaim. - return Unexpected(tecNO_ISSUER); + return std::unexpected(tecNO_ISSUER); } // If the issuer hasn't minted an NFToken before we must add a @@ -259,7 +259,7 @@ NFTokenMint::doApply() (*root)[sfMintedNFTokens] = mintedNftCnt + 1u; if ((*root)[sfMintedNFTokens] == 0u) - return Unexpected(tecMAX_SEQUENCE_REACHED); + return std::unexpected(tecMAX_SEQUENCE_REACHED); // Get the unique sequence number of this token by // sfFirstNFTokenSequence + sfMintedNFTokens @@ -268,7 +268,7 @@ NFTokenMint::doApply() // Check for more overflow cases if (tokenSeq + 1u == 0u || tokenSeq < offset) - return Unexpected(tecMAX_SEQUENCE_REACHED); + return std::unexpected(tecMAX_SEQUENCE_REACHED); ctx_.view().update(root); return tokenSeq; diff --git a/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp b/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp index 94a5ca848d..90e33d3a70 100644 --- a/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp +++ b/src/libxrpl/tx/transactors/token/MPTokenIssuanceCreate.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -22,6 +21,7 @@ #include #include +#include #include namespace xrpl { @@ -100,16 +100,16 @@ MPTokenIssuanceCreate::preflight(PreflightContext const& ctx) return tesSUCCESS; } -Expected +std::expected MPTokenIssuanceCreate::create(ApplyView& view, beast::Journal journal, MPTCreateArgs const& args) { auto const acct = view.peek(keylet::account(args.account)); if (!acct) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE if (args.priorBalance && *(args.priorBalance) < view.fees().accountReserve((*acct)[sfOwnerCount] + 1)) - return Unexpected(tecINSUFFICIENT_RESERVE); + return std::unexpected(tecINSUFFICIENT_RESERVE); auto const mptId = makeMptID(args.sequence, args.account); auto const mptIssuanceKeylet = keylet::mptIssuance(mptId); @@ -120,7 +120,7 @@ MPTokenIssuanceCreate::create(ApplyView& view, beast::Journal journal, MPTCreate keylet::ownerDir(args.account), mptIssuanceKeylet, describeOwnerDir(args.account)); if (!ownerNode) - return Unexpected(tecDIR_FULL); // LCOV_EXCL_LINE + return std::unexpected(tecDIR_FULL); // LCOV_EXCL_LINE auto mptIssuance = std::make_shared(mptIssuanceKeylet); (*mptIssuance)[sfFlags] = args.flags & ~tfUniversal; @@ -156,10 +156,10 @@ MPTokenIssuanceCreate::create(ApplyView& view, beast::Journal journal, MPTCreate // would dangle the pointer and is a programmer error. auto const sleHolding = view.read(keylet::unchecked(*args.referenceHolding)); if (!sleHolding) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE auto const type = sleHolding->getType(); if (type != ltMPTOKEN && type != ltRIPPLE_STATE) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE (*mptIssuance)[sfReferenceHolding] = *args.referenceHolding; } diff --git a/src/libxrpl/tx/transactors/vault/VaultClawback.cpp b/src/libxrpl/tx/transactors/vault/VaultClawback.cpp index eb12905467..a8587feaeb 100644 --- a/src/libxrpl/tx/transactors/vault/VaultClawback.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultClawback.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -26,6 +25,7 @@ #include #include +#include #include #include #include @@ -218,7 +218,7 @@ VaultClawback::preclaim(PreclaimContext const& ctx) return tecWRONG_ASSET; } -Expected, TER> +std::expected, TER> VaultClawback::assetsToClawback( SLE::ref vault, SLE::const_ref sleShareIssuance, @@ -230,7 +230,7 @@ VaultClawback::assetsToClawback( // preclaim should have blocked this , now it's an internal error // LCOV_EXCL_START JLOG(j_.error()) << "VaultClawback: asset mismatch in clawback."; - return Unexpected(tecINTERNAL); + return std::unexpected(tecINTERNAL); // LCOV_EXCL_STOP } @@ -248,7 +248,7 @@ VaultClawback::assetsToClawback( view(), holder, share, FreezeHandling::IgnoreFreeze, AuthHandling::IgnoreAuth, j_); auto const maybeAssets = sharesToAssetsWithdraw(vault, sleShareIssuance, sharesDestroyed); if (!maybeAssets) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE return std::make_pair(*maybeAssets, sharesDestroyed); } @@ -265,7 +265,7 @@ VaultClawback::assetsToClawback( auto const maybeAssets = sharesToAssetsWithdraw(vault, sleShareIssuance, sharesDestroyed); if (!maybeAssets) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE assetsRecovered = *maybeAssets; } @@ -274,13 +274,13 @@ VaultClawback::assetsToClawback( auto const maybeShares = assetsToSharesWithdraw(vault, sleShareIssuance, clawbackAmount); if (!maybeShares) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE sharesDestroyed = *maybeShares; auto const maybeAssets = sharesToAssetsWithdraw(vault, sleShareIssuance, sharesDestroyed); if (!maybeAssets) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE assetsRecovered = *maybeAssets; } // Clamp to maximum. @@ -294,20 +294,20 @@ VaultClawback::assetsToClawback( auto const maybeShares = assetsToSharesWithdraw( vault, sleShareIssuance, assetsRecovered, TruncateShares::Yes); if (!maybeShares) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE sharesDestroyed = *maybeShares; } auto const maybeAssets = sharesToAssetsWithdraw(vault, sleShareIssuance, sharesDestroyed); if (!maybeAssets) - return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE assetsRecovered = *maybeAssets; if (assetsRecovered > *assetsAvailable) { // LCOV_EXCL_START JLOG(j_.error()) << "VaultClawback: invalid rounding of shares."; - return Unexpected(tecINTERNAL); + return std::unexpected(tecINTERNAL); // LCOV_EXCL_STOP } } @@ -322,7 +322,7 @@ VaultClawback::assetsToClawback( << ", assetsTotal=" << vault->at(sfAssetsTotal).value() << ", sharesTotal=" << sleShareIssuance->at(sfOutstandingAmount) << ", amount=" << clawbackAmount.value(); - return Unexpected(tecPATH_DRY); + return std::unexpected(tecPATH_DRY); } return std::make_pair(assetsRecovered, sharesDestroyed); diff --git a/src/test/app/Delegate_test.cpp b/src/test/app/Delegate_test.cpp index 588aeee634..70b091290c 100644 --- a/src/test/app/Delegate_test.cpp +++ b/src/test/app/Delegate_test.cpp @@ -2018,8 +2018,8 @@ class Delegate_test : public beast::unit_test::Suite auto jrr = env.rpc("json", "sign_for", to_string(jv))[jss::result]; BEAST_EXPECT(jrr[jss::status] == "error"); BEAST_EXPECT( - jrr[jss::error_message].asString().find( - "A Signer may not be the transaction's Account") != std::string::npos); + jrr[jss::error_message].asString().contains( + "A Signer may not be the transaction's Account")); } } diff --git a/src/test/app/GRPCServerTLS_test.cpp b/src/test/app/GRPCServerTLS_test.cpp index ae0d839a6e..a48986d004 100644 --- a/src/test/app/GRPCServerTLS_test.cpp +++ b/src/test/app/GRPCServerTLS_test.cpp @@ -479,8 +479,7 @@ public: } catch (std::runtime_error const& e) { - BEAST_EXPECT( - std::string(e.what()).find("Incomplete TLS configuration") != std::string::npos); + BEAST_EXPECT(std::string(e.what()).contains("Incomplete TLS configuration")); } } @@ -505,8 +504,7 @@ public: } catch (std::runtime_error const& e) { - BEAST_EXPECT( - std::string(e.what()).find("Incomplete TLS configuration") != std::string::npos); + BEAST_EXPECT(std::string(e.what()).contains("Incomplete TLS configuration")); } } @@ -533,8 +531,8 @@ public: catch (std::runtime_error const& e) { BEAST_EXPECT( - std::string(e.what()).find( - "ssl_client_ca requires both ssl_cert and ssl_key") != std::string::npos); + std::string(e.what()).contains( + "ssl_client_ca requires both ssl_cert and ssl_key")); } } @@ -556,9 +554,7 @@ public: { // This should fail with "Incomplete TLS configuration" first // because ssl_cert is specified without ssl_key - BEAST_EXPECT( - std::string(e.what()).find("Incomplete TLS configuration") != - std::string::npos); + BEAST_EXPECT(std::string(e.what()).contains("Incomplete TLS configuration")); } } @@ -580,9 +576,7 @@ public: { // This should fail with "Incomplete TLS configuration" first // because ssl_key is specified without ssl_cert - BEAST_EXPECT( - std::string(e.what()).find("Incomplete TLS configuration") != - std::string::npos); + BEAST_EXPECT(std::string(e.what()).contains("Incomplete TLS configuration")); } } } @@ -610,8 +604,8 @@ public: catch (std::runtime_error const& e) { BEAST_EXPECT( - std::string(e.what()).find( - "ssl_cert_chain requires both ssl_cert and ssl_key") != std::string::npos); + std::string(e.what()).contains( + "ssl_cert_chain requires both ssl_cert and ssl_key")); } } @@ -633,9 +627,7 @@ public: { // This should fail with "Incomplete TLS configuration" first // because ssl_cert is specified without ssl_key - BEAST_EXPECT( - std::string(e.what()).find("Incomplete TLS configuration") != - std::string::npos); + BEAST_EXPECT(std::string(e.what()).contains("Incomplete TLS configuration")); } } } diff --git a/src/test/app/Invariants_test.cpp b/src/test/app/Invariants_test.cpp index 3654036869..6d53d25661 100644 --- a/src/test/app/Invariants_test.cpp +++ b/src/test/app/Invariants_test.cpp @@ -216,7 +216,7 @@ class Invariants_test : public beast::unit_test::Suite // std::cerr << messages << '\n'; for (auto const& m : expectLogs) { - BEAST_EXPECTS(messages.find(m) != std::string::npos, m); + BEAST_EXPECTS(messages.contains(m), m); } } } @@ -2187,8 +2187,7 @@ class Invariants_test : public beast::unit_test::Suite BEAST_EXPECT(!invariant.finalize( makeOfferCreateTx(), tesSUCCESS, XRPAmount{}, view, missingRootJlog)); BEAST_EXPECT( - missingRootSink.messages().str().find("book directory root missing") != - std::string::npos); + missingRootSink.messages().str().contains("book directory root missing")); } { // delete diff --git a/src/test/app/MultiSign_test.cpp b/src/test/app/MultiSign_test.cpp index 5092cafef9..f161226210 100644 --- a/src/test/app/MultiSign_test.cpp +++ b/src/test/app/MultiSign_test.cpp @@ -1121,8 +1121,8 @@ public: // Signature should fail. auto const info = submitSTTx(local); BEAST_EXPECT( - info[jss::result][jss::error_exception].asString().find( - "Invalid signature on account r") != std::string::npos); + info[jss::result][jss::error_exception].asString().contains( + "Invalid signature on account r")); } { // Multisign with an empty signers array should fail. diff --git a/src/test/app/NFTokenBurn_test.cpp b/src/test/app/NFTokenBurn_test.cpp index 482d275d51..46b02d03cf 100644 --- a/src/test/app/NFTokenBurn_test.cpp +++ b/src/test/app/NFTokenBurn_test.cpp @@ -794,9 +794,8 @@ class NFTokenBurn_test : public beast::unit_test::Suite BEAST_EXPECT(sink.messages().str().starts_with("Invariant failed:")); // uncomment to log the invariant failure message // log << " --> " << sink.messages().str() << std::endl; - BEAST_EXPECT( - sink.messages().str().find( - "Last NFT page deleted with non-empty directory") != std::string::npos); + BEAST_EXPECT(sink.messages().str().contains( + "Last NFT page deleted with non-empty directory")); } } { @@ -831,8 +830,7 @@ class NFTokenBurn_test : public beast::unit_test::Suite BEAST_EXPECT(sink.messages().str().starts_with("Invariant failed:")); // uncomment to log the invariant failure message // log << " --> " << sink.messages().str() << std::endl; - BEAST_EXPECT( - sink.messages().str().find("Lost NextMinPage link") != std::string::npos); + BEAST_EXPECT(sink.messages().str().contains("Lost NextMinPage link")); } } } diff --git a/src/test/app/NetworkOPs_test.cpp b/src/test/app/NetworkOPs_test.cpp index d0a692b894..c5c8d33706 100644 --- a/src/test/app/NetworkOPs_test.cpp +++ b/src/test/app/NetworkOPs_test.cpp @@ -54,7 +54,7 @@ public: env.close(); } - BEAST_EXPECT(logs.find("No transaction to process!") != std::string::npos); + BEAST_EXPECT(logs.contains("No transaction to process!")); } }; diff --git a/src/test/app/ValidatorSite_test.cpp b/src/test/app/ValidatorSite_test.cpp index e3e3ec27df..8400f2d794 100644 --- a/src/test/app/ValidatorSite_test.cpp +++ b/src/test/app/ValidatorSite_test.cpp @@ -239,7 +239,7 @@ private: json::Value myStatus; for (auto const& vs : jv[jss::validator_sites]) { - if (vs[jss::uri].asString().find(u.uri) != std::string::npos) + if (vs[jss::uri].asString().contains(u.uri)) myStatus = vs; } BEAST_EXPECTS( @@ -248,9 +248,7 @@ private: if (!u.cfg.msg.empty()) { - BEAST_EXPECTS( - sink.messages().str().find(u.cfg.msg) != std::string::npos, - sink.messages().str()); + BEAST_EXPECTS(sink.messages().str().contains(u.cfg.msg), sink.messages().str()); } if (u.cfg.expectedRefreshMin != 0) @@ -324,7 +322,7 @@ private: json::Value myStatus; for (auto const& vs : jv[jss::validator_sites]) { - if (vs[jss::uri].asString().find(u.uri) != std::string::npos) + if (vs[jss::uri].asString().contains(u.uri)) myStatus = vs; } BEAST_EXPECTS( @@ -332,9 +330,7 @@ private: to_string(myStatus)); if (u.shouldFail) { - BEAST_EXPECTS( - sink.messages().str().find(u.expectMsg) != std::string::npos, - sink.messages().str()); + BEAST_EXPECTS(sink.messages().str().contains(u.expectMsg), sink.messages().str()); } } } diff --git a/src/test/basics/Expected_test.cpp b/src/test/basics/Expected_test.cpp deleted file mode 100644 index c8e570835b..0000000000 --- a/src/test/basics/Expected_test.cpp +++ /dev/null @@ -1,221 +0,0 @@ -#include -#include -#include - -#include -#include - -#include -#include -#include -#include - -#if BOOST_VERSION >= 107500 -#endif // BOOST_VERSION -#include - -namespace xrpl::test { - -struct Expected_test : beast::unit_test::Suite -{ - void - run() override - { - // Test non-error const construction. - { - auto const expected = []() -> Expected { return "Valid value"; }(); - BEAST_EXPECT(expected); - BEAST_EXPECT(expected.has_value()); - BEAST_EXPECT(expected.value() == "Valid value"); - BEAST_EXPECT(*expected == "Valid value"); - BEAST_EXPECT(expected->at(0) == 'V'); - - bool throwOccurred = false; - try - { - // There's no error, so should throw. - [[maybe_unused]] TER const t = expected.error(); - } - catch (std::runtime_error const& e) - { - BEAST_EXPECT(e.what() == std::string("bad expected access")); - throwOccurred = true; - } - BEAST_EXPECT(throwOccurred); - } - // Test non-error non-const construction. - { - auto expected = []() -> Expected { return "Valid value"; }(); - BEAST_EXPECT(expected); - BEAST_EXPECT(expected.has_value()); - BEAST_EXPECT(expected.value() == "Valid value"); - BEAST_EXPECT(*expected == "Valid value"); - BEAST_EXPECT(expected->at(0) == 'V'); - std::string const mv = std::move(*expected); - BEAST_EXPECT(mv == "Valid value"); - - bool throwOccurred = false; - try - { - // There's no error, so should throw. - [[maybe_unused]] TER const t = expected.error(); - } - catch (std::runtime_error const& e) - { - BEAST_EXPECT(e.what() == std::string("bad expected access")); - throwOccurred = true; - } - BEAST_EXPECT(throwOccurred); - } - // Test non-error overlapping type construction. - { - auto expected = []() -> Expected { return 1; }(); - BEAST_EXPECT(expected); - BEAST_EXPECT(expected.has_value()); - BEAST_EXPECT(expected.value() == 1); - BEAST_EXPECT(*expected == 1); - - bool throwOccurred = false; - try - { - // There's no error, so should throw. - [[maybe_unused]] std::uint16_t const t = expected.error(); - } - catch (std::runtime_error const& e) - { - BEAST_EXPECT(e.what() == std::string("bad expected access")); - throwOccurred = true; - } - BEAST_EXPECT(throwOccurred); - } - // Test error construction from rvalue. - { - auto const expected = []() -> Expected { - return Unexpected(telLOCAL_ERROR); - }(); - BEAST_EXPECT(!expected); - BEAST_EXPECT(!expected.has_value()); - BEAST_EXPECT(expected.error() == telLOCAL_ERROR); - - bool throwOccurred = false; - try - { - // There's no result, so should throw. - [[maybe_unused]] std::string const s = *expected; - } - catch (std::runtime_error const& e) - { - BEAST_EXPECT(e.what() == std::string("bad expected access")); - throwOccurred = true; - } - BEAST_EXPECT(throwOccurred); - } - // Test error construction from lvalue. - { - auto const err(telLOCAL_ERROR); - auto expected = [&err]() -> Expected { return Unexpected(err); }(); - BEAST_EXPECT(!expected); - BEAST_EXPECT(!expected.has_value()); - BEAST_EXPECT(expected.error() == telLOCAL_ERROR); - - bool throwOccurred = false; - try - { - // There's no result, so should throw. - [[maybe_unused]] std::size_t const s = expected->size(); - } - catch (std::runtime_error const& e) - { - BEAST_EXPECT(e.what() == std::string("bad expected access")); - throwOccurred = true; - } - BEAST_EXPECT(throwOccurred); - } - // Test error construction from const char*. - { - auto const expected = []() -> Expected { - return Unexpected("Not what is expected!"); - }(); - BEAST_EXPECT(!expected); - BEAST_EXPECT(!expected.has_value()); - BEAST_EXPECT(expected.error() == std::string("Not what is expected!")); - } - // Test error construction of string from const char*. - { - auto expected = []() -> Expected { - return Unexpected("Not what is expected!"); - }(); - BEAST_EXPECT(!expected); - BEAST_EXPECT(!expected.has_value()); - BEAST_EXPECT(expected.error() == "Not what is expected!"); - std::string const s(std::move(expected.error())); - BEAST_EXPECT(s == "Not what is expected!"); - } - // Test non-error const construction of Expected. - { - auto const expected = []() -> Expected { return {}; }(); - BEAST_EXPECT(expected); - bool throwOccurred = false; - try - { - // There's no error, so should throw. - [[maybe_unused]] std::size_t const s = expected.error().size(); - } - catch (std::runtime_error const& e) - { - BEAST_EXPECT(e.what() == std::string("bad expected access")); - throwOccurred = true; - } - BEAST_EXPECT(throwOccurred); - } - // Test non-error non-const construction of Expected. - { - auto expected = []() -> Expected { return {}; }(); - BEAST_EXPECT(expected); - bool throwOccurred = false; - try - { - // There's no error, so should throw. - [[maybe_unused]] std::size_t const s = expected.error().size(); - } - catch (std::runtime_error const& e) - { - BEAST_EXPECT(e.what() == std::string("bad expected access")); - throwOccurred = true; - } - BEAST_EXPECT(throwOccurred); - } - // Test error const construction of Expected. - { - auto const expected = []() -> Expected { - return Unexpected("Not what is expected!"); - }(); - BEAST_EXPECT(!expected); - BEAST_EXPECT(expected.error() == "Not what is expected!"); - } - // Test error non-const construction of Expected. - { - auto expected = []() -> Expected { - return Unexpected("Not what is expected!"); - }(); - BEAST_EXPECT(!expected); - BEAST_EXPECT(expected.error() == "Not what is expected!"); - std::string const s(std::move(expected.error())); - BEAST_EXPECT(s == "Not what is expected!"); - } - // Test a case that previously unintentionally returned an array. -#if BOOST_VERSION >= 107500 - { - auto expected = []() -> Expected { - return boost::json::object{{"oops", "me array now"}}; - }(); - BEAST_EXPECT(expected); - BEAST_EXPECT(!expected.value().is_array()); - } -#endif // BOOST_VERSION - } -}; - -BEAST_DEFINE_TESTSUITE(Expected, basics, xrpl); - -} // namespace xrpl::test diff --git a/src/test/consensus/Consensus_test.cpp b/src/test/consensus/Consensus_test.cpp index 6cc8d4fde1..629a97f0ea 100644 --- a/src/test/consensus/Consensus_test.cpp +++ b/src/test/consensus/Consensus_test.cpp @@ -1296,14 +1296,11 @@ public: auto const s = clog->str(); expect(s.find("stalled"), s, __FILE__, line); expect(s.starts_with("Transaction "s + std::to_string(txid)), s, __FILE__, line); - expect(s.find("voting "s + (ourVote ? "YES" : "NO")) != s.npos, s, __FILE__, line); + expect(s.contains("voting "s + (ourVote ? "YES" : "NO")), s, __FILE__, line); expect( - s.find("for "s + std::to_string(ourTime) + " rounds."s) != s.npos, - s, - __FILE__, - line); + s.contains("for "s + std::to_string(ourTime) + " rounds."s), s, __FILE__, line); expect( - s.find("votes in "s + std::to_string(peerTime) + " rounds.") != s.npos, + s.contains("votes in "s + std::to_string(peerTime) + " rounds."), s, __FILE__, line); diff --git a/src/test/jtx/CheckMessageLogs.h b/src/test/jtx/CheckMessageLogs.h index 2cc8c661eb..4bbdec6f06 100644 --- a/src/test/jtx/CheckMessageLogs.h +++ b/src/test/jtx/CheckMessageLogs.h @@ -24,7 +24,7 @@ class CheckMessageLogs : public Logs void write(beast::Severity level, std::string const& text) override { - if (text.find(owner_.msg_) != std::string::npos) + if (text.contains(owner_.msg_)) *owner_.pFound_ = true; } diff --git a/src/test/jtx/directory.h b/src/test/jtx/directory.h index 9a87266802..c63640ae1f 100644 --- a/src/test/jtx/directory.h +++ b/src/test/jtx/directory.h @@ -2,11 +2,11 @@ #include -#include #include #include #include +#include #include /** Directory operations. */ @@ -34,7 +34,7 @@ bumpLastPage( Env& env, std::uint64_t newLastPage, Keylet directory, - std::function adjust) -> Expected; + std::function adjust) -> std::expected; /// Implementation of adjust for the most common ledger entry, i.e. one where /// page index is stored in sfOwnerNode (and only there). Pass this function diff --git a/src/test/jtx/impl/directory.cpp b/src/test/jtx/impl/directory.cpp index 7a92c2bf25..9fb06e25df 100644 --- a/src/test/jtx/impl/directory.cpp +++ b/src/test/jtx/impl/directory.cpp @@ -2,7 +2,6 @@ #include -#include #include #include #include @@ -15,6 +14,7 @@ #include #include +#include #include #include @@ -26,9 +26,9 @@ bumpLastPage( Env& env, std::uint64_t newLastPage, Keylet directory, - std::function adjust) -> Expected + std::function adjust) -> std::expected { - Expected res{}; + std::expected res{}; env.app().getOpenLedger().modify([&](OpenView& view, beast::Journal j) -> bool { Sandbox sb(&view, TapNone); @@ -36,7 +36,7 @@ bumpLastPage( auto sleRoot = sb.peek(directory); if (!sleRoot) { - res = Unexpected(Error::DirectoryRootNotFound); + res = std::unexpected(Error::DirectoryRootNotFound); return false; } @@ -44,26 +44,26 @@ bumpLastPage( auto const lastIndex = sleRoot->getFieldU64(sfIndexPrevious); if (lastIndex == 0) { - res = Unexpected(Error::DirectoryTooSmall); + res = std::unexpected(Error::DirectoryTooSmall); return false; } if (sb.exists(keylet::page(directory, newLastPage))) { - res = Unexpected(Error::DirectoryPageDuplicate); + res = std::unexpected(Error::DirectoryPageDuplicate); return false; } if (lastIndex >= newLastPage) { - res = Unexpected(Error::InvalidLastPage); + res = std::unexpected(Error::InvalidLastPage); return false; } auto slePage = sb.peek(keylet::page(directory, lastIndex)); if (!slePage) { - res = Unexpected(Error::DirectoryPageNotFound); + res = std::unexpected(Error::DirectoryPageNotFound); return false; } @@ -94,7 +94,7 @@ bumpLastPage( auto slePrev = sb.peek(keylet::page(directory, *prevIndex)); if (!slePrev) { - res = Unexpected(Error::DirectoryPageNotFound); + res = std::unexpected(Error::DirectoryPageNotFound); return false; } slePrev->setFieldU64(sfIndexNext, newLastPage); @@ -109,7 +109,7 @@ bumpLastPage( { if (!adjust(sb, key, newLastPage)) { - res = Unexpected(Error::AdjustmentError); + res = std::unexpected(Error::AdjustmentError); return false; } } diff --git a/src/test/nodestore/NuDBFactory_test.cpp b/src/test/nodestore/NuDBFactory_test.cpp index 3ca3fa6838..d0675b3893 100644 --- a/src/test/nodestore/NuDBFactory_test.cpp +++ b/src/test/nodestore/NuDBFactory_test.cpp @@ -88,7 +88,7 @@ private: auto backend = Manager::instance().makeBackend(params, megabytes(4), scheduler, journal); std::string const logOutput = sink.messages().str(); - BEAST_EXPECT(logOutput.find(expectedMessage) != std::string::npos); + BEAST_EXPECT(logOutput.contains(expectedMessage)); } // Helper function to test power of two validation @@ -105,7 +105,7 @@ private: auto backend = Manager::instance().makeBackend(params, megabytes(4), scheduler, journal); std::string const logOutput = sink.messages().str(); - bool const hasWarning = logOutput.find("Invalid nudb_block_size") != std::string::npos; + bool const hasWarning = logOutput.contains("Invalid nudb_block_size"); BEAST_EXPECT(hasWarning == !shouldWork); } @@ -221,10 +221,8 @@ public: catch (std::exception const& e) { std::string const logOutput{e.what()}; - BEAST_EXPECT(logOutput.find("Invalid nudb_block_size: 5000") != std::string::npos); - BEAST_EXPECT( - logOutput.find("Must be power of 2 between 4096 and 32768") != - std::string::npos); + BEAST_EXPECT(logOutput.contains("Invalid nudb_block_size: 5000")); + BEAST_EXPECT(logOutput.contains("Must be power of 2 between 4096 and 32768")); } } @@ -247,8 +245,7 @@ public: catch (std::exception const& e) { std::string const logOutput{e.what()}; - BEAST_EXPECT( - logOutput.find("Invalid nudb_block_size value: invalid") != std::string::npos); + BEAST_EXPECT(logOutput.contains("Invalid nudb_block_size value: invalid")); } } } @@ -291,7 +288,7 @@ public: catch (std::exception const& e) { std::string const logOutput{e.what()}; - BEAST_EXPECT(logOutput.find("Invalid nudb_block_size") != std::string::npos); + BEAST_EXPECT(logOutput.contains("Invalid nudb_block_size")); } } } @@ -355,8 +352,7 @@ public: // Should log success message for valid values std::string const logOutput = sink.messages().str(); - bool const hasSuccessMessage = - logOutput.find("Using custom NuDB block size") != std::string::npos; + bool const hasSuccessMessage = logOutput.contains("Using custom NuDB block size"); BEAST_EXPECT(hasSuccessMessage); } diff --git a/src/test/overlay/reduce_relay_test.cpp b/src/test/overlay/reduce_relay_test.cpp index 54d8f555a2..1c9bf1f9c1 100644 --- a/src/test/overlay/reduce_relay_test.cpp +++ b/src/test/overlay/reduce_relay_test.cpp @@ -806,7 +806,7 @@ public: { auto size = max - min; std::vector s(size); - std::iota(s.begin(), s.end(), min); + std::iota(s.begin(), s.end(), min); // NOLINT(modernize-use-ranges) std::random_device d; std::mt19937 g(d()); std::shuffle(s.begin(), s.end(), g); diff --git a/src/test/server/ServerStatus_test.cpp b/src/test/server/ServerStatus_test.cpp index 5ba71962b3..4a9c12c96b 100644 --- a/src/test/server/ServerStatus_test.cpp +++ b/src/test/server/ServerStatus_test.cpp @@ -801,7 +801,7 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En if (!BEAST_EXPECTS(!ec, ec.message())) return; BEAST_EXPECT(resp.result() == boost::beast::http::status::ok); - BEAST_EXPECT(resp.body().find("connectivity is working.") != std::string::npos); + BEAST_EXPECT(resp.body().contains("connectivity is working.")); // mark the Network as having an Amendment Warning, but won't fail env.app().getOPs().setAmendmentWarned(); @@ -846,7 +846,7 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En if (!BEAST_EXPECTS(!ec, ec.message())) return; BEAST_EXPECT(resp.result() == boost::beast::http::status::ok); - BEAST_EXPECT(resp.body().find("connectivity is working.") != std::string::npos); + BEAST_EXPECT(resp.body().contains("connectivity is working.")); // with ELB_SUPPORT, status still does not indicate a problem env.app().config().elbSupport = true; @@ -866,7 +866,7 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En if (!BEAST_EXPECTS(!ec, ec.message())) return; BEAST_EXPECT(resp.result() == boost::beast::http::status::ok); - BEAST_EXPECT(resp.body().find("connectivity is working.") != std::string::npos); + BEAST_EXPECT(resp.body().contains("connectivity is working.")); } void @@ -929,7 +929,7 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En if (!BEAST_EXPECTS(!ec, ec.message())) return; BEAST_EXPECT(resp.result() == boost::beast::http::status::ok); - BEAST_EXPECT(resp.body().find("connectivity is working.") != std::string::npos); + BEAST_EXPECT(resp.body().contains("connectivity is working.")); // mark the Network as Amendment Blocked, but still won't fail until // ELB is enabled (next step) @@ -977,7 +977,7 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En if (!BEAST_EXPECTS(!ec, ec.message())) return; BEAST_EXPECT(resp.result() == boost::beast::http::status::ok); - BEAST_EXPECT(resp.body().find("connectivity is working.") != std::string::npos); + BEAST_EXPECT(resp.body().contains("connectivity is working.")); env.app().config().elbSupport = true; @@ -996,8 +996,8 @@ class ServerStatus_test : public beast::unit_test::Suite, public beast::test::En if (!BEAST_EXPECTS(!ec, ec.message())) return; BEAST_EXPECT(resp.result() == boost::beast::http::status::internal_server_error); - BEAST_EXPECT(resp.body().find("cannot accept clients:") != std::string::npos); - BEAST_EXPECT(resp.body().find("Server version too old") != std::string::npos); + BEAST_EXPECT(resp.body().contains("cannot accept clients:")); + BEAST_EXPECT(resp.body().contains("Server version too old")); } void diff --git a/src/test/server/Server_test.cpp b/src/test/server/Server_test.cpp index 455a365b7c..54091ef767 100644 --- a/src/test/server/Server_test.cpp +++ b/src/test/server/Server_test.cpp @@ -401,7 +401,7 @@ public: }), std::make_unique(&messages)}; }); - BEAST_EXPECT(messages.find("Missing 'ip' in [port_rpc]") != std::string::npos); + BEAST_EXPECT(messages.contains("Missing 'ip' in [port_rpc]")); except([&] { Env const env{ @@ -413,7 +413,7 @@ public: }), std::make_unique(&messages)}; }); - BEAST_EXPECT(messages.find("Missing 'port' in [port_rpc]") != std::string::npos); + BEAST_EXPECT(messages.contains("Missing 'port' in [port_rpc]")); except([&] { Env const env{ @@ -426,8 +426,7 @@ public: }), std::make_unique(&messages)}; }); - BEAST_EXPECT( - messages.find("Invalid value '0' for key 'port' in [port_rpc]") == std::string::npos); + BEAST_EXPECT(!messages.contains("Invalid value '0' for key 'port' in [port_rpc]")); except([&] { Env const env{ @@ -438,8 +437,7 @@ public: }), std::make_unique(&messages)}; }); - BEAST_EXPECT( - messages.find("Invalid value '0' for key 'port' in [server]") != std::string::npos); + BEAST_EXPECT(messages.contains("Invalid value '0' for key 'port' in [server]")); except([&] { Env const env{ @@ -453,7 +451,7 @@ public: }), std::make_unique(&messages)}; }); - BEAST_EXPECT(messages.find("Missing 'protocol' in [port_rpc]") != std::string::npos); + BEAST_EXPECT(messages.contains("Missing 'protocol' in [port_rpc]")); except([&] // this creates a standard test config without the server // section @@ -482,7 +480,7 @@ public: }), std::make_unique(&messages)}; }); - BEAST_EXPECT(messages.find("Required section [server] is missing") != std::string::npos); + BEAST_EXPECT(messages.contains("Required section [server] is missing")); except([&] // this creates a standard test config without some of the // port sections @@ -503,7 +501,7 @@ public: }), std::make_unique(&messages)}; }); - BEAST_EXPECT(messages.find("Missing section: [port_peer]") != std::string::npos); + BEAST_EXPECT(messages.contains("Missing section: [port_peer]")); } void diff --git a/src/xrpld/overlay/detail/PeerImp.cpp b/src/xrpld/overlay/detail/PeerImp.cpp index 325f8ba038..323dc14673 100644 --- a/src/xrpld/overlay/detail/PeerImp.cpp +++ b/src/xrpld/overlay/detail/PeerImp.cpp @@ -783,7 +783,7 @@ PeerImp::onShutdown(error_code ec) // - broken_pipe: the peer is gone bool const shouldLog = (ec != boost::asio::error::eof && ec != boost::asio::error::operation_aborted && - ec.message().find("application data after close notify") == std::string::npos); + !ec.message().contains("application data after close notify")); if (shouldLog) { diff --git a/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp b/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp index 4d0d10a66b..38827dc93c 100644 --- a/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp +++ b/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp @@ -8,7 +8,6 @@ #include #include -#include #include #include #include @@ -24,6 +23,7 @@ #include #include +#include #include namespace xrpl::RPC { @@ -381,7 +381,7 @@ lookupLedger(std::shared_ptr& ledger, JsonContext const& context return result; } -Expected, json::Value> +std::expected, json::Value> getOrAcquireLedger(RPC::JsonContext const& context) { auto const hasHash = context.params.isMember(jss::ledger_hash); @@ -393,7 +393,7 @@ getOrAcquireLedger(RPC::JsonContext const& context) if ((static_cast(hasHash) + static_cast(hasIndex)) != 1) { - return Unexpected( + return std::unexpected( RPC::makeParamError( "Exactly one of 'ledger_hash' or " "'ledger_index' can be specified.")); @@ -403,29 +403,29 @@ getOrAcquireLedger(RPC::JsonContext const& context) { auto const& jsonHash = context.params.get(jss::ledger_hash, json::ValueType::Null); if (!jsonHash.isString() || !ledgerHash.parseHex(jsonHash.asString())) - return Unexpected(RPC::expectedFieldError(jss::ledger_hash, "hex string")); + return std::unexpected(RPC::expectedFieldError(jss::ledger_hash, "hex string")); } else { auto const& jsonIndex = context.params.get(jss::ledger_index, json::ValueType::Null); if (!jsonIndex.isInt() && !jsonIndex.isUInt()) - return Unexpected(RPC::expectedFieldError(jss::ledger_index, "number")); + return std::unexpected(RPC::expectedFieldError(jss::ledger_index, "number")); // We need a validated ledger to get the hash from the sequence if (ledgerMaster.getValidatedLedgerAge() > RPC::Tuning::kMaxValidatedLedgerAge) { if (context.apiVersion == 1) - return Unexpected(rpcError(RpcNoCurrent)); - return Unexpected(rpcError(RpcNotSynced)); + return std::unexpected(rpcError(RpcNoCurrent)); + return std::unexpected(rpcError(RpcNotSynced)); } ledgerIndex = jsonIndex.asInt(); auto ledger = ledgerMaster.getValidatedLedger(); if (ledgerIndex >= ledger->header().seq) - return Unexpected(RPC::makeParamError("Ledger index too large")); + return std::unexpected(RPC::makeParamError("Ledger index too large")); if (ledgerIndex <= 0) - return Unexpected(RPC::makeParamError("Ledger index too small")); + return std::unexpected(RPC::makeParamError("Ledger index too small")); auto const j = context.app.getJournal("RPCHandler"); // Try to get the hash of the desired ledger from the validated @@ -452,7 +452,7 @@ getOrAcquireLedger(RPC::JsonContext const& context) json::Value jvResult = RPC::makeError( RpcLgrNotFound, "acquiring ledger containing requested index"); jvResult[jss::acquiring] = getJson(LedgerFill(*il, &context)); - return Unexpected(jvResult); + return std::unexpected(jvResult); } if (auto il = context.app.getInboundLedgers().find(*refHash)) @@ -461,11 +461,11 @@ getOrAcquireLedger(RPC::JsonContext const& context) json::Value jvResult = RPC::makeError( RpcLgrNotFound, "acquiring ledger containing requested index"); jvResult[jss::acquiring] = il->getJson(0); - return Unexpected(jvResult); + return std::unexpected(jvResult); } // Likely the app is shutting down - return Unexpected(json::Value()); + return std::unexpected(json::Value()); } neededHash = hashOfSeq(*ledger, ledgerIndex, j); @@ -487,9 +487,10 @@ getOrAcquireLedger(RPC::JsonContext const& context) return ledger; if (auto il = context.app.getInboundLedgers().find(ledgerHash)) - return Unexpected(il->getJson(0)); + return std::unexpected(il->getJson(0)); - return Unexpected(RPC::makeError(RpcNotReady, "findCreate failed to return an inbound ledger")); + return std::unexpected( + RPC::makeError(RpcNotReady, "findCreate failed to return an inbound ledger")); } } // namespace xrpl::RPC diff --git a/src/xrpld/rpc/detail/RPCLedgerHelpers.h b/src/xrpld/rpc/detail/RPCLedgerHelpers.h index faec4ae069..9ec2a6673c 100644 --- a/src/xrpld/rpc/detail/RPCLedgerHelpers.h +++ b/src/xrpld/rpc/detail/RPCLedgerHelpers.h @@ -10,6 +10,7 @@ #include #include +#include #include namespace xrpl { @@ -163,11 +164,11 @@ ledgerFromSpecifier( * * @param context The RPC JsonContext containing request parameters and * environment. - * @return Expected, json::Value> + * @return std::expected, json::Value> * On success, contains a shared pointer to the requested Ledger. * On failure, contains a json::Value describing the error. */ -Expected, json::Value> +std::expected, json::Value> getOrAcquireLedger(RPC::JsonContext const& context); } // namespace RPC diff --git a/src/xrpld/rpc/detail/TransactionSign.cpp b/src/xrpld/rpc/detail/TransactionSign.cpp index 86d895fa1b..8c3a5ea245 100644 --- a/src/xrpld/rpc/detail/TransactionSign.cpp +++ b/src/xrpld/rpc/detail/TransactionSign.cpp @@ -14,7 +14,6 @@ #include #include -#include #include #include #include @@ -57,6 +56,7 @@ #include #include #include +#include #include #include #include @@ -407,23 +407,23 @@ checkTxJsonFields( return ret; } -static Expected +static std::expected checkNetworkID(json::Value const& txJson, uint32_t appNetworkId) { if (appNetworkId > 1024) { if (!txJson.isMember(jss::NetworkID)) { - return Unexpected( + return std::unexpected( RPC::makeError(RpcInvalidParams, RPC::missingFieldMessage("tx_json.NetworkID"))); } if (!txJson[jss::NetworkID].isIntegral() || txJson[jss::NetworkID].asUInt() != appNetworkId) { - return Unexpected( + return std::unexpected( RPC::makeError(RpcInvalidParams, RPC::invalidFieldMessage("tx_json.NetworkID"))); } } - return Expected(); + return std::expected(); } //------------------------------------------------------------------------------ diff --git a/src/xrpld/rpc/handlers/ledger/Ledger.cpp b/src/xrpld/rpc/handlers/ledger/Ledger.cpp index 1b096002bd..5938c8c9c5 100644 --- a/src/xrpld/rpc/handlers/ledger/Ledger.cpp +++ b/src/xrpld/rpc/handlers/ledger/Ledger.cpp @@ -8,7 +8,6 @@ #include #include -#include #include #include #include @@ -28,6 +27,7 @@ #include #include +#include #include #include #include @@ -44,14 +44,14 @@ LedgerHandler::check() { auto const& params = context_.params; - auto getBool = [&](json::StaticString const& field) -> Expected { + auto getBool = [&](json::StaticString const& field) -> std::expected { if (!params.isMember(field)) { return false; } if (!params[field].isBool()) { - return Unexpected(RpcInvalidParams); + return std::unexpected(RpcInvalidParams); } return params[field].asBool(); diff --git a/src/xrpld/rpc/handlers/ledger/LedgerEntry.cpp b/src/xrpld/rpc/handlers/ledger/LedgerEntry.cpp index 9a9119d2ba..236712f0c2 100644 --- a/src/xrpld/rpc/handlers/ledger/LedgerEntry.cpp +++ b/src/xrpld/rpc/handlers/ledger/LedgerEntry.cpp @@ -3,7 +3,6 @@ #include #include -#include #include #include #include @@ -27,6 +26,7 @@ #include #include +#include #include #include #include @@ -34,12 +34,12 @@ namespace xrpl { -using FunctionType = std::function( +using FunctionType = std::function( json::Value const&, json::StaticString const, unsigned const apiVersion)>; -static Expected +static std::expected parseFixed( Keylet const& keylet, json::Value const& params, @@ -55,12 +55,12 @@ fixed(Keylet const& keylet) return [keylet]( json::Value const& params, json::StaticString const fieldName, - unsigned const apiVersion) -> Expected { + unsigned const apiVersion) -> std::expected { return parseFixed(keylet, params, fieldName, apiVersion); }; } -static Expected +static std::expected parseObjectID( json::Value const& params, json::StaticString const fieldName, @@ -73,7 +73,7 @@ parseObjectID( return LedgerEntryHelpers::invalidFieldError("malformedRequest", fieldName, expectedType); } -static Expected +static std::expected parseIndex(json::Value const& params, json::StaticString const fieldName, unsigned const apiVersion) { if (apiVersion > 2u && params.isString()) @@ -95,7 +95,7 @@ parseIndex(json::Value const& params, json::StaticString const fieldName, unsign return parseObjectID(params, fieldName, "hex string"); } -static Expected +static std::expected parseAccountRoot( json::Value const& params, json::StaticString const fieldName, @@ -111,7 +111,7 @@ parseAccountRoot( auto const parseAmendments = fixed(keylet::amendments()); -static Expected +static std::expected parseAMM( json::Value const& params, json::StaticString const fieldName, @@ -125,21 +125,21 @@ parseAMM( if (auto const value = LedgerEntryHelpers::hasRequired(params, {jss::asset, jss::asset2}); !value) { - return Unexpected(value.error()); + return std::unexpected(value.error()); } auto const asset = LedgerEntryHelpers::requiredAsset(params, jss::asset, "malformedRequest"); if (!asset) - return Unexpected(asset.error()); + return std::unexpected(asset.error()); auto const asset2 = LedgerEntryHelpers::requiredAsset(params, jss::asset2, "malformedRequest"); if (!asset2) - return Unexpected(asset2.error()); + return std::unexpected(asset2.error()); return keylet::amm(*asset, *asset2).key; } -static Expected +static std::expected parseBridge( json::Value const& params, json::StaticString const fieldName, @@ -147,7 +147,7 @@ parseBridge( { if (!params.isMember(jss::bridge)) { - return Unexpected(LedgerEntryHelpers::missingFieldError(jss::bridge)); + return std::unexpected(LedgerEntryHelpers::missingFieldError(jss::bridge)); } if (params[jss::bridge].isString()) @@ -157,12 +157,12 @@ parseBridge( auto const bridge = LedgerEntryHelpers::parseBridgeFields(params[jss::bridge]); if (!bridge) - return Unexpected(bridge.error()); + return std::unexpected(bridge.error()); auto const account = LedgerEntryHelpers::requiredAccountID( params, jss::bridge_account, "malformedBridgeAccount"); if (!account) - return Unexpected(account.error()); + return std::unexpected(account.error()); STXChainBridge::ChainType const chainType = STXChainBridge::srcChain(account.value() == bridge->lockingChainDoor()); @@ -172,7 +172,7 @@ parseBridge( return keylet::bridge(*bridge, chainType).key; } -static Expected +static std::expected parseCheck( json::Value const& params, json::StaticString const fieldName, @@ -181,7 +181,7 @@ parseCheck( return parseObjectID(params, fieldName, "hex string"); } -static Expected +static std::expected parseCredential( json::Value const& cred, json::StaticString const fieldName, @@ -195,22 +195,22 @@ parseCredential( auto const subject = LedgerEntryHelpers::requiredAccountID(cred, jss::subject, "malformedRequest"); if (!subject) - return Unexpected(subject.error()); + return std::unexpected(subject.error()); auto const issuer = LedgerEntryHelpers::requiredAccountID(cred, jss::issuer, "malformedRequest"); if (!issuer) - return Unexpected(issuer.error()); + return std::unexpected(issuer.error()); auto const credType = LedgerEntryHelpers::requiredHexBlob( cred, jss::credential_type, kMaxCredentialTypeLength, "malformedRequest"); if (!credType) - return Unexpected(credType.error()); + return std::unexpected(credType.error()); return keylet::credential(*subject, *issuer, Slice(credType->data(), credType->size())).key; } -static Expected +static std::expected parseDelegate( json::Value const& params, json::StaticString const fieldName, @@ -224,17 +224,17 @@ parseDelegate( auto const account = LedgerEntryHelpers::requiredAccountID(params, jss::account, "malformedAddress"); if (!account) - return Unexpected(account.error()); + return std::unexpected(account.error()); auto const authorize = LedgerEntryHelpers::requiredAccountID(params, jss::authorize, "malformedAddress"); if (!authorize) - return Unexpected(authorize.error()); + return std::unexpected(authorize.error()); return keylet::delegate(*account, *authorize).key; } -static Expected +static std::expected parseAuthorizeCredentials(json::Value const& jv) { if (!jv.isArray()) @@ -246,7 +246,7 @@ parseAuthorizeCredentials(json::Value const& jv) std::uint32_t const n = jv.size(); if (n > kMaxCredentialsArraySize) { - return Unexpected( + return std::unexpected( LedgerEntryHelpers::malformedError( "malformedAuthorizedCredentials", "Invalid field '" + std::string(jss::authorized_credentials) + @@ -255,7 +255,7 @@ parseAuthorizeCredentials(json::Value const& jv) if (n == 0) { - return Unexpected( + return std::unexpected( LedgerEntryHelpers::malformedError( "malformedAuthorizedCredentials", "Invalid field '" + std::string(jss::authorized_credentials) + "', array empty.")); @@ -274,18 +274,18 @@ parseAuthorizeCredentials(json::Value const& jv) jo, {jss::issuer, jss::credential_type}, "malformedAuthorizedCredentials"); !value) { - return Unexpected(value.error()); + return std::unexpected(value.error()); } auto const issuer = LedgerEntryHelpers::requiredAccountID( jo, jss::issuer, "malformedAuthorizedCredentials"); if (!issuer) - return Unexpected(issuer.error()); + return std::unexpected(issuer.error()); auto const credentialType = LedgerEntryHelpers::requiredHexBlob( jo, jss::credential_type, kMaxCredentialTypeLength, "malformedAuthorizedCredentials"); if (!credentialType) - return Unexpected(credentialType.error()); + return std::unexpected(credentialType.error()); auto credential = STObject::makeInnerObject(sfCredential); credential.setAccountID(sfIssuer, *issuer); @@ -296,7 +296,7 @@ parseAuthorizeCredentials(json::Value const& jv) return arr; } -static Expected +static std::expected parseDepositPreauth( json::Value const& dp, json::StaticString const fieldName, @@ -318,7 +318,7 @@ parseDepositPreauth( auto const owner = LedgerEntryHelpers::requiredAccountID(dp, jss::owner, "malformedOwner"); if (!owner) { - return Unexpected(owner.error()); + return std::unexpected(owner.error()); } if (dp.isMember(jss::authorized)) @@ -334,7 +334,7 @@ parseDepositPreauth( auto const& ac(dp[jss::authorized_credentials]); auto const arr = parseAuthorizeCredentials(ac); if (!arr.has_value()) - return Unexpected(arr.error()); + return std::unexpected(arr.error()); auto const& sorted = credentials::makeSorted(arr.value()); if (sorted.empty()) @@ -347,7 +347,7 @@ parseDepositPreauth( return keylet::depositPreauth(*owner, sorted).key; } -static Expected +static std::expected parseDID( json::Value const& params, json::StaticString const fieldName, @@ -362,7 +362,7 @@ parseDID( return keylet::did(*account).key; } -static Expected +static std::expected parseDirectoryNode( json::Value const& params, json::StaticString const fieldName, @@ -413,7 +413,7 @@ parseDirectoryNode( return LedgerEntryHelpers::malformedError("malformedRequest", ""); } -static Expected +static std::expected parseEscrow( json::Value const& params, json::StaticString const fieldName, @@ -426,17 +426,17 @@ parseEscrow( auto const id = LedgerEntryHelpers::requiredAccountID(params, jss::owner, "malformedOwner"); if (!id) - return Unexpected(id.error()); + return std::unexpected(id.error()); auto const seq = LedgerEntryHelpers::requiredUInt32(params, jss::seq, "malformedSeq"); if (!seq) - return Unexpected(seq.error()); + return std::unexpected(seq.error()); return keylet::escrow(*id, *seq).key; } auto const parseFeeSettings = fixed(keylet::fees()); -static Expected +static std::expected parseFixed( Keylet const& keylet, json::Value const& params, @@ -455,7 +455,7 @@ parseFixed( return keylet.key; } -static Expected +static std::expected parseLedgerHashes( json::Value const& params, json::StaticString const fieldName, @@ -475,7 +475,7 @@ parseLedgerHashes( return parseFixed(keylet::skip(), params, fieldName, apiVersion); } -static Expected +static std::expected parseLoanBroker( json::Value const& params, json::StaticString const fieldName, @@ -488,15 +488,15 @@ parseLoanBroker( auto const id = LedgerEntryHelpers::requiredAccountID(params, jss::owner, "malformedOwner"); if (!id) - return Unexpected(id.error()); + return std::unexpected(id.error()); auto const seq = LedgerEntryHelpers::requiredUInt32(params, jss::seq, "malformedSeq"); if (!seq) - return Unexpected(seq.error()); + return std::unexpected(seq.error()); return keylet::loanbroker(*id, *seq).key; } -static Expected +static std::expected parseLoan( json::Value const& params, json::StaticString const fieldName, @@ -510,15 +510,15 @@ parseLoan( auto const id = LedgerEntryHelpers::requiredUInt256(params, jss::loan_broker_id, "malformedBroker"); if (!id) - return Unexpected(id.error()); + return std::unexpected(id.error()); auto const seq = LedgerEntryHelpers::requiredUInt32(params, jss::loan_seq, "malformedSeq"); if (!seq) - return Unexpected(seq.error()); + return std::unexpected(seq.error()); return keylet::loan(*id, *seq).key; } -static Expected +static std::expected parseMPToken( json::Value const& params, json::StaticString const fieldName, @@ -532,17 +532,17 @@ parseMPToken( auto const mptIssuanceID = LedgerEntryHelpers::requiredUInt192(params, jss::mpt_issuance_id, "malformedMPTIssuanceID"); if (!mptIssuanceID) - return Unexpected(mptIssuanceID.error()); + return std::unexpected(mptIssuanceID.error()); auto const account = LedgerEntryHelpers::requiredAccountID(params, jss::account, "malformedAccount"); if (!account) - return Unexpected(account.error()); + return std::unexpected(account.error()); return keylet::mptoken(*mptIssuanceID, *account).key; } -static Expected +static std::expected parseMPTokenIssuance( json::Value const& params, json::StaticString const fieldName, @@ -558,7 +558,7 @@ parseMPTokenIssuance( return keylet::mptIssuance(*mptIssuanceID).key; } -static Expected +static std::expected parseNFTokenOffer( json::Value const& params, json::StaticString const fieldName, @@ -567,7 +567,7 @@ parseNFTokenOffer( return parseObjectID(params, fieldName, "hex string"); } -static Expected +static std::expected parseNFTokenPage( json::Value const& params, json::StaticString const fieldName, @@ -578,7 +578,7 @@ parseNFTokenPage( auto const parseNegativeUNL = fixed(keylet::negativeUNL()); -static Expected +static std::expected parseOffer( json::Value const& params, json::StaticString const fieldName, @@ -591,16 +591,16 @@ parseOffer( auto const id = LedgerEntryHelpers::requiredAccountID(params, jss::account, "malformedAddress"); if (!id) - return Unexpected(id.error()); + return std::unexpected(id.error()); auto const seq = LedgerEntryHelpers::requiredUInt32(params, jss::seq, "malformedRequest"); if (!seq) - return Unexpected(seq.error()); + return std::unexpected(seq.error()); return keylet::offer(*id, *seq).key; } -static Expected +static std::expected parseOracle( json::Value const& params, json::StaticString const fieldName, @@ -613,17 +613,17 @@ parseOracle( auto const id = LedgerEntryHelpers::requiredAccountID(params, jss::account, "malformedAccount"); if (!id) - return Unexpected(id.error()); + return std::unexpected(id.error()); auto const seq = LedgerEntryHelpers::requiredUInt32(params, jss::oracle_document_id, "malformedDocumentID"); if (!seq) - return Unexpected(seq.error()); + return std::unexpected(seq.error()); return keylet::oracle(*id, *seq).key; } -static Expected +static std::expected parsePayChannel( json::Value const& params, json::StaticString const fieldName, @@ -632,7 +632,7 @@ parsePayChannel( return parseObjectID(params, fieldName, "hex string"); } -static Expected +static std::expected parsePermissionedDomain( json::Value const& pd, json::StaticString const fieldName, @@ -652,16 +652,16 @@ parsePermissionedDomain( auto const account = LedgerEntryHelpers::requiredAccountID(pd, jss::account, "malformedAddress"); if (!account) - return Unexpected(account.error()); + return std::unexpected(account.error()); auto const seq = LedgerEntryHelpers::requiredUInt32(pd, jss::seq, "malformedRequest"); if (!seq) - return Unexpected(seq.error()); + return std::unexpected(seq.error()); return keylet::permissionedDomain(*account, pd[jss::seq].asUInt()).key; } -static Expected +static std::expected parseRippleState( json::Value const& jvRippleState, json::StaticString const fieldName, @@ -678,7 +678,7 @@ parseRippleState( LedgerEntryHelpers::hasRequired(jvRippleState, {jss::currency, jss::accounts}); !value) { - return Unexpected(value.error()); + return std::unexpected(value.error()); } if (!jvRippleState[jss::accounts].isArray() || jvRippleState[jss::accounts].size() != 2) @@ -710,7 +710,7 @@ parseRippleState( return keylet::line(*id1, *id2, uCurrency).key; } -static Expected +static std::expected parseSignerList( json::Value const& params, json::StaticString const fieldName, @@ -719,7 +719,7 @@ parseSignerList( return parseObjectID(params, fieldName, "hex string"); } -static Expected +static std::expected parseTicket( json::Value const& params, json::StaticString const fieldName, @@ -732,17 +732,17 @@ parseTicket( auto const id = LedgerEntryHelpers::requiredAccountID(params, jss::account, "malformedAddress"); if (!id) - return Unexpected(id.error()); + return std::unexpected(id.error()); auto const seq = LedgerEntryHelpers::requiredUInt32(params, jss::ticket_seq, "malformedRequest"); if (!seq) - return Unexpected(seq.error()); + return std::unexpected(seq.error()); return getTicketIndex(*id, *seq); } -static Expected +static std::expected parseVault( json::Value const& params, json::StaticString const fieldName, @@ -755,16 +755,16 @@ parseVault( auto const id = LedgerEntryHelpers::requiredAccountID(params, jss::owner, "malformedOwner"); if (!id) - return Unexpected(id.error()); + return std::unexpected(id.error()); auto const seq = LedgerEntryHelpers::requiredUInt32(params, jss::seq, "malformedRequest"); if (!seq) - return Unexpected(seq.error()); + return std::unexpected(seq.error()); return keylet::vault(*id, *seq).key; } -static Expected +static std::expected parseXChainOwnedClaimID( json::Value const& claimId, json::StaticString const fieldName, @@ -777,20 +777,20 @@ parseXChainOwnedClaimID( auto const bridgeSpec = LedgerEntryHelpers::parseBridgeFields(claimId); if (!bridgeSpec) - return Unexpected(bridgeSpec.error()); + return std::unexpected(bridgeSpec.error()); auto const seq = LedgerEntryHelpers::requiredUInt32( claimId, jss::xchain_owned_claim_id, "malformedXChainOwnedClaimID"); if (!seq) { - return Unexpected(seq.error()); + return std::unexpected(seq.error()); } - Keylet keylet = keylet::xChainClaimID(*bridgeSpec, *seq); + Keylet const keylet = keylet::xChainClaimID(*bridgeSpec, *seq); return keylet.key; } -static Expected +static std::expected parseXChainOwnedCreateAccountClaimID( json::Value const& claimId, json::StaticString const fieldName, @@ -803,7 +803,7 @@ parseXChainOwnedCreateAccountClaimID( auto const bridgeSpec = LedgerEntryHelpers::parseBridgeFields(claimId); if (!bridgeSpec) - return Unexpected(bridgeSpec.error()); + return std::unexpected(bridgeSpec.error()); auto const seq = LedgerEntryHelpers::requiredUInt32( claimId, @@ -811,10 +811,10 @@ parseXChainOwnedCreateAccountClaimID( "malformedXChainOwnedCreateAccountClaimID"); if (!seq) { - return Unexpected(seq.error()); + return std::unexpected(seq.error()); } - Keylet keylet = keylet::xChainCreateAccountClaimID(*bridgeSpec, *seq); + Keylet const keylet = keylet::xChainCreateAccountClaimID(*bridgeSpec, *seq); return keylet.key; } diff --git a/src/xrpld/rpc/handlers/ledger/LedgerEntryHelpers.h b/src/xrpld/rpc/handlers/ledger/LedgerEntryHelpers.h index e8e295ca2c..463547a90d 100644 --- a/src/xrpld/rpc/handlers/ledger/LedgerEntryHelpers.h +++ b/src/xrpld/rpc/handlers/ledger/LedgerEntryHelpers.h @@ -10,41 +10,42 @@ #include #include +#include #include namespace xrpl::LedgerEntryHelpers { -inline Unexpected +inline std::unexpected missingFieldError(json::StaticString const field, std::optional err = std::nullopt) { json::Value json = json::ValueType::Object; json[jss::error] = err.value_or("malformedRequest"); json[jss::error_code] = RpcInvalidParams; json[jss::error_message] = RPC::missingFieldMessage(std::string(field.cStr())); - return Unexpected(json); + return std::unexpected(json); } -inline Unexpected +inline std::unexpected invalidFieldError(std::string const& err, json::StaticString const field, std::string const& type) { json::Value json = json::ValueType::Object; json[jss::error] = err; json[jss::error_code] = RpcInvalidParams; json[jss::error_message] = RPC::expectedFieldMessage(field, type); - return Unexpected(json); + return std::unexpected(json); } -inline Unexpected +inline std::unexpected malformedError(std::string const& err, std::string const& message) { json::Value json = json::ValueType::Object; json[jss::error] = err; json[jss::error_code] = RpcInvalidParams; json[jss::error_message] = message; - return Unexpected(json); + return std::unexpected(json); } -inline Expected +inline std::expected hasRequired( json::Value const& params, std::initializer_list fields, @@ -65,7 +66,7 @@ std::optional parse(json::Value const& param); template -Expected +std::expected required( json::Value const& params, json::StaticString const fieldName, @@ -99,7 +100,7 @@ parse(json::Value const& param) return account; } -inline Expected +inline std::expected requiredAccountID( json::Value const& params, json::StaticString const fieldName, @@ -121,7 +122,7 @@ parseHexBlob(json::Value const& param, std::size_t maxLength) return blob; } -inline Expected +inline std::expected requiredHexBlob( json::Value const& params, json::StaticString const fieldName, @@ -156,7 +157,7 @@ parse(json::Value const& param) return std::nullopt; } -inline Expected +inline std::expected requiredUInt32( json::Value const& params, json::StaticString const fieldName, @@ -178,7 +179,7 @@ parse(json::Value const& param) return uNodeIndex; } -inline Expected +inline std::expected requiredUInt256( json::Value const& params, json::StaticString const fieldName, @@ -200,7 +201,7 @@ parse(json::Value const& param) return field; } -inline Expected +inline std::expected requiredUInt192( json::Value const& params, json::StaticString const fieldName, @@ -223,13 +224,13 @@ parse(json::Value const& param) } } -inline Expected +inline std::expected requiredAsset(json::Value const& params, json::StaticString const fieldName, std::string const& err) { return required(params, fieldName, err, "Asset"); } -inline Expected +inline std::expected parseBridgeFields(json::Value const& params) { if (auto const value = hasRequired( @@ -240,21 +241,21 @@ parseBridgeFields(json::Value const& params) jss::IssuingChainIssue}); !value) { - return Unexpected(value.error()); + return std::unexpected(value.error()); } auto const lockingChainDoor = requiredAccountID(params, jss::LockingChainDoor, "malformedLockingChainDoor"); if (!lockingChainDoor) { - return Unexpected(lockingChainDoor.error()); + return std::unexpected(lockingChainDoor.error()); } auto const issuingChainDoor = requiredAccountID(params, jss::IssuingChainDoor, "malformedIssuingChainDoor"); if (!issuingChainDoor) { - return Unexpected(issuingChainDoor.error()); + return std::unexpected(issuingChainDoor.error()); } Issue lockingChainIssue; diff --git a/src/xrpld/rpc/handlers/orderbook/AMMInfo.cpp b/src/xrpld/rpc/handlers/orderbook/AMMInfo.cpp index b9f4a42880..2c2f96b0e8 100644 --- a/src/xrpld/rpc/handlers/orderbook/AMMInfo.cpp +++ b/src/xrpld/rpc/handlers/orderbook/AMMInfo.cpp @@ -2,7 +2,6 @@ #include #include -#include #include #include #include @@ -18,7 +17,7 @@ #include #include #include -#include +#include // IWYU pragma: keep #include #include #include @@ -27,6 +26,7 @@ #include #include +#include #include #include #include @@ -35,7 +35,7 @@ namespace xrpl { -Expected +std::expected getAsset(json::Value const& v, beast::Journal j) { try @@ -46,7 +46,7 @@ getAsset(json::Value const& v, beast::Journal j) { JLOG(j.debug()) << "getAsset " << ex.what(); } - return Unexpected(RpcIssueMalformed); + return std::unexpected(RpcIssueMalformed); } std::string @@ -79,7 +79,7 @@ doAMMInfo(RPC::JsonContext& context) SLE::const_pointer amm; }; - auto getValuesFromContextParams = [&]() -> Expected { + auto getValuesFromContextParams = [&]() -> std::expected { std::optional accountID; std::optional asset1; std::optional asset2; @@ -92,7 +92,7 @@ doAMMInfo(RPC::JsonContext& context) // NOTE, identical check for apVersion >= 3 below if (context.apiVersion < 3 && kInvalid(params)) - return Unexpected(RpcInvalidParams); + return std::unexpected(RpcInvalidParams); if (params.isMember(jss::asset)) { @@ -102,7 +102,7 @@ doAMMInfo(RPC::JsonContext& context) } else { - return Unexpected(i.error()); + return std::unexpected(i.error()); } } @@ -114,7 +114,7 @@ doAMMInfo(RPC::JsonContext& context) } else { - return Unexpected(i.error()); + return std::unexpected(i.error()); } } @@ -122,25 +122,25 @@ doAMMInfo(RPC::JsonContext& context) { auto const id = parseBase58((params[jss::amm_account].asString())); if (!id) - return Unexpected(RpcActMalformed); + return std::unexpected(RpcActMalformed); auto const sle = ledger->read(keylet::account(*id)); if (!sle) - return Unexpected(RpcActMalformed); + return std::unexpected(RpcActMalformed); ammID = sle->getFieldH256(sfAMMID); if (ammID->isZero()) - return Unexpected(RpcActNotFound); + return std::unexpected(RpcActNotFound); } if (params.isMember(jss::account)) { accountID = parseBase58(params[jss::account].asString()); if (!accountID || !ledger->read(keylet::account(*accountID))) - return Unexpected(RpcActMalformed); + return std::unexpected(RpcActMalformed); } // NOTE, identical check for apVersion < 3 above if (context.apiVersion >= 3 && kInvalid(params)) - return Unexpected(RpcInvalidParams); + return std::unexpected(RpcInvalidParams); XRPL_ASSERT( (asset1.has_value() == asset2.has_value()) && (asset1.has_value() != ammID.has_value()), @@ -154,7 +154,7 @@ doAMMInfo(RPC::JsonContext& context) }(); auto const amm = ledger->read(ammKeylet); if (!amm) - return Unexpected(RpcActNotFound); + return std::unexpected(RpcActNotFound); if (!asset1 && !asset2) { asset1 = (*amm)[sfAsset]; diff --git a/src/xrpld/rpc/handlers/server_info/ServerDefinitions.cpp b/src/xrpld/rpc/handlers/server_info/ServerDefinitions.cpp index aa23a7af26..1e9e0ddc14 100644 --- a/src/xrpld/rpc/handlers/server_info/ServerDefinitions.cpp +++ b/src/xrpld/rpc/handlers/server_info/ServerDefinitions.cpp @@ -65,7 +65,7 @@ ServerDefinitions::translate(std::string const& inp) }; // TODO: use string::contains with C++23 - auto contains = [&](std::string_view s) -> bool { return inp.find(s) != std::string::npos; }; + auto contains = [&](std::string_view s) -> bool { return inp.contains(s); }; if (contains("UINT")) { diff --git a/src/xrpld/rpc/handlers/transaction/Simulate.cpp b/src/xrpld/rpc/handlers/transaction/Simulate.cpp index 676f0318a2..7ee28c4886 100644 --- a/src/xrpld/rpc/handlers/transaction/Simulate.cpp +++ b/src/xrpld/rpc/handlers/transaction/Simulate.cpp @@ -7,7 +7,6 @@ #include #include -#include #include #include #include @@ -33,6 +32,7 @@ #include #include +#include #include #include #include @@ -42,7 +42,7 @@ namespace xrpl { -static Expected +static std::expected getAutofillSequence(json::Value const& txJson, RPC::JsonContext& context) { // autofill Sequence @@ -52,13 +52,13 @@ getAutofillSequence(json::Value const& txJson, RPC::JsonContext& context) { // sanity check, should fail earlier // LCOV_EXCL_START - return Unexpected(RPC::invalidFieldError("tx.Account")); + return std::unexpected(RPC::invalidFieldError("tx.Account")); // LCOV_EXCL_STOP } auto const srcAddressID = parseBase58(accountStr.asString()); if (!srcAddressID.has_value()) { - return Unexpected( + return std::unexpected( RPC::makeError(RpcSrcActMalformed, RPC::invalidFieldMessage("tx.Account"))); } SLE::const_pointer const sle = @@ -69,7 +69,7 @@ getAutofillSequence(json::Value const& txJson, RPC::JsonContext& context) << "Failed to find source account " << "in current ledger: " << toBase58(*srcAddressID); - return Unexpected(rpcError(RpcSrcActNotFound)); + return std::unexpected(rpcError(RpcSrcActNotFound)); } return hasTicketSeq ? 0 : context.app.getTxQ().nextQueuableSeq(sle).value(); diff --git a/src/xrpld/rpc/handlers/transaction/Submit.cpp b/src/xrpld/rpc/handlers/transaction/Submit.cpp index f0c4cb2391..79f3680684 100644 --- a/src/xrpld/rpc/handlers/transaction/Submit.cpp +++ b/src/xrpld/rpc/handlers/transaction/Submit.cpp @@ -4,7 +4,6 @@ #include #include -#include #include #include #include @@ -21,17 +20,18 @@ #include #include +#include #include #include namespace xrpl { -static Expected +static std::expected getFailHard(RPC::JsonContext const& context) { if (context.params.isMember(jss::fail_hard) && !context.params[jss::fail_hard].isBool()) { - return Unexpected(RPC::expectedFieldError(jss::fail_hard, "boolean")); + return std::unexpected(RPC::expectedFieldError(jss::fail_hard, "boolean")); } return NetworkOPs::doFailHard( context.params.isMember(jss::fail_hard) && context.params[jss::fail_hard].asBool());