xrpld
Loading...
Searching...
No Matches
libxrpl/protocol/STAmount.cpp
1#include <xrpl/protocol/STAmount.h>
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/MathUtilities.h>
5#include <xrpl/basics/Number.h>
6#include <xrpl/basics/contract.h>
7#include <xrpl/basics/safe_cast.h>
8#include <xrpl/beast/utility/Zero.h>
9#include <xrpl/beast/utility/instrumentation.h>
10#include <xrpl/json/json_forwards.h>
11#include <xrpl/json/json_value.h>
12#include <xrpl/protocol/AccountID.h>
13#include <xrpl/protocol/Asset.h>
14#include <xrpl/protocol/Concepts.h>
15#include <xrpl/protocol/Feature.h>
16#include <xrpl/protocol/IOUAmount.h>
17#include <xrpl/protocol/Issue.h>
18#include <xrpl/protocol/MPTAmount.h>
19#include <xrpl/protocol/MPTIssue.h>
20#include <xrpl/protocol/Protocol.h>
21#include <xrpl/protocol/Rules.h>
22#include <xrpl/protocol/SField.h>
23#include <xrpl/protocol/STArray.h>
24#include <xrpl/protocol/STBase.h>
25#include <xrpl/protocol/STNumber.h>
26#include <xrpl/protocol/STObject.h>
27#include <xrpl/protocol/Serializer.h>
28#include <xrpl/protocol/SystemParameters.h>
29#include <xrpl/protocol/UintTypes.h>
30#include <xrpl/protocol/XRPAmount.h>
31#include <xrpl/protocol/jss.h>
32
33#include <boost/algorithm/string/classification.hpp>
34#include <boost/algorithm/string/split.hpp>
35#include <boost/multiprecision/detail/default_ops.hpp>
36
37#include <algorithm>
38#include <cstddef>
39#include <cstdint>
40#include <exception>
41#include <format>
42#include <iterator>
43#include <limits>
44#include <memory>
45#include <optional>
46#include <stdexcept>
47#include <string>
48#include <utility>
49#include <variant>
50#include <vector>
51
52namespace xrpl {
53
54static std::uint64_t const kTenTO14 = 100000000000000ull;
56static std::uint64_t const kTenTO17 = kTenTO14 * 1000;
57
58//------------------------------------------------------------------------------
59static std::int64_t
60getInt64Value(STAmount const& amount, bool valid, char const* error)
61{
62 if (!valid)
64 XRPL_ASSERT(amount.exponent() == 0, "xrpl::getInt64Value : exponent is zero");
65
66 auto ret = static_cast<std::int64_t>(amount.mantissa());
67
68 XRPL_ASSERT(
69 static_cast<std::uint64_t>(ret) == amount.mantissa(),
70 "xrpl::getInt64Value : mantissa must roundtrip");
71
72 if (amount.negative())
73 ret = -ret;
74
75 return ret;
76}
77
78static std::int64_t
79getSNValue(STAmount const& amount)
80{
81 return getInt64Value(amount, amount.native(), "amount is not native!");
82}
83
84static std::int64_t
85getMPTValue(STAmount const& amount)
86{
87 return getInt64Value(amount, amount.holds<MPTIssue>(), "amount is not MPT!");
88}
89
90static bool
91areComparable(STAmount const& v1, STAmount const& v2)
92{
93 return std::visit(
94 [&]<ValidIssueType TIss1, ValidIssueType TIss2>(TIss1 const& issue1, TIss2 const& issue2) {
95 if constexpr (kIsIssueV<TIss1> && kIsIssueV<TIss2>)
96 {
97 return v1.native() == v2.native() && issue1.currency == issue2.currency;
98 }
99 else if constexpr (kIsMptissueV<TIss1> && kIsMptissueV<TIss2>)
100 {
101 return issue1 == issue2;
102 }
103 else
104 {
105 return false;
106 }
107 },
108 v1.asset().value(),
109 v2.asset().value());
110}
111
112static_assert(kInitialXrp.drops() == STAmount::kMaxNativeN);
113
114STAmount::STAmount(SerialIter& sit, SField const& name) : STBase(name)
115{
116 std::uint64_t value = sit.get64();
117
118 // native or MPT
119 if ((value & kIssuedCurrency) == 0)
120 {
121 if ((value & kMpToken) != 0)
122 {
123 // is MPT
124 offset_ = 0;
125 isNegative_ = (value & kPositive) == 0;
126 value_ = (value << 8) | sit.get8();
127 asset_ = sit.get192();
128 return;
129 }
130 // else is XRP
131 asset_ = xrpIssue();
132 // positive
133 if ((value & kPositive) != 0)
134 {
136 offset_ = 0;
137 isNegative_ = false;
138 return;
139 }
140
141 // negative
142 if (value == 0)
143 Throw<std::runtime_error>("negative zero is not canonical");
144
146 offset_ = 0;
147 isNegative_ = true;
148 return;
149 }
150
151 Issue issue;
152 issue.currency = sit.get160();
153
154 if (isXRP(issue.currency))
155 Throw<std::runtime_error>("invalid native currency");
156
157 issue.account = sit.get160();
158
159 if (isXRP(issue.account))
160 Throw<std::runtime_error>("invalid native account");
161
162 // 10 bits for the offset, sign and "not native" flag
163 int offset = static_cast<int>(value >> (64 - 10));
164
165 value &= ~(1023ull << (64 - 10));
166
167 if (value != 0u)
168 {
169 bool const isNegative = (offset & 256) == 0;
170 offset = (offset & 255) - 97; // center the range
171
172 if (value < kMinValue || value > kMaxValue || offset < kMinOffset || offset > kMaxOffset)
173 {
174 Throw<std::runtime_error>("invalid currency value");
175 }
176
177 asset_ = issue;
178 value_ = value;
179 offset_ = offset;
180 isNegative_ = isNegative;
181 canonicalize();
182 return;
183 }
184
185 if (offset != 512)
186 Throw<std::runtime_error>("invalid currency value");
187
188 asset_ = issue;
189 value_ = 0;
190 offset_ = 0;
191 isNegative_ = false;
192 canonicalize();
193}
194
196 : STBase(name), asset_(xrpIssue()), offset_(0)
197{
198 set(mantissa);
199}
200
203{
204 XRPL_ASSERT(
206 "xrpl::STAmount::STAmount(SField, std::uint64_t, bool) : maximum "
207 "mantissa input");
208}
209
210STAmount::STAmount(SField const& name, STAmount const& from)
211 : STBase(name)
212 , asset_(from.asset_)
213 , value_(from.value_)
214 , offset_(from.offset_)
216{
217 XRPL_ASSERT(
219 "xrpl::STAmount::STAmount(SField, STAmount) : maximum input");
220 canonicalize();
221}
222
223//------------------------------------------------------------------------------
224
227{
228 XRPL_ASSERT(
230 "xrpl::STAmount::STAmount(std::uint64_t, bool) : maximum mantissa "
231 "input");
232}
233
235 : asset_(xrpIssue()), offset_(0), isNegative_(amount < beast::kZero)
236{
237 if (isNegative_)
238 {
240 }
241 else
242 {
244 }
245
246 canonicalize();
247}
248
251{
252 return std::make_unique<STAmount>(sit, name);
253}
254
255STBase*
256STAmount::copy(std::size_t n, void* buf) const
257{
258 return emplace(n, buf, *this);
259}
260
261STBase*
263{
264 return emplace(n, buf, std::move(*this));
265}
266
267//------------------------------------------------------------------------------
268//
269// Conversion
270//
271//------------------------------------------------------------------------------
274{
275 if (!native())
276 Throw<std::logic_error>("Cannot return non-native STAmount as XRPAmount");
277
278 auto drops = static_cast<XRPAmount::value_type>(value_);
279 XRPL_ASSERT(offset_ == 0, "xrpl::STAmount::xrp : amount is canonical");
280
281 if (isNegative_)
282 drops = -drops;
283
284 return XRPAmount{drops};
285}
286
289{
290 if (integral())
291 Throw<std::logic_error>("Cannot return non-IOU STAmount as IOUAmount");
292
293 auto mantissa = static_cast<std::int64_t>(value_);
294 auto const exponent = offset_;
295
296 if (isNegative_)
298
299 return {mantissa, exponent};
300}
301
304{
305 if (!holds<MPTIssue>())
306 Throw<std::logic_error>("Cannot return STAmount as MPTAmount");
307
308 auto value = static_cast<MPTAmount::value_type>(value_);
309 XRPL_ASSERT(offset_ == 0, "xrpl::STAmount::mpt : amount is canonical");
310
311 if (isNegative_)
312 value = -value;
313
314 return MPTAmount{value};
315}
316
319{
320 XRPL_ASSERT(integral() == false, "xrpl::STAmount::operator=(IOUAmount) : is not integral");
321 offset_ = iou.exponent();
323 if (isNegative_)
324 {
325 value_ = static_cast<std::uint64_t>(-iou.mantissa());
326 }
327 else
328 {
329 value_ = static_cast<std::uint64_t>(iou.mantissa());
330 }
331 return *this;
332}
333
336{
337 if (!getCurrentTransactionRules() || isFeatureEnabled(featureSingleAssetVault) ||
338 isFeatureEnabled(featureLendingProtocol))
339 {
340 *this = fromNumber(asset_, number);
341 }
342 else
343 {
344 auto const originalMantissa = number.mantissa();
345 isNegative_ = originalMantissa < 0;
346 value_ = isNegative_ ? -originalMantissa : originalMantissa;
347 offset_ = number.exponent();
348 }
349 canonicalize();
350 return *this;
351}
352
353//------------------------------------------------------------------------------
354//
355// Operators
356//
357//------------------------------------------------------------------------------
358
361{
362 *this = *this + a;
363 return *this;
364}
365
368{
369 *this = *this - a;
370 return *this;
371}
372
374operator+(STAmount const& v1, STAmount const& v2)
375{
376 if (!areComparable(v1, v2))
377 Throw<std::runtime_error>("Can't add amounts that are't comparable!");
378
379 if (v2 == beast::kZero)
380 return v1;
381
382 if (v1 == beast::kZero)
383 {
384 // Result must be in terms of v1 currency and issuer.
385 return {v1.getFName(), v1.asset(), v2.mantissa(), v2.exponent(), v2.negative()};
386 }
387
388 // XRPAmount and MPTAmount check for int64 overflow under fixCleanup3_5_0.
389 if (v1.native())
390 return {v1.getFName(), (v1.xrp() + v2.xrp()).drops()};
391 if (v1.holds<MPTIssue>())
392 return {v1.asset_, (v1.mpt() + v2.mpt()).value()};
393
394 auto x = v1;
395 x = v1.iou() + v2.iou();
396 return x;
397}
398
400operator-(STAmount const& v1, STAmount const& v2)
401{
402 return v1 + (-v2);
403}
404
405//------------------------------------------------------------------------------
406
407std::uint64_t const STAmount::kURateOne = getRate(STAmount(1), STAmount(1));
408
409void
411{
412 asset_ = asset;
413}
414
415// Convert an offer into an index amount so they sort by rate.
416// A taker will take the best, lowest, rate first.
417// (e.g. a taker will prefer pay 1 get 3 over pay 1 get 2.
418// --> offerOut: takerGets: How much the offerer is selling to the taker.
419// --> offerIn: takerPays: How much the offerer is receiving from the taker.
420// <-- uRate: normalize(offerIn/offerOut)
421// A lower rate is better for the person taking the order.
422// The taker gets more for less with a lower rate.
423// Zero is returned if the offer is worthless.
425getRate(STAmount const& offerOut, STAmount const& offerIn)
426{
427 if (offerOut == beast::kZero)
428 return 0;
429
430 try
431 {
432 STAmount const r = divide(offerIn, offerOut, noIssue());
433 if (r == beast::kZero) // offer is too good
434 return 0;
435 XRPL_ASSERT(
436 (r.exponent() >= -100) && (r.exponent() <= 155),
437 "xrpl::getRate : exponent inside range");
438 std::uint64_t const ret = r.exponent() + 100;
439 return (ret << (64 - 8)) | r.mantissa();
440 }
441 catch (...)
442 {
443 // overflow -- very bad offer
444 return 0;
445 }
446}
447
448bool
449isRepresentable(Asset const& asset, Number const& value)
450{
451 try
452 {
453 // Out-of-range values throw std::overflow_error from Number or
454 // IOUAmount, or std::runtime_error from STAmount::canonicalize.
455 [[maybe_unused]] STAmount const amount{asset, value};
456 return true;
457 }
458 catch (std::runtime_error const&)
459 {
460 return false;
461 }
462}
463
482bool
483canAdd(STAmount const& a, STAmount const& b)
484{
485 // cannot add different currencies
486 if (!areComparable(a, b))
487 return false;
488
489 // special case: adding anything to zero is always fine
490 if (a == beast::kZero || b == beast::kZero)
491 return true;
492
493 // XRP case (overflow & underflow check)
494 if (isXRP(a) && isXRP(b))
495 return checkedAdd(a.xrp().drops(), b.xrp().drops()).has_value();
496
497 // IOU case (precision check)
498 auto const ret = std::visit(
499 [&]<ValidIssueType TIss1, ValidIssueType TIss2>(
500 TIss1 const&, TIss2 const&) -> std::optional<bool> {
501 if constexpr (kIsIssueV<TIss1> && kIsIssueV<TIss2>)
502 {
503 static STAmount const kOne{IOUAmount{1, 0}, noIssue()};
504 static STAmount const kMaxLoss{IOUAmount{1, -4}, noIssue()};
505 STAmount const lhs = divide((a - b) + b, a, noIssue()) - kOne;
506 STAmount const rhs = divide((b - a) + a, b, noIssue()) - kOne;
507 return ((rhs.negative() ? -rhs : rhs) + (lhs.negative() ? -lhs : lhs)) <= kMaxLoss;
508 }
509
510 // MPT (overflow & underflow check)
512 return checkedAdd(a.mpt().value(), b.mpt().value()).has_value();
513 return std::nullopt;
514 },
515 a.asset().value(),
516 b.asset().value());
517 if (ret)
518 return *ret;
519 // LCOV_EXCL_START
520 UNREACHABLE("STAmount::canAdd : unexpected STAmount type");
521 return false;
522 // LCOV_EXCL_STOP
523}
524
542bool
543canSubtract(STAmount const& a, STAmount const& b)
544{
545 // Cannot subtract different currencies
546 if (!areComparable(a, b))
547 return false;
548
549 // Special case: subtracting zero is always fine
550 if (b == beast::kZero)
551 return true;
552
553 // XRP case (underflow & overflow check)
554 if (isXRP(a) && isXRP(b))
555 {
556 XRPAmount const aVal = a.xrp();
557 XRPAmount const bVal = b.xrp();
558 // Check for underflow
559 if (bVal > XRPAmount{0} && aVal < bVal)
560 return false;
561
562 // Check for overflow
563 return checkedSub(aVal.drops(), bVal.drops()).has_value();
564 }
565
566 // IOU case (no underflow)
567 auto const ret = std::visit(
568 [&]<ValidIssueType TIss1, ValidIssueType TIss2>(
569 TIss1 const&, TIss2 const&) -> std::optional<bool> {
570 if constexpr (kIsIssueV<TIss1> && kIsIssueV<TIss2>)
571 {
572 return true;
573 }
574
575 // MPT case (underflow & overflow check)
577 {
578 MPTAmount const aVal = a.mpt();
579 MPTAmount const bVal = b.mpt();
580
581 // Underflow check
582 if (bVal > MPTAmount{0} && aVal < bVal)
583 return false;
584
585 // Overflow check
586 return checkedSub(aVal.value(), bVal.value()).has_value();
587 }
588 return std::nullopt;
589 },
590 a.asset().value(),
591 b.asset().value());
592 if (ret)
593 return *ret;
594 // LCOV_EXCL_START
595 UNREACHABLE("STAmount::canSubtract : unexpected STAmount type");
596 return false;
597 // LCOV_EXCL_STOP
598}
599
600void
602{
604
605 if (!native())
606 {
607 // It is an error for currency or issuer not to be specified for valid
608 // json.
609 elem[jss::value] = getText();
610 asset_.setJson(elem);
611 }
612 else
613 {
614 elem = getText();
615 }
616}
617
618//------------------------------------------------------------------------------
619//
620// STBase
621//
622//------------------------------------------------------------------------------
623
626{
627 return STI_AMOUNT;
628}
629
632{
633 std::string ret;
634
635 ret.reserve(64);
636 ret = getText() + "/" + asset_.getText();
637 return ret;
638}
639
642{
643 // keep full internal accuracy, but make more human friendly if possible
644 if (*this == beast::kZero)
645 return "0";
646
647 std::string const rawValue(std::to_string(value_));
648 std::string ret;
649
650 if (isNegative_)
651 ret.append(1, '-');
652
653 bool const scientific((offset_ != 0) && ((offset_ < -25) || (offset_ > -5)));
654
655 if (native() || asset_.holds<MPTIssue>() || scientific)
656 {
657 ret.append(rawValue);
658
659 if (scientific)
660 {
661 ret.append(1, 'e');
663 }
664
665 return ret;
666 }
667
668 XRPL_ASSERT(offset_ + 43 > 0, "xrpl::STAmount::getText : minimum offset");
669
670 size_t const padPrefix = 27;
671 size_t const padSuffix = 23;
672
673 std::string val;
674 val.reserve(rawValue.length() + padPrefix + padSuffix);
675 val.append(padPrefix, '0');
676 val.append(rawValue);
677 val.append(padSuffix, '0');
678
679 size_t const offset(offset_ + 43);
680
681 auto preFrom(val.begin());
682 auto const preTo(val.begin() + offset);
683
684 auto const postFrom(val.begin() + offset);
685 auto postTo(val.end());
686
687 // Crop leading zeroes. Take advantage of the fact that there's always a
688 // fixed amount of leading zeroes and skip them.
689 if (std::distance(preFrom, preTo) > padPrefix)
690 preFrom += padPrefix;
691
692 XRPL_ASSERT(postTo >= postFrom, "xrpl::STAmount::getText : first distance check");
693
694 preFrom = std::find_if(preFrom, preTo, [](char c) { return c != '0'; });
695
696 // Crop trailing zeroes. Take advantage of the fact that there's always a
697 // fixed amount of trailing zeroes and skip them.
698 if (std::distance(postFrom, postTo) > padSuffix)
699 postTo -= padSuffix;
700
701 XRPL_ASSERT(postTo >= postFrom, "xrpl::STAmount::getText : second distance check");
702
703 postTo = std::find_if(
706 [](char c) { return c != '0'; })
707 .base();
708
709 // Assemble the output:
710 if (preFrom == preTo)
711 {
712 ret.append(1, '0');
713 }
714 else
715 {
716 ret.append(preFrom, preTo);
717 }
718
719 if (postTo != postFrom)
720 {
721 ret.append(1, '.');
722 ret.append(postFrom, postTo);
723 }
724
725 return ret;
726}
727
730{
731 json::Value elem;
732 setJson(elem);
733 return elem;
734}
735
736void
738{
739 asset_.visit(
740 [&](MPTIssue const& issue) {
741 auto u8 = static_cast<unsigned char>(kMpToken >> 56);
742 if (!isNegative_)
743 u8 |= static_cast<unsigned char>(kPositive >> 56);
744 s.add8(u8);
745 s.add64(value_);
746 s.addBitString(issue.getMptID());
747 },
748 [&](Issue const& issue) {
749 if (native())
750 {
751 XRPL_ASSERT(offset_ == 0, "xrpl::STAmount::add : zero offset");
752
753 if (!isNegative_)
754 {
756 }
757 else
758 {
759 s.add64(value_);
760 }
761 }
762 else
763 {
764 if (*this == beast::kZero)
765 {
767 }
768 else if (isNegative_) // 512 = not native
769 {
770 s.add64(value_ | (static_cast<std::uint64_t>(offset_ + 512 + 97) << (64 - 10)));
771 }
772 else // 256 = positive
773 {
774 s.add64(
775 value_ |
776 (static_cast<std::uint64_t>(offset_ + 512 + 256 + 97) << (64 - 10)));
777 }
778 s.addBitString(issue.currency);
779 s.addBitString(issue.account);
780 }
781 });
782}
783
784bool
786{
787 auto const* v = dynamic_cast<STAmount const*>(&t);
788 return (v != nullptr) && (*v == *this);
789}
790
791bool
793{
794 return (value_ == 0) && native();
795}
796
797//------------------------------------------------------------------------------
798
799// amount = value_ * [10 ^ offset_]
800// Representation range is 10^80 - 10^(-80).
801//
802// On the wire:
803// - high bit is 0 for XRP, 1 for issued currency
804// - next bit is 1 for positive, 0 for negative (except 0 issued currency, which
805// is a special case of 0x8000000000000000
806// - for issued currencies, the next 8 bits are (offset_+97).
807// The +97 is so that this value is always positive.
808// - The remaining bits are significant digits (mantissa)
809// That's 54 bits for issued currency and 62 bits for native
810// (but XRP only needs 57 bits for the max value of 10^17 drops)
811//
812// value_ is zero if the amount is zero, otherwise it's within the range
813// 10^15 to (10^16 - 1) inclusive.
814// offset_ is in the range -96 to +80.
815void
817{
818 if (integral())
819 {
820 // native and MPT currency amounts should always have an offset of zero
821 // log(2^64,10) ~ 19.2
822 if (value_ == 0 || offset_ <= -20)
823 {
824 value_ = 0;
825 offset_ = 0;
826 isNegative_ = false;
827 return;
828 }
829
830 // log(cMaxNativeN, 10) == 17
831 if (native() && offset_ > 17)
832 Throw<std::runtime_error>("Native currency amount out of range");
833 // log(maxMPTokenAmount, 10) ~ 18.96
834 if (asset_.holds<MPTIssue>() && offset_ > 18)
835 Throw<std::runtime_error>("MPT amount out of range");
836
838 auto const set = [&](auto const& val) {
839 auto const value = val.value();
840 isNegative_ = value < 0;
842 };
843 if (native())
844 {
845 set(XRPAmount{num});
846 }
847 else if (asset_.holds<MPTIssue>())
848 {
849 set(MPTAmount{num});
850 }
851 else
852 {
853 Throw<std::runtime_error>("Unknown integral asset type"); // LCOV_EXCL_LINE
854 }
855 offset_ = 0;
856
857 if (native() && value_ > kMaxNativeN)
858 {
859 Throw<std::runtime_error>("Native currency amount out of range");
860 }
861 if (!native() && value_ > kMaxMpTokenAmount)
862 {
863 Throw<std::runtime_error>("MPT amount out of range");
864 }
865
866 return;
867 }
868
869 *this = iou();
870}
871
872void
874{
875 if (v < 0)
876 {
877 isNegative_ = true;
878 value_ = static_cast<std::uint64_t>(-v);
879 }
880 else
881 {
882 isNegative_ = false;
883 value_ = static_cast<std::uint64_t>(v);
884 }
885}
886
887//------------------------------------------------------------------------------
888
891{
892 if (rate == 0)
893 return STAmount(noIssue());
894
895 std::uint64_t const mantissa = rate & ~(255ull << (64 - 8));
896 int const exponent = static_cast<int>(rate >> (64 - 8)) - 100;
897
898 return STAmount(noIssue(), mantissa, exponent);
899}
900
901STAmount
902amountFromString(Asset const& asset, std::string const& amount)
903{
904 auto const parts = partsFromString(amount);
905 if ((asset.native() || asset.holds<MPTIssue>()) && parts.exponent < 0)
906 Throw<std::runtime_error>("XRP and MPT must be specified as integral amount.");
907 return {asset, parts.mantissa, parts.exponent, parts.negative};
908}
909
910STAmount
911amountFromJson(SField const& name, json::Value const& v)
912{
913 Asset asset;
914
915 json::Value value;
916 json::Value currencyOrMPTID;
917 json::Value issuer;
918 bool isMPT = false;
919
920 if (v.isNull())
921 {
922 Throw<std::runtime_error>("XRP may not be specified with a null Json value");
923 }
924 if (v.isObject())
925 {
926 if (!validJSONAsset(v))
927 Throw<std::runtime_error>("Invalid Asset's Json specification");
928
929 value = v[jss::value];
930 if (v.isMember(jss::mpt_issuance_id))
931 {
932 isMPT = true;
933 currencyOrMPTID = v[jss::mpt_issuance_id];
934 }
935 else
936 {
937 currencyOrMPTID = v[jss::currency];
938 issuer = v[jss::issuer];
939 }
940 }
941 else if (v.isArray())
942 {
943 value = v.get(json::UInt(0), 0);
944 currencyOrMPTID = v.get(json::UInt(1), json::ValueType::Null);
945 issuer = v.get(json::UInt(2), json::ValueType::Null);
946 }
947 else if (v.isString())
948 {
949 std::string val = v.asString();
951 boost::split(elements, val, boost::is_any_of("\t\n\r ,/"));
952
953 if (elements.size() > 3)
954 Throw<std::runtime_error>("invalid amount string");
955
956 value = elements[0];
957
958 if (elements.size() > 1)
959 currencyOrMPTID = elements[1];
960
961 if (elements.size() > 2)
962 issuer = elements[2];
963 }
964 else
965 {
966 value = v;
967 }
968
969 bool const native = !currencyOrMPTID.isString() || currencyOrMPTID.asString().empty() ||
970 (currencyOrMPTID.asString() == systemCurrencyCode());
971
972 if (native)
973 {
974 if (v.isObjectOrNull())
975 Throw<std::runtime_error>("XRP may not be specified as an object");
976 asset = xrpIssue();
977 }
978 else
979 {
980 if (isMPT)
981 {
982 // sequence (32 bits) + account (160 bits)
983 MPTID u;
984 if (!u.parseHex(currencyOrMPTID.asString()))
985 Throw<std::runtime_error>("invalid MPTokenIssuanceID");
986 asset = u;
987 }
988 else
989 {
990 Issue issue;
991 if (!toCurrency(issue.currency, currencyOrMPTID.asString()))
992 Throw<std::runtime_error>("invalid currency");
993 if (!issuer.isString() || !toIssuer(issue.account, issuer.asString()))
994 Throw<std::runtime_error>("invalid issuer");
995 if (issue.native())
996 Throw<std::runtime_error>("invalid issuer");
997 asset = issue;
998 }
999 }
1000
1001 NumberParts parts;
1002
1003 if (value.isInt())
1004 {
1005 if (value.asInt() >= 0)
1006 {
1007 parts.mantissa = value.asInt();
1008 }
1009 else
1010 {
1011 parts.mantissa = value.asAbsUInt();
1012 parts.negative = true;
1013 }
1014 }
1015 else if (value.isUInt())
1016 {
1017 parts.mantissa = v.asUInt();
1018 }
1019 else if (value.isString())
1020 {
1021 parts = partsFromString(value.asString());
1022 // Can't specify XRP or MPT using fractional representation
1023 if ((asset.native() || asset.holds<MPTIssue>()) && parts.exponent < 0)
1024 Throw<std::runtime_error>("XRP and MPT must be specified as integral amount.");
1025 }
1026 else
1027 {
1028 Throw<std::runtime_error>("invalid amount type");
1029 }
1030
1031 return {name, asset, parts.mantissa, parts.exponent, parts.negative};
1032}
1033
1034bool
1036{
1037 try
1038 {
1039 result = amountFromJson(sfGeneric, jvSource);
1040 return true;
1041 }
1042 catch (std::exception const& e)
1043 {
1044 JLOG(debugLog().warn()) << "amountFromJsonNoThrow: caught: " << e.what();
1045 }
1046 return false;
1047}
1048
1049//------------------------------------------------------------------------------
1050//
1051// Operators
1052//
1053//------------------------------------------------------------------------------
1054
1055bool
1056operator==(STAmount const& lhs, STAmount const& rhs)
1057{
1058 return areComparable(lhs, rhs) && lhs.negative() == rhs.negative() &&
1059 lhs.exponent() == rhs.exponent() && lhs.mantissa() == rhs.mantissa();
1060}
1061
1062bool
1063operator<(STAmount const& lhs, STAmount const& rhs)
1064{
1065 if (!areComparable(lhs, rhs))
1066 Throw<std::runtime_error>("Can't compare amounts that are't comparable!");
1067
1068 if (lhs.negative() != rhs.negative())
1069 return lhs.negative();
1070
1071 if (lhs.mantissa() == 0)
1072 {
1073 if (rhs.negative())
1074 return false;
1075 return rhs.mantissa() != 0;
1076 }
1077
1078 // We know that lhs is non-zero and both sides have the same sign. Since
1079 // rhs is zero (and thus not negative), lhs must, therefore, be strictly
1080 // greater than zero. So if rhs is zero, the comparison must be false.
1081 if (rhs.mantissa() == 0)
1082 return false;
1083
1084 if (lhs.exponent() > rhs.exponent())
1085 return lhs.negative();
1086 if (lhs.exponent() < rhs.exponent())
1087 return !lhs.negative();
1088 if (lhs.mantissa() > rhs.mantissa())
1089 return lhs.negative();
1090 if (lhs.mantissa() < rhs.mantissa())
1091 return !lhs.negative();
1092
1093 return false;
1094}
1095
1096STAmount
1097operator-(STAmount const& value)
1098{
1099 if (value.mantissa() == 0)
1100 return value;
1101 return STAmount(
1102 value.getFName(),
1103 value.asset(),
1104 value.mantissa(),
1105 value.exponent(),
1106 !value.negative(),
1108}
1109
1110static bool
1111hasInvalidAmount(STBase const& field, int depth, beast::Journal j);
1112
1113static bool
1114hasInvalidAmount(STObject const& object, int depth, beast::Journal j)
1115{
1116 return std::ranges::any_of(
1117 object, [&](STBase const& field) { return hasInvalidAmount(field, depth, j); });
1118}
1119
1120static bool
1121hasInvalidAmount(STArray const& array, int depth, beast::Journal j)
1122{
1123 return std::ranges::any_of(
1124 array, [&](STObject const& object) { return hasInvalidAmount(object, depth, j); });
1125}
1126
1127static bool
1128hasInvalidAmount(STBase const& field, int depth, beast::Journal j)
1129{
1130 if (depth > 10)
1131 {
1132 JLOG(j.error()) << "hasInvalidAmount: depth exceeds 10";
1133 return true;
1134 }
1135
1136 // Dispatch on the serialized type tag rather than RTTI: this is on the invariant-checking path
1137 // and a dynamic_cast chain over every field of every modified entry is measurably expensive.
1138 // The object-like tags below all denote STObject subclasses (STLedgerEntry, STTx), so the
1139 // downcast is sound; nested fields are only ever plain STI_OBJECT / STI_ARRAY containers.
1140 // safeDowncast keeps a dynamic_cast validity assert in debug builds while compiling to
1141 // static_cast in release.
1142 switch (field.getSType())
1143 {
1144 case STI_AMOUNT: {
1145 auto const& amount = safeDowncast<STAmount const&>(field);
1146 return !isLegalMPT(amount) || !isLegalNet(amount);
1147 }
1148
1149 case STI_OBJECT:
1150 case STI_LEDGERENTRY:
1151 case STI_TRANSACTION:
1152 return hasInvalidAmount(safeDowncast<STObject const&>(field), depth + 1, j);
1153
1154 case STI_ARRAY:
1155 return hasInvalidAmount(safeDowncast<STArray const&>(field), depth + 1, j);
1156
1157 default: {
1158 XRPL_ASSERT(
1159 dynamic_cast<STObject const*>(&field) == nullptr,
1160 "xrpl::hasInvalidAmount : unhandled STObject type");
1161 return false;
1162 }
1163 }
1164}
1165
1166bool
1168{
1169 return hasInvalidAmount(field, 0, j);
1170}
1171
1172//------------------------------------------------------------------------------
1173//
1174// Arithmetic
1175//
1176//------------------------------------------------------------------------------
1177
1178// Calculate (a * b) / c when all three values are 64-bit
1179// without loss of precision:
1180static std::uint64_t
1181muldiv(std::uint64_t multiplier, std::uint64_t multiplicand, std::uint64_t divisor)
1182{
1183 boost::multiprecision::uint128_t ret;
1184
1185 boost::multiprecision::multiply(ret, multiplier, multiplicand);
1186 ret /= divisor;
1187
1189 {
1191 std::format("overflow: ({} * {}) / {}", multiplier, multiplicand, divisor));
1192 }
1193
1194 return static_cast<uint64_t>(ret);
1195}
1196
1197static std::uint64_t
1199 std::uint64_t multiplier,
1200 std::uint64_t multiplicand,
1201 std::uint64_t divisor,
1202 std::uint64_t rounding)
1203{
1204 boost::multiprecision::uint128_t ret;
1205
1206 boost::multiprecision::multiply(ret, multiplier, multiplicand);
1207 ret += rounding;
1208 ret /= divisor;
1209
1211 {
1213 "overflow: (({} * {}) + {}) / {}", multiplier, multiplicand, rounding, divisor));
1214 }
1215
1216 return static_cast<uint64_t>(ret);
1217}
1218
1219STAmount
1220divide(STAmount const& num, STAmount const& den, Asset const& asset)
1221{
1222 if (den == beast::kZero)
1223 Throw<std::runtime_error>("division by zero");
1224
1225 if (num == beast::kZero)
1226 return {asset};
1227
1228 // The legacy path below assumes 16-digit mantissas. An MPT mantissa is
1229 // the raw 63-bit value and is never scaled down, so an MPT numerator can
1230 // overflow the quotient and an MPT denominator shortens it, moving the +5
1231 // nudge into a significant digit. Use Number arithmetic under
1232 // MPTokensV2 whenever an MPT is involved, as mulRound/divRound do. Pin
1233 // the rounding mode so the result does not depend on the caller's.
1234 if (isFeatureEnabled(featureMPTokensV2, /*resultIfNoRules*/ true) &&
1235 (asset.holds<MPTIssue>() || num.holds<MPTIssue>() || den.holds<MPTIssue>()))
1236 {
1238 return STAmount{asset, Number{num} / Number{den}};
1239 }
1240
1241 std::uint64_t numVal = num.mantissa();
1242 std::uint64_t denVal = den.mantissa();
1243 int numOffset = num.exponent();
1244 int denOffset = den.exponent();
1245
1246 if (num.integral())
1247 {
1248 while (numVal < STAmount::kMinValue)
1249 {
1250 // Need to bring into range
1251 numVal *= 10;
1252 --numOffset;
1253 }
1254 }
1255
1256 if (den.integral())
1257 {
1258 while (denVal < STAmount::kMinValue)
1259 {
1260 denVal *= 10;
1261 --denOffset;
1262 }
1263 }
1264
1265 // We divide the two mantissas (each is between 10^15
1266 // and 10^16). To maintain precision, we multiply the
1267 // numerator by 10^17 (the product is in the range of
1268 // 10^32 to 10^33) followed by a division, so the result
1269 // is in the range of 10^16 to 10^15.
1270 std::uint64_t quotient = muldiv(numVal, kTenTO17, denVal);
1271 int offset = numOffset - denOffset - 17;
1272
1273 // An integral (XRP) numerator is not scaled down to 16 digits, so the
1274 // quotient can land in [2^63, 2^64). The STAmount constructor reads
1275 // that as a negative IOU mantissa, and the +5 can wrap. Drop a digit
1276 // first; the result is canonicalized to 16 digits anyway.
1277 if (quotient > static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max()) - 5 &&
1278 isFeatureEnabled(featureMPTokensV2, /*resultIfNoRules*/ true))
1279 {
1280 quotient /= 10;
1281 ++offset;
1282 }
1283
1284 return STAmount(asset, quotient + 5, offset, num.negative() != den.negative());
1285}
1286
1287STAmount
1288multiply(STAmount const& v1, STAmount const& v2, Asset const& asset)
1289{
1290 if (v1 == beast::kZero || v2 == beast::kZero)
1291 return STAmount(asset);
1292
1293 if (v1.native() && v2.native() && asset.native())
1294 {
1295 std::uint64_t const minV = std::min(getSNValue(v1), getSNValue(v2));
1296 std::uint64_t const maxV = std::max(getSNValue(v1), getSNValue(v2));
1297
1298 if (minV > 3000000000ull) // sqrt(cMaxNative)
1299 Throw<std::runtime_error>("Native value overflow");
1300
1301 if (((maxV >> 32) * minV) > 2095475792ull) // cMaxNative / 2^32
1302 Throw<std::runtime_error>("Native value overflow");
1303
1304 return STAmount(v1.getFName(), minV * maxV);
1305 }
1306 if (v1.holds<MPTIssue>() && v2.holds<MPTIssue>() && asset.holds<MPTIssue>())
1307 {
1308 std::uint64_t const minV = std::min(getMPTValue(v1), getMPTValue(v2));
1309 std::uint64_t const maxV = std::max(getMPTValue(v1), getMPTValue(v2));
1310
1311 if (minV > 3037000499ull) // sqrt(maxMPTokenAmount) ~ 3037000499.98
1312 Throw<std::runtime_error>("MPT value overflow");
1313
1314 if (((maxV >> 32) * minV) > 2147483648ull) // maxMPTokenAmount / 2^32
1315 Throw<std::runtime_error>("MPT value overflow");
1316
1317 return STAmount(asset, minV * maxV);
1318 }
1319
1320 auto const r = Number{v1} * Number{v2};
1321 return STAmount{asset, r};
1322}
1323
1324// This is the legacy version of canonicalizeRound. It's been in use
1325// for years, so it is deeply embedded in the behavior of cross-currency
1326// transactions.
1327//
1328// However, in 2022 it was noticed that the rounding characteristics were
1329// surprising. When the code converts from IOU-like to XRP-like there may
1330// be a fraction of the IOU-like representation that is too small to be
1331// represented in drops. `canonicalizeRound()` currently does some unusual
1332// rounding.
1333//
1334// 1. If the fractional part is greater than or equal to 0.1, then the
1335// number of drops is rounded up.
1336//
1337// 2. However, if the fractional part is less than 0.1 (for example,
1338// 0.099999), then the number of drops is rounded down.
1339//
1340// The XRP Ledger has this rounding behavior baked in. But there are
1341// situations where this rounding behavior led to undesirable outcomes.
1342// So an alternative rounding approach was introduced. You'll see that
1343// alternative below.
1344static void
1345canonicalizeRound(bool integral, std::uint64_t& value, int& offset, bool)
1346{
1347 if (integral)
1348 {
1349 if (offset < 0)
1350 {
1351 int loops = 0;
1352
1353 while (offset < -1)
1354 {
1355 value /= 10;
1356 ++offset;
1357 ++loops;
1358 }
1359
1360 value += (loops >= 2) ? 9 : 10; // add before last divide
1361 value /= 10;
1362 ++offset;
1363 }
1364 }
1365 else if (value > STAmount::kMaxValue)
1366 {
1367 while (value > (10 * STAmount::kMaxValue))
1368 {
1369 value /= 10;
1370 ++offset;
1371 }
1372
1373 value += 9; // add before last divide
1374 value /= 10;
1375 ++offset;
1376 }
1377}
1378
1379// The original canonicalizeRound did not allow the rounding direction to
1380// be specified. It also ignored some of the bits that could contribute to
1381// rounding decisions. canonicalizeRoundStrict() tracks all of the bits in
1382// the value being rounded.
1383static void
1384canonicalizeRoundStrict(bool integral, std::uint64_t& value, int& offset, bool roundUp)
1385{
1386 if (integral)
1387 {
1388 if (offset < 0)
1389 {
1390 bool hadRemainder = false;
1391
1392 while (offset < -1)
1393 {
1394 // It would be better to use std::lldiv than to separately
1395 // compute the remainder. But std::lldiv does not support
1396 // unsigned arguments.
1397 std::uint64_t const newValue = value / 10;
1398 hadRemainder |= (value != (newValue * 10));
1399 value = newValue;
1400 ++offset;
1401 }
1402 value += (hadRemainder && roundUp) ? 10 : 9; // Add before last divide
1403 value /= 10;
1404 ++offset;
1405 }
1406 }
1407 else if (value > STAmount::kMaxValue)
1408 {
1409 while (value > (10 * STAmount::kMaxValue))
1410 {
1411 value /= 10;
1412 ++offset;
1413 }
1414 value += 9; // add before last divide
1415 value /= 10;
1416 ++offset;
1417 }
1418}
1419
1420STAmount
1422{
1423 // Nothing to do for integral types.
1424 if (value.integral())
1425 return value;
1426
1427 // Nothing to do for zero.
1428 if (value == beast::kZero)
1429 return value;
1430
1431 // If the value's exponent is greater than or equal to the scale, then
1432 // rounding will do nothing, and might even lose precision, so just return
1433 // the value.
1434 if (value.exponent() >= scale)
1435 return value;
1436
1437 STAmount const referenceValue{value.asset(), STAmount::kMinValue, scale, value.negative()};
1438
1439 NumberRoundModeGuard const mg(rounding);
1440 // With an IOU, the result of addition will be truncated to the
1441 // precision of the larger value, which in this case is referenceValue. Then
1442 // remove the reference value via subtraction, and we're left with the
1443 // rounded value.
1444 return (value + referenceValue) - referenceValue;
1445}
1446
1447namespace {
1448
1449// We need a class that has an interface similar to NumberRoundModeGuard
1450// but does nothing.
1451class DontAffectNumberRoundMode
1452{
1453public:
1454 explicit DontAffectNumberRoundMode(Number::RoundingMode mode) noexcept
1455 {
1456 }
1457
1458 DontAffectNumberRoundMode(DontAffectNumberRoundMode const&) = delete;
1459
1460 DontAffectNumberRoundMode&
1461 operator=(DontAffectNumberRoundMode const&) = delete;
1462};
1463
1465roundMode(bool const resultNegative, bool const roundUp)
1466{
1467 using enum Number::RoundingMode;
1468 // STAmount roundUp means "away from zero". The legacy scaled-mantissa
1469 // multiply and divide paths reach that result with slightly different
1470 // mechanics, including a final TowardsZero materialization in multiply.
1471 //
1472 // The MPT/V2 Number path already performs the operation under the directed
1473 // mode below. Use the same mode again when converting back to STAmount so a
1474 // fractional integral result stays consistently rounded after Number
1475 // arithmetic, independent of whether the operation was multiply or divide.
1476 return roundUp ^ resultNegative ? Upward : Downward;
1477}
1478
1480roundNumberResult(
1481 Asset const& asset,
1482 bool const resultNegative,
1483 bool const roundUp,
1484 Number const& number)
1485{
1486 // MPT/V2 Number arithmetic uses directed rounding both for the operation
1487 // and for materializing the final integral amount.
1488 NumberRoundModeGuard const finalRound(roundMode(resultNegative, roundUp));
1489 auto result = STAmount{asset, number};
1490 // An integral result can't underflow: when roundUp is set, roundMode()
1491 // above selects Upward, and materializing a Number into an integral
1492 // STAmount honors that mode (Number::operator rep()), so any positive
1493 // value rounds up to at least 1.
1494 [[maybe_unused]] bool const nonzeroPositiveRoundUp =
1495 roundUp && !resultNegative && number != beast::kZero;
1496 ALWAYS(
1497 !nonzeroPositiveRoundUp || !asset.integral() || result != beast::kZero,
1498 "xrpl::roundNumberResult : positive rounded-up integral result is representable");
1499
1500 if (roundUp && !resultNegative && !result)
1501 {
1502 // Preserve existing mulRound/divRound behavior for a positive result
1503 // too small to represent in the target asset. An IOU result with an
1504 // MPT operand (e.g. 1 MPT / 1e95) below the smallest IOU is flushed to
1505 // zero by IOUAmount normalization regardless of the rounding mode, so
1506 // snap it up to the smallest positive IOU. The only zero case for an
1507 // integral result is a zero operand, which the mulRound/divRound
1508 // callers handle before reaching this function.
1509 if (asset.integral())
1510 return STAmount{asset, 1}; // LCOV_EXCL_LINE
1511 return STAmount{asset, STAmount::kMinValue, STAmount::kMinOffset, false};
1512 }
1513
1514 return result;
1515}
1516
1517} // anonymous namespace
1518
1519// Pass the canonicalizeRound function pointer as a template parameter.
1520//
1521// We might need to use NumberRoundModeGuard. Allow the caller
1522// to pass either that or a replacement as a template parameter.
1523template <void (*CanonicalizeFunc)(bool, std::uint64_t&, int&, bool), typename MightSaveRound>
1524static STAmount
1525mulRoundImpl(STAmount const& v1, STAmount const& v2, Asset const& asset, bool roundUp)
1526{
1527 if (v1 == beast::kZero || v2 == beast::kZero)
1528 return {asset};
1529
1530 if (v1.native() && v2.native() && asset.native())
1531 {
1532 std::uint64_t const minV = std::min(getSNValue(v1), getSNValue(v2));
1533 std::uint64_t const maxV = std::max(getSNValue(v1), getSNValue(v2));
1534
1535 if (minV > 3000000000ull) // sqrt(cMaxNative)
1536 Throw<std::runtime_error>("Native value overflow");
1537
1538 if (((maxV >> 32) * minV) > 2095475792ull) // cMaxNative / 2^32
1539 Throw<std::runtime_error>("Native value overflow");
1540
1541 return STAmount(v1.getFName(), minV * maxV);
1542 }
1543
1544 if (v1.holds<MPTIssue>() && v2.holds<MPTIssue>() && asset.holds<MPTIssue>())
1545 {
1546 std::uint64_t const minV = std::min(getMPTValue(v1), getMPTValue(v2));
1547 std::uint64_t const maxV = std::max(getMPTValue(v1), getMPTValue(v2));
1548
1549 if (minV > 3037000499ull) // sqrt(maxMPTokenAmount) ~ 3037000499.98
1550 Throw<std::runtime_error>("MPT value overflow");
1551
1552 if (((maxV >> 32) * minV) > 2147483648ull) // maxMPTokenAmount / 2^32
1553 Throw<std::runtime_error>("MPT value overflow");
1554
1555 return STAmount(asset, minV * maxV);
1556 }
1557
1558 bool const resultNegative = v1.negative() != v2.negative();
1559
1560 // The legacy path below assumes 16-digit mantissas. An MPT mantissa is the
1561 // raw 63-bit balance, so any MPT operand (not just an MPT result) can
1562 // overflow it: a large MPT amount times an IOU-shaped rate into an XRP or
1563 // IOU result is the offer-crossing remainder and partial-fill case. Use
1564 // Number arithmetic under MPTokensV2 whenever an MPT is involved.
1565 //
1566 // Outside a transaction (no current rules, e.g. pathfinding) default to
1567 // the Number path: an MPT operand can only reach here through MPT
1568 // offers or AMMs, which require MPTokensV2, so this keeps RPC quotes on
1569 // the same arithmetic as the transaction they describe.
1570 if (isFeatureEnabled(featureMPTokensV2, /*resultIfNoRules*/ true) &&
1571 (asset.holds<MPTIssue>() || v1.holds<MPTIssue>() || v2.holds<MPTIssue>()))
1572 {
1573 Number result;
1574 {
1575 NumberRoundModeGuard const operationRound(roundMode(resultNegative, roundUp));
1576 result = Number{v1} * Number{v2};
1577 }
1578
1579 return roundNumberResult(asset, resultNegative, roundUp, result);
1580 }
1581
1582 std::uint64_t value1 = v1.mantissa(), value2 = v2.mantissa();
1583 int offset1 = v1.exponent(), offset2 = v2.exponent();
1584
1585 if (v1.integral())
1586 {
1587 while (value1 < STAmount::kMinValue)
1588 {
1589 value1 *= 10;
1590 --offset1;
1591 }
1592 }
1593
1594 if (v2.integral())
1595 {
1596 while (value2 < STAmount::kMinValue)
1597 {
1598 value2 *= 10;
1599 --offset2;
1600 }
1601 }
1602 // We multiply the two mantissas (each is between 10^15
1603 // and 10^16), so their product is in the 10^30 to 10^32
1604 // range. Dividing their product by 10^14 maintains the
1605 // precision, by scaling the result to 10^16 to 10^18.
1606 //
1607 // If we're rounding up, we want to round up away
1608 // from zero, and if we're rounding down, truncation
1609 // is implicit.
1610 std::uint64_t amount =
1611 muldivRound(value1, value2, kTenTO14, (resultNegative != roundUp) ? kTenTO14M1 : 0);
1612
1613 int offset = offset1 + offset2 + 14;
1614 if (resultNegative != roundUp)
1615 {
1616 CanonicalizeFunc(asset.integral(), amount, offset, roundUp);
1617 }
1618 STAmount result = [&] {
1619 // If appropriate, tell Number to round down. This gives the desired
1620 // result from STAmount::canonicalize.
1621 MightSaveRound const savedRound(Number::RoundingMode::TowardsZero);
1622 return STAmount(asset, amount, offset, resultNegative);
1623 }();
1624
1625 if (roundUp && !resultNegative && !result)
1626 {
1627 if (asset.integral())
1628 {
1629 // return the smallest value above zero
1630 amount = 1;
1631 offset = 0;
1632 }
1633 else
1634 {
1635 // return the smallest value above zero
1636 amount = STAmount::kMinValue;
1637 offset = STAmount::kMinOffset;
1638 }
1639 return STAmount(asset, amount, offset, resultNegative);
1640 }
1641 return result;
1642}
1643
1644STAmount
1645mulRound(STAmount const& v1, STAmount const& v2, Asset const& asset, bool roundUp)
1646{
1648}
1649
1650STAmount
1651mulRoundStrict(STAmount const& v1, STAmount const& v2, Asset const& asset, bool roundUp)
1652{
1654}
1655
1656// We might need to use NumberRoundModeGuard. Allow the caller
1657// to pass either that or a replacement as a template parameter.
1658template <typename MightSaveRound>
1659static STAmount
1660divRoundImpl(STAmount const& num, STAmount const& den, Asset const& asset, bool roundUp)
1661{
1662 if (den == beast::kZero)
1663 Throw<std::runtime_error>("division by zero");
1664
1665 if (num == beast::kZero)
1666 return {asset};
1667
1668 bool const resultNegative = (num.negative() != den.negative());
1669
1670 // See mulRoundImpl: any MPT operand, not just an MPT result, and the
1671 // Number path when there are no current rules.
1672 // fixCleanup3_5_0: the legacy path below overflows on large MPT amounts.
1673 auto const enabled = isFeatureEnabled(featureMPTokensV2, /*resultIfNoRules*/ true) ||
1674 isFeatureEnabled(fixCleanup3_5_0, /*resultIfNoRules*/ true);
1675 if ((asset.holds<MPTIssue>() || num.holds<MPTIssue>() || den.holds<MPTIssue>()) && enabled)
1676 {
1677 // Match the multiply path above: Number performs the rounded
1678 // operation, then STAmount materializes the final MPT amount using the
1679 // same final rounding mode as the legacy path below.
1680 Number result;
1681 {
1682 NumberRoundModeGuard const operationRound(roundMode(resultNegative, roundUp));
1683 result = Number{num} / Number{den};
1684 }
1685
1686 return roundNumberResult(asset, resultNegative, roundUp, result);
1687 }
1688
1689 std::uint64_t numVal = num.mantissa(), denVal = den.mantissa();
1690 int numOffset = num.exponent(), denOffset = den.exponent();
1691
1692 if (num.integral())
1693 {
1694 while (numVal < STAmount::kMinValue)
1695 {
1696 numVal *= 10;
1697 --numOffset;
1698 }
1699 }
1700
1701 if (den.integral())
1702 {
1703 while (denVal < STAmount::kMinValue)
1704 {
1705 denVal *= 10;
1706 --denOffset;
1707 }
1708 }
1709
1710 // We divide the two mantissas (each is between 10^15
1711 // and 10^16). To maintain precision, we multiply the
1712 // numerator by 10^17 (the product is in the range of
1713 // 10^32 to 10^33) followed by a division, so the result
1714 // is in the range of 10^16 to 10^15.
1715 //
1716 // We round away from zero if we're rounding up or
1717 // truncate if we're rounding down.
1718 std::uint64_t amount =
1719 muldivRound(numVal, kTenTO17, denVal, (resultNegative != roundUp) ? denVal - 1 : 0);
1720
1721 int offset = numOffset - denOffset - 17;
1722
1723 if (resultNegative != roundUp)
1724 canonicalizeRound(asset.integral(), amount, offset, roundUp);
1725
1726 STAmount result = [&] {
1727 // If appropriate, tell Number the rounding mode we are using.
1728 // Note that "roundUp == true" actually means "round away from zero".
1729 // Otherwise, round toward zero.
1730 using enum Number::RoundingMode;
1731 MightSaveRound const savedRound(roundUp ^ resultNegative ? Upward : Downward);
1732 return STAmount(asset, amount, offset, resultNegative);
1733 }();
1734
1735 if (roundUp && !resultNegative && !result)
1736 {
1737 if (asset.integral())
1738 {
1739 // return the smallest value above zero
1740 amount = 1;
1741 offset = 0;
1742 }
1743 else
1744 {
1745 // return the smallest value above zero
1746 amount = STAmount::kMinValue;
1747 offset = STAmount::kMinOffset;
1748 }
1749 return STAmount(asset, amount, offset, resultNegative);
1750 }
1751 return result;
1752}
1753
1754STAmount
1755divRound(STAmount const& num, STAmount const& den, Asset const& asset, bool roundUp)
1756{
1757 return divRoundImpl<DontAffectNumberRoundMode>(num, den, asset, roundUp);
1758}
1759
1760STAmount
1761divRoundStrict(STAmount const& num, STAmount const& den, Asset const& asset, bool roundUp)
1762{
1763 return divRoundImpl<NumberRoundModeGuard>(num, den, asset, roundUp);
1764}
1765
1766STAmount
1768{
1769 XRPL_ASSERT(
1771 "xrpl::mulRatio(STAmount) : rounding is Upward or Downward");
1772 bool const roundUp = rounding == Number::RoundingMode::Upward;
1773 return amt.asset().visit(
1774 [&](Issue const& issue) -> STAmount {
1775 if (amt.native())
1776 return mulRatio(amt.xrp(), num, den, roundUp);
1777 return {mulRatio(amt.iou(), num, den, roundUp), issue};
1778 },
1779 [&](MPTIssue const& issue) -> STAmount {
1780 return {mulRatio(amt.mpt(), num, den, roundUp), issue};
1781 });
1782}
1783
1784[[nodiscard]] bool
1786{
1788}
1789} // namespace xrpl
T any_of(T... args)
T append(T... args)
T begin(T... args)
A generic endpoint for log messages.
Definition Journal.h:44
Stream error() const
Definition Journal.h:362
Represents a JSON value.
Definition json_value.h:121
bool isNull() const
isNull() tests to see if this field is null.
bool isObject() const
Value get(UInt index, Value const &defaultValue) const
If the array contains at least index+1 elements, returns the element value, otherwise returns default...
bool isArray() const
bool isString() const
UInt asUInt() const
std::string asString() const
Returns the unquoted string value.
bool isObjectOrNull() const
bool isMember(char const *key) const
Return true if the object has a member named key.
constexpr auto visit(Visitors &&... visitors) const -> decltype(auto)
Definition Asset.h:117
constexpr bool native() const
Definition Asset.h:125
bool integral() const
Definition Asset.h:133
constexpr bool holds() const
Definition Asset.h:177
constexpr value_type const & value() const
Definition Asset.h:201
constexpr bool parseHex(std::string_view sv)
Parse a hex string into a base_uint.
Definition base_uint.h:526
Floating point representation of amounts with high dynamic range.
Definition IOUAmount.h:26
A currency issued by an account.
Definition Issue.h:18
Currency currency
Definition Issue.h:20
AccountID account
Definition Issue.h:21
bool native() const
Definition Issue.cpp:54
std::int64_t value_type
Definition MPTAmount.h:25
constexpr value_type value() const
Returns the underlying value.
Definition MPTAmount.h:135
constexpr MPTID const & getMptID() const
Definition MPTIssue.h:43
Number is a floating point type that can represent a wide range of values.
Definition Number.h:351
constexpr rep mantissa() const noexcept
Returns the mantissa of the external view of the Number.
Definition Number.h:696
constexpr int exponent() const noexcept
Returns the exponent of the external view of the Number.
Definition Number.h:718
Identifies fields.
Definition SField.h:131
void set(std::int64_t v)
constexpr bool holds() const noexcept
Definition STAmount.h:478
void setIssue(Asset const &asset)
Set the Issue for this amount.
static constexpr std::uint64_t kIssuedCurrency
Definition STAmount.h:73
std::string getFullText() const override
static STAmount fromNumber(A const &asset, Number const &number)
Definition STAmount.h:569
void add(Serializer &s) const override
bool isNegative_
Definition STAmount.h:56
ExponentType offset_
Definition STAmount.h:55
static std::uint64_t const kURateOne
Definition STAmount.h:78
std::uint64_t mantissa() const noexcept
Definition STAmount.h:490
static constexpr std::uint64_t kPositive
Definition STAmount.h:74
int signum() const noexcept
Definition STAmount.h:522
bool isEquivalent(STBase const &t) const override
STBase * copy(std::size_t n, void *buf) const override
MantissaType value_
Definition STAmount.h:54
std::string getText() const override
static constexpr int kMinOffset
Definition STAmount.h:61
SerializedTypeID getSType() const override
bool negative() const noexcept
Definition STAmount.h:484
static constexpr std::uint64_t kMaxNativeN
Definition STAmount.h:72
bool isDefault() const override
bool integral() const noexcept
Definition STAmount.h:465
static constexpr std::uint64_t kValueMask
Definition STAmount.h:76
STAmount & operator=(beast::Zero)
Definition STAmount.h:554
static std::unique_ptr< STAmount > construct(SerialIter &, SField const &name)
bool native() const noexcept
Definition STAmount.h:471
Asset const & asset() const
Definition STAmount.h:496
STAmount & operator+=(STAmount const &)
void setJson(json::Value &) const
static constexpr std::uint64_t kMpToken
Definition STAmount.h:75
json::Value getJson(JsonOptions=JsonOptions::Values::None) const override
STAmount & operator-=(STAmount const &)
int exponent() const noexcept
Definition STAmount.h:459
bool isZeroAtScale(int scale) const
Checks if this amount evaluates to zero when constrained to a specific accounting scale.
static constexpr std::uint64_t kMinValue
Definition STAmount.h:65
static constexpr std::uint64_t kMaxValue
Definition STAmount.h:67
STBase * move(std::size_t n, void *buf) override
static constexpr int kMaxOffset
Definition STAmount.h:62
STAmount const & value() const noexcept
Definition STAmount.h:610
STAmount(SerialIter &sit, SField const &name)
A type which can be exported to a well known binary format.
Definition STBase.h:129
SField const & getFName() const
Definition STBase.cpp:120
static STBase * emplace(std::size_t n, void *buf, T &&val)
Definition STBase.h:226
virtual SerializedTypeID getSType() const
Definition STBase.cpp:54
UInt192 get192()
Definition Serializer.h:547
UInt160 get160()
Definition Serializer.h:541
int addBitString(BaseUInt< Bits, Tag > const &v)
Definition Serializer.h:202
int add8(unsigned char byteValue)
constexpr value_type drops() const
Returns the number of drops.
Definition XRPAmount.h:163
std::int64_t value_type
Definition XRPAmount.h:32
T distance(T... args)
T empty(T... args)
T end(T... args)
T find_if(T... args)
T format(T... args)
T make_reverse_iterator(T... args)
T make_unique(T... args)
T max(T... args)
T min(T... args)
constexpr Zero kZero
Definition Zero.h:30
unsigned int UInt
@ Object
object value (collection of name/value pairs).
Definition json_value.h:33
@ Null
'null' value
Definition json_value.h:26
TER valid(STTx const &tx, ReadView const &view, AccountID const &src, beast::Journal j)
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
constexpr BaseUInt< Bits, Tag > operator+(BaseUInt< Bits, Tag > const &a, BaseUInt< Bits, Tag > const &b)
Definition base_uint.h:650
static std::int64_t getMPTValue(STAmount const &amount)
constexpr std::optional< std::int64_t > checkedSub(std::int64_t a, std::int64_t b) noexcept
Subtract two signed 64-bit integers, returning std::nullopt when the exact mathematical difference is...
STAmount divide(STAmount const &amount, Rate const &rate)
Definition Rate2.cpp:69
bool operator<(Slice const &lhs, Slice const &rhs) noexcept
Definition Slice.h:212
Issue const & xrpIssue()
Returns an asset specifier that represents XRP.
Definition Issue.h:108
static STAmount mulRoundImpl(STAmount const &v1, STAmount const &v2, Asset const &asset, bool roundUp)
constexpr std::optional< std::int64_t > checkedAdd(std::int64_t a, std::int64_t b) noexcept
Add two signed 64-bit integers, returning std::nullopt when the exact mathematical sum is not represe...
constexpr bool operator==(BaseUInt< Bits, Tag > const &lhs, BaseUInt< Bits, Tag > const &rhs)
Definition base_uint.h:613
bool isLegalMPT(STAmount const &value)
Definition STAmount.h:622
bool isXRP(AccountID const &c)
Definition AccountID.h:84
beast::Journal debugLog()
Returns a debug journal.
Definition Log.cpp:399
NumberParts partsFromString(std::string const &number)
Definition STNumber.cpp:160
Number operator-(Number const &x, Number const &y)
Definition Number.h:793
STAmount mulRoundStrict(STAmount const &v1, STAmount const &v2, Asset const &asset, bool roundUp)
bool isFeatureEnabled(UInt256 const &feature, bool resultIfNoRules)
Check whether a feature is enabled in the current ledger rules.
Definition Rules.cpp:199
int scale(Number const &number, Asset const &asset)
Get the scale of a Number for a given asset.
Definition STAmount.h:819
bool isLegalNet(STAmount const &value)
Definition STAmount.h:616
bool validJSONAsset(json::Value const &jv)
Definition Asset.cpp:51
SField const sfGeneric
STAmount amountFromString(Asset const &asset, std::string const &amount)
std::optional< Rules > const & getCurrentTransactionRules()
Definition Rules.cpp:30
bool toCurrency(Currency &, std::string const &)
Tries to convert a string to a Currency, returns true on success.
Definition UintTypes.cpp:65
static std::uint64_t const kTenTO14
STAmount divRound(STAmount const &v1, STAmount const &v2, Asset const &asset, bool roundUp)
constexpr Dest unsafeCast(Src s) noexcept
Definition safe_cast.h:55
STAmount roundToScale(STAmount const &value, std::int32_t scale, Number::RoundingMode rounding=Number::getround())
Round an arbitrary precision Amount to the precision of an STAmount that has a given exponent.
bool canAdd(STAmount const &amt1, STAmount const &amt2)
Safely checks if two STAmount values can be added without overflow, underflow, or precision loss.
bool amountFromJsonNoThrow(STAmount &result, json::Value const &jvSource)
STAmount amountFromQuality(std::uint64_t rate)
IOUAmount mulRatio(IOUAmount const &amt, std::uint32_t num, std::uint32_t den, bool roundUp)
SerializedTypeID
Definition SField.h:93
BaseUInt< 192 > MPTID
MPTID is a 192-bit value representing MPT Issuance ID, which is a concatenation of a 32-bit sequence ...
Definition UintTypes.h:54
std::uint64_t getRate(STAmount const &offerOut, STAmount const &offerIn)
static std::int64_t getSNValue(STAmount const &amount)
static bool areComparable(STAmount const &v1, STAmount const &v2)
STAmount amountFromJson(SField const &name, json::Value const &v)
bool hasInvalidAmount(STBase const &field, beast::Journal j)
bool isRepresentable(Asset const &asset, Number const &value)
Check whether an arbitrary precision Number can be converted to an STAmount of a given Asset without ...
static std::uint64_t const kTenTO17
STAmount mulRound(STAmount const &v1, STAmount const &v2, Asset const &asset, bool roundUp)
static std::int64_t getInt64Value(STAmount const &amount, bool valid, char const *error)
bool canSubtract(STAmount const &amt1, STAmount const &amt2)
Determines if it is safe to subtract one STAmount from another.
Dest safeDowncast(Src *s) noexcept
Definition safe_cast.h:84
constexpr bool kIsIssueV
Definition Asset.h:162
static std::uint64_t muldivRound(std::uint64_t multiplier, std::uint64_t multiplicand, std::uint64_t divisor, std::uint64_t rounding)
STAmount divRoundStrict(STAmount const &v1, STAmount const &v2, Asset const &asset, bool roundUp)
Issue const & noIssue()
Returns an asset specifier that represents no account and currency.
Definition Issue.h:118
constexpr bool kIsMptissueV
Definition Asset.h:165
static std::uint64_t muldiv(std::uint64_t multiplier, std::uint64_t multiplicand, std::uint64_t divisor)
static std::string const & systemCurrencyCode()
STAmount multiply(STAmount const &amount, Number const &frac, Number::RoundingMode rm)
static STAmount divRoundImpl(STAmount const &num, STAmount const &den, Asset const &asset, bool roundUp)
constexpr std::uint64_t kMaxMpTokenAmount
The maximum amount of MPTokenIssuance.
Definition Protocol.h:297
constexpr XRPAmount kInitialXrp
Configure the native currency.
static void canonicalizeRoundStrict(bool integral, std::uint64_t &value, int &offset, bool roundUp)
bool toIssuer(AccountID &, std::string const &)
Convert hex or base58 string to AccountID.
static std::uint64_t const kTenTO14M1
static void canonicalizeRound(bool integral, std::uint64_t &value, int &offset, bool)
XRPL_NO_SANITIZE_ADDRESS void Throw(Args &&... args)
Definition contract.h:52
T reserve(T... args)
T length(T... args)
Note, should be treated as flags that can be | and &.
Definition STBase.h:22
std::uint64_t mantissa
Definition STNumber.h:97
T to_string(T... args)
T visit(T... args)
T what(T... args)