1#include <xrpl/basics/Expected.h>
2#include <xrpl/basics/Log.h>
3#include <xrpl/basics/chrono.h>
4#include <xrpl/beast/utility/instrumentation.h>
5#include <xrpl/ledger/CredentialHelpers.h>
6#include <xrpl/ledger/Credit.h>
7#include <xrpl/ledger/ReadView.h>
8#include <xrpl/ledger/View.h>
9#include <xrpl/protocol/Feature.h>
10#include <xrpl/protocol/Indexes.h>
11#include <xrpl/protocol/LedgerFormats.h>
12#include <xrpl/protocol/MPTIssue.h>
13#include <xrpl/protocol/Protocol.h>
14#include <xrpl/protocol/Quality.h>
15#include <xrpl/protocol/TER.h>
16#include <xrpl/protocol/TxFlags.h>
17#include <xrpl/protocol/digest.h>
18#include <xrpl/protocol/st.h>
34 auto const& svIndexes = page->getFieldV256(sfIndexes);
35 XRPL_ASSERT(index <= svIndexes.size(),
"xrpl::detail::internalDirNext : index inside range");
37 if (index >= svIndexes.size())
39 auto const next = page->getFieldU64(sfIndexNext);
52 XRPL_ASSERT(page,
"xrpl::detail::internalDirNext : non-null root");
62 entry = svIndexes[index++];
173 if (issuer != account)
201 if (issuer != account)
224 for (
auto const& account : accounts)
230 for (
auto const& account : accounts)
249 if (mptIssuance ==
nullptr)
252 auto const issuer = mptIssuance->getAccountID(sfIssuer);
254 if (mptIssuer ==
nullptr)
257 UNREACHABLE(
"xrpl::isVaultPseudoAccountFrozen : null MPToken issuer");
262 if (!mptIssuer->isFieldPresent(sfVaultID))
266 if (vault ==
nullptr)
268 UNREACHABLE(
"xrpl::isVaultPseudoAccountFrozen : null vault");
273 return isAnyFrozen(view, {issuer, account}, vault->at(sfAsset), depth + 1);
284 if (issuer == account)
337 else if (sleIssuer->isFieldPresent(sfAMMID))
342 isLPTokenFrozen(view, account, (*sleAmm)[sfAsset].get<Issue>(), (*sleAmm)[sfAsset2].get<Issue>()))
360 bool includeOppositeLimit,
366 amount = sle->getFieldAmount(sfBalance);
367 bool const accountHigh = account > issuer;
368 auto const& oppositeField = accountHigh ? sfLowLimit : sfHighLimit;
374 if (includeOppositeLimit)
376 amount += sle->getFieldAmount(oppositeField);
378 amount.setIssuer(issuer);
382 amount.clear(
Issue{currency, issuer});
385 JLOG(j.
trace()) <<
"getTrustLineBalance:" <<
" account=" <<
to_string(account)
386 <<
" amount=" << amount.getFullText();
407 bool const returnSpendable = (includeFullBalance ==
shFULL_BALANCE);
408 if (returnSpendable && account == issuer)
441 bool const returnSpendable = (includeFullBalance ==
shFULL_BALANCE);
443 if (returnSpendable && account == mptIssue.
getIssuer())
454 mptIssue, issuance->at(~sfMaximumAmount).value_or(
maxMPTokenAmount) - issuance->at(sfOutstandingAmount)};
462 amount.clear(mptIssue);
464 amount.clear(mptIssue);
467 amount =
STAmount{mptIssue, sleMpt->getFieldU64(sfMPTAmount)};
474 amount.clear(mptIssue);
483 amount.clear(mptIssue);
490[[nodiscard]] STAmount
504 return accountHolds(view, account, value, zeroIfFrozen, j, includeFullBalance);
508 return accountHolds(view, account, value, zeroIfFrozen, zeroIfUnauthorized, j, includeFullBalance);
549 JLOG(j.fatal()) <<
"Account " << *
id <<
" owner count exceeds max!";
561 JLOG(j.fatal()) <<
"Account " << *
id <<
" owner count set below 0!";
564 XRPL_ASSERT(!
id,
"xrpl::confineOwnerCount : id is not set");
584 auto const fullBalance = sle->getFieldAmount(sfBalance);
588 STAmount const amount = (balance < reserve) ?
STAmount{0} : balance - reserve;
590 JLOG(j.
trace()) <<
"accountHolds:" <<
" account=" <<
to_string(
id) <<
" amount=" << amount.getFullText()
591 <<
" fullBalance=" << fullBalance.getFullText() <<
" balance=" << balance.getFullText()
592 <<
" reserve=" << reserve <<
" ownerCount=" << ownerCount <<
" ownerCountAdj=" << ownerCountAdj;
600 XRPL_ASSERT(
root.type == ltDIR_NODE,
"xrpl::forEachItem : valid root type");
602 if (
root.type != ltDIR_NODE)
609 auto sle = view.
read(pos);
612 for (
auto const& key : sle->getFieldV256(sfIndexes))
614 auto const next = sle->getFieldU64(sfIndexNext);
630 XRPL_ASSERT(
root.type == ltDIR_NODE,
"xrpl::forEachItemAfter : valid root type");
632 if (
root.type != ltDIR_NODE)
635 auto currentIndex =
root;
638 if (
after.isNonZero())
642 if (
auto hintDir = view.
read(hintIndex))
644 for (
auto const& key : hintDir->getFieldV256(sfIndexes))
649 currentIndex = hintIndex;
658 auto const ownerDir = view.
read(currentIndex);
661 for (
auto const& key : ownerDir->getFieldV256(sfIndexes))
674 auto const uNodeNext = ownerDir->getFieldU64(sfIndexNext);
684 auto const ownerDir = view.
read(currentIndex);
687 for (
auto const& key : ownerDir->getFieldV256(sfIndexes))
690 auto const uNodeNext = ownerDir->getFieldU64(sfIndexNext);
703 if (sle && sle->isFieldPresent(sfTransferRate))
704 return Rate{sle->getFieldU32(sfTransferRate)};
716 return Rate{1'000'000'000u + 10'000 * sle->getFieldU16(sfTransferFee)};
731 amount.asset().value());
743 if (hash && (*hash != validLedger.
header().
hash))
745 JLOG(s) << reason <<
" incompatible with valid ledger";
747 JLOG(s) <<
"Hash(VSeq): " <<
to_string(*hash);
756 if (hash && (*hash != testLedger.
header().
hash))
758 JLOG(s) << reason <<
" incompatible preceding ledger";
760 JLOG(s) <<
"Hash(NSeq): " <<
to_string(*hash);
770 JLOG(s) << reason <<
" incompatible ledger";
795 if (testLedger.
header().
seq > validIndex)
799 if (hash && (*hash != validHash))
801 JLOG(s) << reason <<
" incompatible following ledger";
802 JLOG(s) <<
"Hash(VSeq): " <<
to_string(*hash);
807 else if ((validIndex == testLedger.
header().
seq) && (testLedger.
header().
hash != validHash))
809 JLOG(s) << reason <<
" incompatible ledger";
816 JLOG(s) <<
"Val: " << validIndex <<
" " <<
to_string(validHash);
827 auto const sleNode = view.
read(k);
830 if (!sleNode->getFieldV256(sfIndexes).empty())
835 return sleNode->getFieldU64(sfIndexNext) == 0;
845 if (sle->isFieldPresent(sfAmendments))
847 auto const& v = sle->getFieldV256(sfAmendments);
848 amendments.insert(v.begin(), v.end());
862 if (sle->isFieldPresent(sfMajorities))
865 using d = tp::duration;
867 auto const majorities = sle->getFieldArray(sfMajorities);
869 for (
auto const& m : majorities)
870 ret[m.getFieldH256(sfAmendment)] = tp(d(m.getFieldU32(sfCloseTime)));
881 if (seq > ledger.
seq())
883 JLOG(journal.
warn()) <<
"Can't get seq " << seq <<
" from " << ledger.
seq() <<
" future";
886 if (seq == ledger.
seq())
888 if (seq == (ledger.
seq() - 1))
891 if (
int diff = ledger.
seq() - seq; diff <= 256)
898 hashIndex->getFieldU32(sfLastLedgerSequence) == (ledger.
seq() - 1),
899 "xrpl::hashOfSeq : matching ledger sequence");
900 STVector256 vec = hashIndex->getFieldV256(sfHashes);
901 if (vec.
size() >= diff)
902 return vec[vec.
size() - diff];
903 JLOG(journal.
warn()) <<
"Ledger " << ledger.
seq() <<
" missing hash for " << seq <<
" (" << vec.
size()
904 <<
"," << diff <<
")";
908 JLOG(journal.
warn()) <<
"Ledger " << ledger.
seq() <<
":" << ledger.
header().
hash <<
" missing normal list";
912 if ((seq & 0xff) != 0)
914 JLOG(journal.
debug()) <<
"Can't get seq " << seq <<
" from " << ledger.
seq() <<
" past";
922 auto const lastSeq = hashIndex->getFieldU32(sfLastLedgerSequence);
923 XRPL_ASSERT(lastSeq >= seq,
"xrpl::hashOfSeq : minimum last ledger");
924 XRPL_ASSERT((lastSeq & 0xff) == 0,
"xrpl::hashOfSeq : valid last ledger");
925 auto const diff = (lastSeq - seq) >> 8;
926 STVector256 vec = hashIndex->getFieldV256(sfHashes);
927 if (vec.
size() > diff)
928 return vec[vec.
size() - diff - 1];
930 JLOG(journal.
warn()) <<
"Can't get seq " << seq <<
" from " << ledger.
seq() <<
" error";
945 XRPL_ASSERT(amount,
"xrpl::adjustOwnerCount : nonzero amount input");
950 sle->at(sfOwnerCount) = adjusted;
966 object->setFieldU64(node, *page);
979 rsh(hash.data(), hash.size());
1002 "xrpl::getPseudoAccountFields : unable to find account root "
1006 auto const& soTemplate = ar->getSOTemplate();
1009 for (
auto const& field : soTemplate)
1014 return pseudoFields;
1016 return pseudoFields;
1026 return sleAcct && sleAcct->getType() == ltACCOUNT_ROOT &&
1027 std::count_if(fields.begin(), fields.end(), [&sleAcct, &pseudoFieldFilter](
SField const* sf) ->
bool {
1028 return sleAcct->isFieldPresent(*sf) && (pseudoFieldFilter.empty() || pseudoFieldFilter.contains(sf));
1032Expected<std::shared_ptr<SLE>,
TER>
1039 fields.begin(), fields.end(), [&ownerField](
SField const* sf) ->
bool { return *sf == ownerField; }) == 1,
1040 "xrpl::createPseudoAccount : valid owner field");
1043 if (accountId == beast::zero)
1048 account->setAccountID(sfAccount, accountId);
1049 account->setFieldAmount(sfBalance,
STAmount{});
1059 account->setFieldU32(sfSequence, seqno);
1065 account->setFieldH256(ownerField, pseudoOwnerKey);
1110 if (toSle ==
nullptr)
1140 auto const& issuer = amount.getIssuer();
1141 if (from == to || to == issuer ||
isXRP(issuer))
1148 auto const& currency = issue.currency;
1149 auto const owed =
creditBalance(view, to, issuer, currency);
1150 if (owed <= beast::zero)
1152 auto const limit =
creditLimit(view, to, issuer, currency);
1153 if (-owed >= limit || amount > (limit + owed))
1159 amount.asset().value());
1169 bool hasDestinationTag)
1192 bool hasDestinationTag)
1196 return canWithdraw(view, from, to, toSle, amount, hasDestinationTag);
1202 auto const from = tx[sfAccount];
1203 auto const to = tx[~sfDestination].value_or(from);
1220 if (dstAcct == senderAcct)
1222 if (
auto const ter =
addEmptyHolding(view, senderAcct, priorBalance, amount.asset(), j);
1238 JLOG(j.
error()) <<
"LoanBrokerCoverWithdraw: negative balance of "
1239 "broker cover assets.";
1261 auto const& issuerId = issue.
getIssuer();
1262 auto const& currency = issue.
currency;
1266 auto const& srcId = issuerId;
1267 auto const& dstId = accountID;
1268 auto const high = srcId > dstId;
1269 auto const index =
keylet::line(srcId, dstId, currency);
1272 if (!sleDst || !sleSrc)
1277 if (view.
read(index))
1296 STAmount{Issue{currency, noAccount()}},
1297 STAmount{Issue{currency, dstId}},
1311 auto const& mptID = mptIssue.
getMptID();
1312 auto const mpt = view.
peek(keylet::mptIssuance(mptID));
1317 if (view.
peek(keylet::mptoken(mptID, accountID)))
1329 MPTID const& mptIssuanceID,
1335 auto const sleAcct = view.
peek(keylet::account(account));
1349 auto const mptokenKey = keylet::mptoken(mptIssuanceID, account);
1350 auto const sleMpt = view.
peek(mptokenKey);
1351 if (!sleMpt || (*sleMpt)[sfMPTAmount] != 0)
1354 if (!view.
dirRemove(keylet::ownerDir(account), (*sleMpt)[sfOwnerNode], sleMpt->key(),
false))
1372 std::uint32_t const uOwnerCount = sleAcct->getFieldU32(sfOwnerCount);
1376 if (priorBalance < reserveCreate)
1380 auto const mpt = view.
read(keylet::mptIssuance(mptIssuanceID));
1381 if (!mpt || mpt->getAccountID(sfIssuer) == account)
1384 UNREACHABLE(
"xrpl::authorizeMPToken : invalid issuance or issuers token");
1390 auto const mptokenKey = keylet::mptoken(mptIssuanceID, account);
1392 if (
auto ter =
dirLink(view, account, mptoken))
1395 (*mptoken)[sfAccount] = account;
1396 (*mptoken)[sfMPTokenIssuanceID] = mptIssuanceID;
1397 (*mptoken)[sfFlags] = 0;
1406 auto const sleMptIssuance = view.
read(keylet::mptIssuance(mptIssuanceID));
1407 if (!sleMptIssuance)
1413 if (account != (*sleMptIssuance)[sfIssuer])
1416 auto const sleMpt = view.
peek(keylet::mptoken(mptIssuanceID, *holderID));
1426 flagsOut &= ~lsfMPTAuthorized;
1432 if (flagsIn != flagsOut)
1433 sleMpt->setFieldU32(sfFlags, flagsOut);
1442 bool const bSrcHigh,
1448 bool const bNoRipple,
1459 JLOG(j.
trace()) <<
"trustCreate: " << to_string(uSrcAccountID) <<
", " << to_string(uDstAccountID) <<
", "
1462 auto const& uLowAccountID = !bSrcHigh ? uSrcAccountID : uDstAccountID;
1463 auto const& uHighAccountID = bSrcHigh ? uSrcAccountID : uDstAccountID;
1464 if (uLowAccountID == uHighAccountID)
1467 UNREACHABLE(
"xrpl::trustCreate : trust line to self");
1474 view.
insert(sleRippleState);
1488 bool const bSetDst = saLimit.
getIssuer() == uDstAccountID;
1489 bool const bSetHigh = bSrcHigh ^ bSetDst;
1491 XRPL_ASSERT(sleAccount,
"xrpl::trustCreate : non-null SLE");
1496 sleAccount->getAccountID(sfAccount) == (bSetHigh ? uHighAccountID : uLowAccountID),
1497 "xrpl::trustCreate : matching account ID");
1498 auto const slePeer = view.
peek(keylet::account(bSetHigh ? uLowAccountID : uHighAccountID));
1503 sleRippleState->setFieldU64(sfLowNode, *lowNode);
1504 sleRippleState->setFieldU64(sfHighNode, *highNode);
1506 sleRippleState->setFieldAmount(bSetHigh ? sfHighLimit : sfLowLimit, saLimit);
1507 sleRippleState->setFieldAmount(
1508 bSetHigh ? sfLowLimit : sfHighLimit,
1512 sleRippleState->setFieldU32(bSetHigh ? sfHighQualityIn : sfLowQualityIn, uQualityIn);
1515 sleRippleState->setFieldU32(bSetHigh ? sfHighQualityOut : sfLowQualityOut, uQualityOut);
1542 sleRippleState->setFieldU32(sfFlags, uFlags);
1546 sleRippleState->setFieldAmount(sfBalance, bSetHigh ? -saBalance : saBalance);
1548 view.
creditHook(uSrcAccountID, uDstAccountID, saBalance, saBalance.
zeroed());
1558 auto const sle = view.
read(keylet::account(accountID));
1562 auto const balance = sle->getFieldAmount(sfBalance);
1563 if (balance.xrp() != 0)
1572 bool const accountIsIssuer = accountID == issue.
account;
1573 auto const line = view.
peek(keylet::line(accountID, issue));
1576 if (!accountIsIssuer && line->at(sfBalance)->iou() != beast::zero)
1583 auto sleLowAccount = view.
peek(keylet::account(line->at(sfLowLimit)->getIssuer()));
1597 auto sleHighAccount = view.
peek(keylet::account(line->at(sfHighLimit)->getIssuer()));
1598 if (!sleHighAccount)
1608 return trustDelete(view, line, line->at(sfLowLimit)->getIssuer(), line->at(sfHighLimit)->getIssuer(), journal);
1617 bool const accountIsIssuer = accountID == mptIssue.
getIssuer();
1618 auto const& mptID = mptIssue.
getMptID();
1619 auto const mptoken = view.
peek(keylet::mptoken(mptID, accountID));
1626 if (mptoken->at(sfMPTAmount) != 0)
1648 std::uint64_t uLowNode = sleRippleState->getFieldU64(sfLowNode);
1649 std::uint64_t uHighNode = sleRippleState->getFieldU64(sfHighNode);
1651 JLOG(j.
trace()) <<
"trustDelete: Deleting ripple line: low";
1653 if (!view.
dirRemove(keylet::ownerDir(uLowAccountID), uLowNode, sleRippleState->key(),
false))
1658 JLOG(j.
trace()) <<
"trustDelete: Deleting ripple line: high";
1660 if (!view.
dirRemove(keylet::ownerDir(uHighAccountID), uHighNode, sleRippleState->key(),
false))
1665 JLOG(j.
trace()) <<
"trustDelete: Deleting ripple line: state";
1666 view.
erase(sleRippleState);
1676 auto offerIndex = sle->key();
1677 auto owner = sle->getAccountID(sfAccount);
1680 uint256 uDirectory = sle->getFieldH256(sfBookDirectory);
1682 if (!view.
dirRemove(keylet::ownerDir(owner), sle->getFieldU64(sfOwnerNode), offerIndex,
false))
1687 if (!view.
dirRemove(keylet::page(uDirectory), sle->getFieldU64(sfBookNode), offerIndex,
false))
1692 if (sle->isFieldPresent(sfAdditionalBooks))
1695 sle->isFlag(
lsfHybrid) && sle->isFieldPresent(sfDomainID),
1696 "xrpl::offerDelete : should be a hybrid domain offer");
1698 auto const& additionalBookDirs = sle->getFieldArray(sfAdditionalBooks);
1700 for (
auto const& bookDir : additionalBookDirs)
1702 auto const& dirIndex = bookDir.getFieldH256(sfBookDirectory);
1703 auto const& dirNode = bookDir.getFieldU64(sfBookNode);
1705 if (!view.
dirRemove(keylet::page(dirIndex), dirNode, offerIndex,
false))
1737 !bCheckIssuer || uSenderID == issuer || uReceiverID == issuer,
1738 "xrpl::rippleCreditIOU : matching issuer or don't care");
1742 XRPL_ASSERT(uSenderID != uReceiverID,
"xrpl::rippleCreditIOU : sender is not receiver");
1744 bool const bSenderHigh = uSenderID > uReceiverID;
1745 auto const index = keylet::line(uSenderID, uReceiverID, currency);
1747 XRPL_ASSERT(!
isXRP(uSenderID) && uSenderID !=
noAccount(),
"xrpl::rippleCreditIOU : sender is not XRP");
1748 XRPL_ASSERT(!
isXRP(uReceiverID) && uReceiverID !=
noAccount(),
"xrpl::rippleCreditIOU : receiver is not XRP");
1751 if (
auto const sleRippleState = view.
peek(index))
1753 STAmount saBalance = sleRippleState->getFieldAmount(sfBalance);
1758 view.
creditHook(uSenderID, uReceiverID, saAmount, saBalance);
1760 STAmount const saBefore = saBalance;
1762 saBalance -= saAmount;
1764 JLOG(j.
trace()) <<
"rippleCreditIOU: " << to_string(uSenderID) <<
" -> " << to_string(uReceiverID)
1768 std::uint32_t const uFlags(sleRippleState->getFieldU32(sfFlags));
1769 bool bDelete =
false;
1773 if (saBefore > beast::zero
1775 && saBalance <= beast::zero
1782 !sleRippleState->getFieldAmount(!bSenderHigh ? sfLowLimit : sfHighLimit)
1784 && !sleRippleState->getFieldU32(!bSenderHigh ? sfLowQualityIn : sfHighQualityIn)
1786 && !sleRippleState->getFieldU32(!bSenderHigh ? sfLowQualityOut : sfHighQualityOut))
1793 sleRippleState->setFieldU32(sfFlags, uFlags & (!bSenderHigh ? ~
lsfLowReserve : ~lsfHighReserve));
1796 bDelete = !saBalance
1805 sleRippleState->setFieldAmount(sfBalance, saBalance);
1811 view, sleRippleState, bSenderHigh ? uReceiverID : uSenderID, !bSenderHigh ? uReceiverID : uSenderID, j);
1814 view.
update(sleRippleState);
1818 STAmount const saReceiverLimit(
Issue{currency, uReceiverID});
1823 JLOG(j.
debug()) <<
"rippleCreditIOU: "
1825 << to_string(uSenderID) <<
" -> " << to_string(uReceiverID) <<
" : " << saAmount.
getFullText();
1827 auto const sleAccount = view.
peek(keylet::account(uReceiverID));
1864 auto const& issuer = saAmount.
getIssuer();
1866 XRPL_ASSERT(!
isXRP(uSenderID) && !
isXRP(uReceiverID),
"xrpl::rippleSendIOU : neither sender nor receiver is XRP");
1867 XRPL_ASSERT(uSenderID != uReceiverID,
"xrpl::rippleSendIOU : sender is not receiver");
1869 if (uSenderID == issuer || uReceiverID == issuer || issuer ==
noAccount())
1872 auto const ter =
rippleCreditIOU(view, uSenderID, uReceiverID, saAmount,
false, j);
1875 saActual = saAmount;
1883 saActual = (waiveFee == WaiveTransferFee::Yes) ? saAmount :
multiply(saAmount,
transferRate(view, issuer));
1885 JLOG(j.
debug()) <<
"rippleSendIOU> " << to_string(uSenderID) <<
" - > " << to_string(uReceiverID)
1891 terResult =
rippleCreditIOU(view, uSenderID, issuer, saActual,
true, j);
1911 XRPL_ASSERT(!
isXRP(senderID),
"xrpl::rippleSendMultiIOU : sender is not XRP");
1915 actual = takeFromSender;
1918 for (
auto const& r : receivers)
1920 auto const& receiverID = r.first;
1926 if (!amount || (senderID == receiverID))
1929 XRPL_ASSERT(!
isXRP(receiverID),
"xrpl::rippleSendMultiIOU : receiver is not XRP");
1931 if (senderID == issuer || receiverID == issuer || issuer ==
noAccount())
1934 if (
auto const ter =
rippleCreditIOU(view, senderID, receiverID, amount,
false, j))
1949 actual += actualSend;
1950 takeFromSender += actualSend;
1952 JLOG(j.
debug()) <<
"rippleSendMultiIOU> " << to_string(senderID) <<
" - > " << to_string(receiverID)
1953 <<
" : deliver=" << amount.getFullText() <<
" cost=" << actual.
getFullText();
1955 if (
TER const terResult =
rippleCreditIOU(view, issuer, receiverID, amount,
true, j))
1959 if (senderID != issuer && takeFromSender)
1961 if (
TER const terResult =
rippleCreditIOU(view, senderID, issuer, takeFromSender,
true, j))
1989 "xrpl::accountSendIOU : minimum amount and not MPT");
1996 if (!saAmount || (uSenderID == uReceiverID))
2003 JLOG(j.
trace()) <<
"accountSendIOU: " << to_string(uSenderID) <<
" -> " << to_string(uReceiverID) <<
" : "
2006 return rippleSendIOU(view, uSenderID, uReceiverID, saAmount, saActual, j, waiveFee);
2019 if (
auto stream = j.
trace())
2025 sender_bal = sender->getFieldAmount(sfBalance).getFullText();
2028 receiver_bal = receiver->getFieldAmount(sfBalance).getFullText();
2030 stream <<
"accountSendIOU> " << to_string(uSenderID) <<
" (" << sender_bal <<
") -> " << to_string(uReceiverID)
2031 <<
" (" << receiver_bal <<
") : " << saAmount.
getFullText();
2036 if (sender->getFieldAmount(sfBalance) < saAmount)
2046 auto const sndBal = sender->getFieldAmount(sfBalance);
2050 sender->setFieldAmount(sfBalance, sndBal - saAmount);
2058 auto const rcvBal = receiver->getFieldAmount(sfBalance);
2059 receiver->setFieldAmount(sfBalance, rcvBal + saAmount);
2065 if (
auto stream = j.
trace())
2071 sender_bal = sender->getFieldAmount(sfBalance).getFullText();
2074 receiver_bal = receiver->getFieldAmount(sfBalance).getFullText();
2076 stream <<
"accountSendIOU< " << to_string(uSenderID) <<
" (" << sender_bal <<
") -> " << to_string(uReceiverID)
2077 <<
" (" << receiver_bal <<
") : " << saAmount.
getFullText();
2092 XRPL_ASSERT_PARTS(receivers.
size() > 1,
"xrpl::accountSendMultiIOU",
"multiple recipients provided");
2097 JLOG(j.
trace()) <<
"accountSendMultiIOU: " << to_string(senderID) <<
" sending " << receivers.
size() <<
" IOUs";
2110 if (
auto stream = j.
trace())
2115 sender_bal = sender->getFieldAmount(sfBalance).getFullText();
2117 stream <<
"accountSendMultiIOU> " << to_string(senderID) <<
" (" << sender_bal <<
") -> " << receivers.
size()
2123 for (
auto const& r : receivers)
2125 auto const& receiverID = r.first;
2128 if (amount < beast::zero)
2136 if (!amount || (senderID == receiverID))
2141 if (
auto stream = j.
trace())
2146 receiver_bal = receiver->getFieldAmount(sfBalance).getFullText();
2148 stream <<
"accountSendMultiIOU> " << to_string(senderID) <<
" -> " << to_string(receiverID) <<
" ("
2149 << receiver_bal <<
") : " << amount.getFullText();
2155 auto const rcvBal = receiver->getFieldAmount(sfBalance);
2156 receiver->setFieldAmount(sfBalance, rcvBal + amount);
2162 takeFromSender += amount;
2165 if (
auto stream = j.
trace())
2170 receiver_bal = receiver->getFieldAmount(sfBalance).getFullText();
2172 stream <<
"accountSendMultiIOU< " << to_string(senderID) <<
" -> " << to_string(receiverID) <<
" ("
2173 << receiver_bal <<
") : " << amount.getFullText();
2179 if (sender->getFieldAmount(sfBalance) < takeFromSender)
2185 auto const sndBal = sender->getFieldAmount(sfBalance);
2189 sender->setFieldAmount(sfBalance, sndBal - takeFromSender);
2194 if (
auto stream = j.
trace())
2200 sender_bal = sender->getFieldAmount(sfBalance).getFullText();
2202 stream <<
"accountSendMultiIOU< " << to_string(senderID) <<
" (" << sender_bal <<
") -> " << receivers.
size()
2218 auto const& issuer = saAmount.
getIssuer();
2219 auto sleIssuance = view.
peek(mptID);
2222 if (uSenderID == issuer)
2224 (*sleIssuance)[sfOutstandingAmount] += saAmount.
mpt().
value();
2225 view.
update(sleIssuance);
2229 auto const mptokenID = keylet::mptoken(mptID.key, uSenderID);
2230 if (
auto sle = view.
peek(mptokenID))
2232 auto const amt = sle->getFieldU64(sfMPTAmount);
2233 auto const pay = saAmount.
mpt().
value();
2236 (*sle)[sfMPTAmount] = amt - pay;
2243 if (uReceiverID == issuer)
2245 auto const outstanding = sleIssuance->getFieldU64(sfOutstandingAmount);
2246 auto const redeem = saAmount.
mpt().
value();
2247 if (outstanding >= redeem)
2249 sleIssuance->setFieldU64(sfOutstandingAmount, outstanding - redeem);
2250 view.
update(sleIssuance);
2257 auto const mptokenID = keylet::mptoken(mptID.key, uReceiverID);
2258 if (
auto sle = view.
peek(mptokenID))
2260 (*sle)[sfMPTAmount] += saAmount.
mpt().
value();
2280 XRPL_ASSERT(uSenderID != uReceiverID,
"xrpl::rippleSendMPT : sender is not receiver");
2283 auto const& issuer = saAmount.
getIssuer();
2289 if (uSenderID == issuer || uReceiverID == issuer)
2293 if (uSenderID == issuer)
2295 auto const sendAmount = saAmount.
mpt().
value();
2296 auto const maximumAmount = sle->at(~sfMaximumAmount).value_or(
maxMPTokenAmount);
2297 if (sendAmount > maximumAmount || sle->getFieldU64(sfOutstandingAmount) > maximumAmount - sendAmount)
2302 auto const ter =
rippleCreditMPT(view, uSenderID, uReceiverID, saAmount, j);
2305 saActual = saAmount;
2310 saActual = (waiveFee == WaiveTransferFee::Yes)
2314 JLOG(j.
debug()) <<
"rippleSendMPT> " << to_string(uSenderID) <<
" - > " << to_string(uReceiverID)
2335 auto const& issuer = mptIssue.
getIssuer();
2337 auto const sle = view.
read(keylet::mptIssuance(mptIssue.
getMptID()));
2343 actual = takeFromSender;
2345 for (
auto const& r : receivers)
2347 auto const& receiverID = r.first;
2348 STAmount amount{mptIssue, r.second};
2350 if (amount < beast::zero)
2358 if (!amount || (senderID == receiverID))
2361 if (senderID == issuer || receiverID == issuer)
2365 if (senderID == issuer)
2368 takeFromSender == beast::zero,
2369 "rippler::rippleSendMultiMPT",
2370 "sender == issuer, takeFromSender == zero");
2371 auto const sendAmount = amount.mpt().value();
2372 auto const maximumAmount = sle->at(~sfMaximumAmount).value_or(
maxMPTokenAmount);
2373 if (sendAmount > maximumAmount || sle->getFieldU64(sfOutstandingAmount) > maximumAmount - sendAmount)
2378 if (
auto const ter =
rippleCreditMPT(view, senderID, receiverID, amount, j))
2388 STAmount actualSend = (waiveFee == WaiveTransferFee::Yes)
2391 actual += actualSend;
2392 takeFromSender += actualSend;
2394 JLOG(j.
debug()) <<
"rippleSendMultiMPT> " << to_string(senderID) <<
" - > " << to_string(receiverID)
2395 <<
" : deliver=" << amount.getFullText() <<
" cost=" << actualSend.
getFullText();
2397 if (
auto const terResult =
rippleCreditMPT(view, issuer, receiverID, amount, j))
2400 if (senderID != issuer && takeFromSender)
2402 if (
TER const terResult =
rippleCreditMPT(view, senderID, issuer, takeFromSender, j))
2418 XRPL_ASSERT(saAmount >= beast::zero && saAmount.
holds<
MPTIssue>(),
"xrpl::accountSendMPT : minimum amount and MPT");
2423 if (!saAmount || (uSenderID == uReceiverID))
2428 return rippleSendMPT(view, uSenderID, uReceiverID, saAmount, saActual, j, waiveFee);
2457 return accountSendIOU(view, uSenderID, uReceiverID, saAmount, j, waiveFee);
2459 return accountSendMPT(view, uSenderID, uReceiverID, saAmount, j, waiveFee);
2473 XRPL_ASSERT_PARTS(receivers.
size() > 1,
"xrpl::accountSendMulti",
"multiple recipients provided");
2498 auto sle = view.
peek(keylet::account(sender));
2503 if (before > beast::zero
2505 &&
after <= beast::zero
2512 !state->getFieldAmount(!bSenderHigh ? sfLowLimit : sfHighLimit)
2514 && !state->getFieldU32(!bSenderHigh ? sfLowQualityIn : sfHighQualityIn)
2516 && !state->getFieldU32(!bSenderHigh ? sfLowQualityOut : sfHighQualityOut))
2524 state->setFieldU32(sfFlags, flags & (!bSenderHigh ? ~
lsfLowReserve : ~lsfHighReserve));
2537 XRPL_ASSERT(!
isXRP(account) && !
isXRP(issue.
account),
"xrpl::issueIOU : neither account nor issuer is XRP");
2540 XRPL_ASSERT(issue == amount.issue(),
"xrpl::issueIOU : matching issue");
2543 XRPL_ASSERT(issue.
account != account,
"xrpl::issueIOU : not issuer account");
2545 JLOG(j.
trace()) <<
"issueIOU: " << to_string(account) <<
": " << amount.getFullText();
2547 bool bSenderHigh = issue.
account > account;
2549 auto const index = keylet::line(issue.
account, account, issue.
currency);
2551 if (
auto state = view.
peek(index))
2553 STAmount final_balance = state->getFieldAmount(sfBalance);
2558 STAmount const start_balance = final_balance;
2560 final_balance -= amount;
2562 auto const must_delete =
2573 state->setFieldAmount(sfBalance, final_balance);
2576 view, state, bSenderHigh ? account : issue.
account, bSenderHigh ? issue.
account : account, j);
2591 auto const receiverAccount = view.
peek(keylet::account(account));
2592 if (!receiverAccount)
2618 XRPL_ASSERT(!
isXRP(account) && !
isXRP(issue.
account),
"xrpl::redeemIOU : neither account nor issuer is XRP");
2621 XRPL_ASSERT(issue == amount.issue(),
"xrpl::redeemIOU : matching issue");
2624 XRPL_ASSERT(issue.
account != account,
"xrpl::redeemIOU : not issuer account");
2626 JLOG(j.
trace()) <<
"redeemIOU: " << to_string(account) <<
": " << amount.getFullText();
2628 bool bSenderHigh = account > issue.
account;
2632 STAmount final_balance = state->getFieldAmount(sfBalance);
2637 STAmount const start_balance = final_balance;
2639 final_balance -= amount;
2641 auto const must_delete =
updateTrustLine(view, state, bSenderHigh, account, start_balance, final_balance, j);
2651 state->setFieldAmount(sfBalance, final_balance);
2656 view, state, bSenderHigh ? issue.
account : account, bSenderHigh ? account : issue.
account, j);
2667 JLOG(j.
fatal()) <<
"redeemIOU: " << to_string(account) <<
" attempts to redeem " << amount.getFullText()
2668 <<
" but no trust line exists!";
2677 XRPL_ASSERT(from != beast::zero,
"xrpl::transferXRP : nonzero from account");
2678 XRPL_ASSERT(to != beast::zero,
"xrpl::transferXRP : nonzero to account");
2679 XRPL_ASSERT(from != to,
"xrpl::transferXRP : sender is not receiver");
2680 XRPL_ASSERT(amount.native(),
"xrpl::transferXRP : amount is XRP");
2684 if (!sender || !receiver)
2687 JLOG(j.
trace()) <<
"transferXRP: " << to_string(from) <<
" -> " << to_string(to) <<
") : " << amount.getFullText();
2689 if (sender->getFieldAmount(sfBalance) < amount)
2700 sender->setFieldAmount(sfBalance, sender->getFieldAmount(sfBalance) - amount);
2703 receiver->setFieldAmount(sfBalance, receiver->getFieldAmount(sfBalance) + amount);
2717 if (!trustLine && authType == AuthType::StrongAuth)
2722 if (
auto const issuerAccount = view.
read(keylet::account(issue.
account));
2737 auto const mptID = keylet::mptIssuance(mptIssue.
getMptID());
2738 auto const sleIssuance = view.
read(mptID);
2742 auto const mptIssuer = sleIssuance->getAccountID(sfIssuer);
2745 if (mptIssuer == account)
2748 bool const featureSAVEnabled = view.
rules().
enabled(featureSingleAssetVault);
2750 if (featureSAVEnabled)
2756 auto const sleIssuer = view.
read(keylet::account(mptIssuer));
2760 if (sleIssuer->isFieldPresent(sfVaultID))
2762 auto const sleVault = view.
read(keylet::vault(sleIssuer->getFieldH256(sfVaultID)));
2766 auto const asset = sleVault->at(sfAsset);
2770 return requireAuth(view, issue, account, authType);
2772 return requireAuth(view, issue, account, authType, depth + 1);
2780 auto const mptokenID = keylet::mptoken(mptID.key, account);
2781 auto const sleToken = view.
read(mptokenID);
2784 if (!sleToken && (authType == AuthType::StrongAuth || authType == AuthType::Legacy))
2789 auto const maybeDomainID = sleIssuance->at(~sfDomainID);
2794 "xrpl::requireAuth : issuance requires authorization");
2796 if (
auto const ter = credentials::validDomain(view, *maybeDomainID, account);
isTesSuccess(ter))
2804 if (featureSAVEnabled)
2821 MPTID const& mptIssuanceID,
2826 auto const sleIssuance = view.
read(keylet::mptIssuance(mptIssuanceID));
2830 XRPL_ASSERT(sleIssuance->isFlag(
lsfMPTRequireAuth),
"xrpl::enforceMPTokenAuthorization : authorization required");
2832 if (account == sleIssuance->at(sfIssuer))
2835 auto const keylet = keylet::mptoken(mptIssuanceID, account);
2836 auto const sleToken = view.
read(keylet);
2837 auto const maybeDomainID = sleIssuance->at(~sfDomainID);
2839 bool const authorizedByDomain = [&]() ->
bool {
2841 if (!maybeDomainID.has_value())
2852 if (!authorizedByDomain && sleToken ==
nullptr)
2863 else if (!authorizedByDomain && maybeDomainID.has_value())
2870 else if (!authorizedByDomain)
2875 sleToken !=
nullptr && !maybeDomainID.has_value(),
"xrpl::enforceMPTokenAuthorization : found MPToken");
2881 else if (authorizedByDomain && sleToken !=
nullptr)
2885 XRPL_ASSERT(maybeDomainID.has_value(),
"xrpl::enforceMPTokenAuthorization : found MPToken for domain");
2888 else if (authorizedByDomain)
2893 maybeDomainID.has_value() && sleToken ==
nullptr,
2894 "xrpl::enforceMPTokenAuthorization : new MPToken for domain");
2908 UNREACHABLE(
"xrpl::enforceMPTokenAuthorization : condition list is incomplete");
2916 auto const mptID = keylet::mptIssuance(mptIssue.
getMptID());
2917 auto const sleIssuance = view.
read(mptID);
2923 if (from != (*sleIssuance)[sfIssuer] && to != (*sleIssuance)[sfIssuer])
2935 auto const& issuerId = issue.
getIssuer();
2936 if (issuerId == from || issuerId == to)
2938 auto const sleIssuer = view.
read(keylet::account(issuerId));
2939 if (sleIssuer ==
nullptr)
2942 auto const isRippleDisabled = [&](
AccountID account) ->
bool {
2945 auto const line = view.
read(keylet::line(account, issue));
2948 bool const issuerHigh = issuerId > account;
2955 if (isRippleDisabled(from) && isRippleDisabled(to))
2964 Keylet const& ownerDirKeylet,
2971 unsigned int uDirEntry{0};
2972 uint256 dirEntry{beast::zero};
2975 if (view.
exists(ownerDirKeylet) &&
dirFirst(view, ownerDirKeylet.
key, sleDirNode, uDirEntry, dirEntry))
2979 if (maxNodesToDelete && ++deleted > *maxNodesToDelete)
2983 auto sleItem = view.
peek(keylet::child(dirEntry));
2988 JLOG(j.
fatal()) <<
"DeleteAccount: Directory node in ledger " << view.
seq()
2989 <<
" has index to object that is missing: " << to_string(dirEntry);
2994 LedgerEntryType const nodeType{safe_cast<LedgerEntryType>(sleItem->getFieldU16(sfLedgerEntryType))};
2998 auto const [ter, skipEntry] = deleter(nodeType, dirEntry, sleItem);
3018 XRPL_ASSERT(uDirEntry >= 1,
"xrpl::cleanupOnAccountDelete : minimum dir entries");
3022 JLOG(j.
error()) <<
"DeleteAccount iterator re-validation failed.";
3026 if (skipEntry == SkipEntry::No)
3029 }
while (
dirNext(view, ownerDirKeylet.
key, sleDirNode, uDirEntry, dirEntry));
3042 if (!sleState || sleState->getType() != ltRIPPLE_STATE)
3046 sleState->getFieldAmount(sfLowLimit).getIssuer(), sleState->getFieldAmount(sfHighLimit).getIssuer());
3047 auto sleLow = view.
peek(keylet::account(low));
3048 auto sleHigh = view.
peek(keylet::account(high));
3049 if (!sleLow || !sleHigh)
3052 bool const ammLow = sleLow->isFieldPresent(sfAMMID);
3053 bool const ammHigh = sleHigh->isFieldPresent(sfAMMID);
3056 if (ammLow && ammHigh)
3060 if (!ammLow && !ammHigh)
3064 if (ammAccountID && (low != *ammAccountID && high != *ammAccountID))
3069 JLOG(j.
error()) <<
"deleteAMMTrustLine: failed to delete the trustline.";
3074 if (!(sleState->getFlags() & uFlags))
3095 return rippleCreditIOU(view, uSenderID, uReceiverID, saAmount, bCheckIssuer, j);
3099 XRPL_ASSERT(!bCheckIssuer,
"xrpl::rippleCredit : not checking issuer");
3112 XRPL_ASSERT(!assets.
negative(),
"xrpl::assetsToSharesDeposit : non-negative assets");
3113 XRPL_ASSERT(assets.
asset() == vault->at(sfAsset),
"xrpl::assetsToSharesDeposit : assets and vault match");
3114 if (assets.
negative() || assets.
asset() != vault->at(sfAsset))
3117 Number const assetTotal = vault->at(sfAssetsTotal);
3118 STAmount shares{vault->at(sfShareMPTID)};
3119 if (assetTotal == 0)
3122 Number const shareTotal = issuance->at(sfOutstandingAmount);
3123 shares = ((shareTotal * assets) / assetTotal).truncate();
3133 XRPL_ASSERT(!shares.
negative(),
"xrpl::sharesToAssetsDeposit : non-negative shares");
3134 XRPL_ASSERT(shares.
asset() == vault->at(sfShareMPTID),
"xrpl::sharesToAssetsDeposit : shares and vault match");
3135 if (shares.
negative() || shares.
asset() != vault->at(sfShareMPTID))
3138 Number const assetTotal = vault->at(sfAssetsTotal);
3139 STAmount assets{vault->at(sfAsset)};
3140 if (assetTotal == 0)
3143 Number const shareTotal = issuance->at(sfOutstandingAmount);
3144 assets = (assetTotal * shares) / shareTotal;
3155 XRPL_ASSERT(!assets.
negative(),
"xrpl::assetsToSharesDeposit : non-negative assets");
3156 XRPL_ASSERT(assets.
asset() == vault->at(sfAsset),
"xrpl::assetsToSharesWithdraw : assets and vault match");
3157 if (assets.
negative() || assets.
asset() != vault->at(sfAsset))
3160 Number assetTotal = vault->at(sfAssetsTotal);
3161 assetTotal -= vault->at(sfLossUnrealized);
3162 STAmount shares{vault->at(sfShareMPTID)};
3163 if (assetTotal == 0)
3165 Number const shareTotal = issuance->at(sfOutstandingAmount);
3166 Number result = (shareTotal * assets) / assetTotal;
3167 if (truncate == TruncateShares::yes)
3179 XRPL_ASSERT(!shares.
negative(),
"xrpl::sharesToAssetsDeposit : non-negative shares");
3180 XRPL_ASSERT(shares.
asset() == vault->at(sfShareMPTID),
"xrpl::sharesToAssetsWithdraw : shares and vault match");
3181 if (shares.
negative() || shares.
asset() != vault->at(sfShareMPTID))
3184 Number assetTotal = vault->at(sfAssetsTotal);
3185 assetTotal -= vault->at(sfLossUnrealized);
3186 STAmount assets{vault->at(sfAsset)};
3187 if (assetTotal == 0)
3189 Number const shareTotal = issuance->at(sfOutstandingAmount);
3190 assets = (assetTotal * shares) / shareTotal;
3197 auto const mptIssue = amount.get<
MPTIssue>();
3198 auto const mptID = keylet::mptIssuance(mptIssue.getMptID());
3199 auto sleIssuance = view.
peek(mptID);
3202 JLOG(j.
error()) <<
"rippleLockEscrowMPT: MPT issuance not found for " << mptIssue.getMptID();
3206 if (amount.getIssuer() == sender)
3208 JLOG(j.
error()) <<
"rippleLockEscrowMPT: sender is the issuer, cannot lock MPTs.";
3215 auto const mptokenID = keylet::mptoken(mptID.key, sender);
3216 auto sle = view.
peek(mptokenID);
3219 JLOG(j.
error()) <<
"rippleLockEscrowMPT: MPToken not found for " << sender;
3223 auto const amt = sle->getFieldU64(sfMPTAmount);
3224 auto const pay = amount.mpt().value();
3229 JLOG(j.
error()) <<
"rippleLockEscrowMPT: insufficient MPTAmount for " << to_string(sender) <<
": " << amt
3234 (*sle)[sfMPTAmount] = amt - pay;
3237 uint64_t
const locked = (*sle)[~sfLockedAmount].value_or(0);
3241 JLOG(j.
error()) <<
"rippleLockEscrowMPT: overflow on locked amount for " << to_string(sender) <<
": "
3242 << locked <<
" + " << pay;
3246 if (sle->isFieldPresent(sfLockedAmount))
3247 (*sle)[sfLockedAmount] += pay;
3249 sle->setFieldU64(sfLockedAmount, pay);
3257 uint64_t
const issuanceEscrowed = (*sleIssuance)[~sfLockedAmount].value_or(0);
3258 auto const pay = amount.mpt().value();
3263 JLOG(j.
error()) <<
"rippleLockEscrowMPT: overflow on issuance "
3264 "locked amount for "
3265 << mptIssue.getMptID() <<
": " << issuanceEscrowed <<
" + " << pay;
3269 if (sleIssuance->isFieldPresent(sfLockedAmount))
3270 (*sleIssuance)[sfLockedAmount] += pay;
3272 sleIssuance->setFieldU64(sfLockedAmount, pay);
3274 view.
update(sleIssuance);
3289 XRPL_ASSERT(netAmount == grossAmount,
"xrpl::rippleUnlockEscrowMPT : netAmount == grossAmount");
3291 auto const& issuer = netAmount.
getIssuer();
3293 auto const mptID = keylet::mptIssuance(mptIssue.getMptID());
3294 auto sleIssuance = view.
peek(mptID);
3297 JLOG(j.
error()) <<
"rippleUnlockEscrowMPT: MPT issuance not found for " << mptIssue.getMptID();
3303 if (!sleIssuance->isFieldPresent(sfLockedAmount))
3305 JLOG(j.
error()) <<
"rippleUnlockEscrowMPT: no locked amount in issuance for " << mptIssue.getMptID();
3309 auto const locked = sleIssuance->getFieldU64(sfLockedAmount);
3310 auto const redeem = grossAmount.
mpt().
value();
3315 JLOG(j.
error()) <<
"rippleUnlockEscrowMPT: insufficient locked amount for " << mptIssue.getMptID() <<
": "
3316 << locked <<
" < " << redeem;
3320 auto const newLocked = locked - redeem;
3322 sleIssuance->makeFieldAbsent(sfLockedAmount);
3324 sleIssuance->setFieldU64(sfLockedAmount, newLocked);
3325 view.
update(sleIssuance);
3328 if (issuer != receiver)
3331 auto const mptokenID = keylet::mptoken(mptID.key, receiver);
3332 auto sle = view.
peek(mptokenID);
3335 JLOG(j.
error()) <<
"rippleUnlockEscrowMPT: MPToken not found for " << receiver;
3339 auto current = sle->getFieldU64(sfMPTAmount);
3340 auto delta = netAmount.
mpt().
value();
3345 JLOG(j.
error()) <<
"rippleUnlockEscrowMPT: overflow on MPTAmount for " << to_string(receiver) <<
": "
3350 (*sle)[sfMPTAmount] += delta;
3356 auto const outstanding = sleIssuance->getFieldU64(sfOutstandingAmount);
3357 auto const redeem = netAmount.
mpt().
value();
3362 JLOG(j.
error()) <<
"rippleUnlockEscrowMPT: insufficient outstanding amount for " << mptIssue.getMptID()
3363 <<
": " << outstanding <<
" < " << redeem;
3367 sleIssuance->setFieldU64(sfOutstandingAmount, outstanding - redeem);
3368 view.
update(sleIssuance);
3371 if (issuer == sender)
3373 JLOG(j.
error()) <<
"rippleUnlockEscrowMPT: sender is the issuer, "
3374 "cannot unlock MPTs.";
3380 auto const mptokenID = keylet::mptoken(mptID.key, sender);
3381 auto sle = view.
peek(mptokenID);
3384 JLOG(j.
error()) <<
"rippleUnlockEscrowMPT: MPToken not found for " << sender;
3388 if (!sle->isFieldPresent(sfLockedAmount))
3390 JLOG(j.
error()) <<
"rippleUnlockEscrowMPT: no locked amount in MPToken for " << to_string(sender);
3394 auto const locked = sle->getFieldU64(sfLockedAmount);
3395 auto const delta = grossAmount.
mpt().
value();
3400 JLOG(j.
error()) <<
"rippleUnlockEscrowMPT: insufficient locked amount for " << to_string(sender) <<
": "
3401 << locked <<
" < " << delta;
3405 auto const newLocked = locked - delta;
3407 sle->makeFieldAbsent(sfLockedAmount);
3409 sle->setFieldU64(sfLockedAmount, newLocked);
3420 auto const outstanding = sleIssuance->getFieldU64(sfOutstandingAmount);
3424 JLOG(j.
error()) <<
"rippleUnlockEscrowMPT: insufficient outstanding amount for " << mptIssue.getMptID()
3425 <<
": " << outstanding <<
" < " << diff;
3429 sleIssuance->setFieldU64(sfOutstandingAmount, outstanding - diff);
3430 view.
update(sleIssuance);
Provide a light-weight way to check active() before string formatting.
A generic endpoint for log messages.
static Sink & getNullSink()
Returns a Sink which does nothing.
Stream trace() const
Severity stream access functions.
Writeable view to a ledger, for applying a transaction.
virtual void update(std::shared_ptr< SLE > const &sle)=0
Indicate changes to a peeked SLE.
bool dirRemove(Keylet const &directory, std::uint64_t page, uint256 const &key, bool keepRoot)
Remove an entry from a directory.
virtual void erase(std::shared_ptr< SLE > const &sle)=0
Remove a peeked SLE.
virtual void insert(std::shared_ptr< SLE > const &sle)=0
Insert a new state SLE.
virtual void creditHook(AccountID const &from, AccountID const &to, STAmount const &amount, STAmount const &preCreditBalance)
virtual void adjustOwnerCountHook(AccountID const &account, std::uint32_t cur, std::uint32_t next)
std::optional< std::uint64_t > dirInsert(Keylet const &directory, uint256 const &key, std::function< void(std::shared_ptr< SLE > const &)> const &describe)
Insert an entry to a directory.
virtual std::shared_ptr< SLE > peek(Keylet const &k)=0
Prepare to modify the SLE associated with key.
constexpr value_type const & value() const
A currency issued by an account.
AccountID const & getIssuer() const
constexpr value_type value() const
Returns the underlying value.
constexpr MPTID const & getMptID() const
AccountID const & getIssuer() const
std::chrono::time_point< NetClock > time_point
std::chrono::duration< rep, period > duration
Number is a floating point type that can represent a wide range of values.
Number truncate() const noexcept
virtual Rules const & rules() const =0
Returns the tx processing rules.
NetClock::time_point parentCloseTime() const
Returns the close time of the previous ledger.
virtual Fees const & fees() const =0
Returns the fees for the base ledger.
virtual bool exists(Keylet const &k) const =0
Determine if a state item exists.
virtual LedgerHeader const & header() const =0
Returns information about the ledger.
virtual STAmount balanceHook(AccountID const &account, AccountID const &issuer, STAmount const &amount) const
virtual bool open() const =0
Returns true if this reflects an open ledger.
LedgerIndex seq() const
Returns the sequence number of the base ledger.
virtual std::uint32_t ownerCountHook(AccountID const &account, std::uint32_t count) const
virtual std::shared_ptr< SLE const > read(Keylet const &k) const =0
Return the state item associated with a key.
bool enabled(uint256 const &feature) const
Returns true if a feature is enabled.
constexpr bool holds() const noexcept
constexpr TIss const & get() const
std::string getFullText() const override
static constexpr std::uint64_t cMaxValue
void setIssuer(AccountID const &uIssuer)
std::uint64_t mantissa() const noexcept
bool negative() const noexcept
STAmount zeroed() const
Returns a zero value with the same issuer and currency.
static int const cMaxOffset
Currency const & getCurrency() const
bool native() const noexcept
Asset const & asset() const
int exponent() const noexcept
AccountID const & getIssuer() const
std::shared_ptr< STLedgerEntry > const & ref
std::shared_ptr< STLedgerEntry const > const_pointer
bool isFieldPresent(SField const &field) const
T emplace_back(T... args)
bool internalDirFirst(V &view, uint256 const &root, std::shared_ptr< N > &page, unsigned int &index, uint256 &entry)
bool internalDirNext(V &view, uint256 const &root, std::shared_ptr< N > &page, unsigned int &index, uint256 &entry)
Keylet const & skip() noexcept
The index of the "short" skip list.
Keylet depositPreauth(AccountID const &owner, AccountID const &preauthorized) noexcept
A DepositPreauth.
Keylet const & amendments() noexcept
The index of the amendment table.
Keylet ownerDir(AccountID const &id) noexcept
The root page of an account's directory.
Keylet mptIssuance(std::uint32_t seq, AccountID const &issuer) noexcept
Keylet amm(Asset const &issue1, Asset const &issue2) noexcept
AMM entry.
Keylet child(uint256 const &key) noexcept
Any item that can be in an owner dir.
Keylet vault(AccountID const &owner, std::uint32_t seq) noexcept
Keylet line(AccountID const &id0, AccountID const &id1, Currency const ¤cy) noexcept
The index of a trust line for a given currency.
Keylet mptoken(MPTID const &issuanceID, AccountID const &holder) noexcept
Keylet account(AccountID const &id) noexcept
AccountID root.
Keylet page(uint256 const &root, std::uint64_t index=0) noexcept
A page in a directory.
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
TER trustCreate(ApplyView &view, bool const bSrcHigh, AccountID const &uSrcAccountID, AccountID const &uDstAccountID, uint256 const &uIndex, SLE::ref sleAccount, bool const bAuth, bool const bNoRipple, bool const bFreeze, bool bDeepFreeze, STAmount const &saBalance, STAmount const &saLimit, std::uint32_t uSrcQualityIn, std::uint32_t uSrcQualityOut, beast::Journal j)
Create a trust line.
std::optional< STAmount > sharesToAssetsDeposit(std::shared_ptr< SLE const > const &vault, std::shared_ptr< SLE const > const &issuance, STAmount const &shares)
std::vector< SField const * > const & getPseudoAccountFields()
XRPAmount xrpLiquid(ReadView const &view, AccountID const &id, std::int32_t ownerCountAdj, beast::Journal j)
TER addEmptyHolding(ApplyView &view, AccountID const &accountID, XRPAmount priorBalance, Issue const &issue, beast::Journal journal)
Any transactors that call addEmptyHolding() in doApply must call canAddHolding() in preflight with th...
void LogicError(std::string const &how) noexcept
Called when faulty logic causes a broken invariant.
FreezeHandling
Controls the treatment of frozen account balances.
bool dirFirst(ApplyView &view, uint256 const &root, std::shared_ptr< SLE > &page, unsigned int &index, uint256 &entry)
AccountID pseudoAccountAddress(ReadView const &view, uint256 const &pseudoOwnerKey)
bool dirIsEmpty(ReadView const &view, Keylet const &k)
Returns true if the directory is empty.
SpendableHandling
Controls whether to include the account's full spendable balance.
bool isXRP(AccountID const &c)
TER canAddHolding(ReadView const &view, Asset const &asset)
std::uint8_t constexpr maxAssetCheckDepth
Maximum recursion depth for vault shares being put as an asset inside another vault; counted from 0.
std::map< uint256, NetClock::time_point > majorityAmendments_t
std::set< uint256 > getEnabledAmendments(ReadView const &view)
TER issueIOU(ApplyView &view, AccountID const &account, STAmount const &amount, Issue const &issue, beast::Journal j)
sha512_half_hasher::result_type sha512Half(Args const &... args)
Returns the SHA512-Half of a series of objects.
TER verifyValidDomain(ApplyView &view, AccountID const &account, uint256 domainID, beast::Journal j)
TER removeEmptyHolding(ApplyView &view, AccountID const &accountID, Issue const &issue, beast::Journal journal)
bool isVaultPseudoAccountFrozen(ReadView const &view, AccountID const &account, MPTIssue const &mptShare, int depth)
std::string to_string(base_uint< Bits, Tag > const &a)
TER rippleUnlockEscrowMPT(ApplyView &view, AccountID const &uGrantorID, AccountID const &uGranteeID, STAmount const &netAmount, STAmount const &grossAmount, beast::Journal j)
TER doWithdraw(ApplyView &view, STTx const &tx, AccountID const &senderAcct, AccountID const &dstAcct, AccountID const &sourceAcct, XRPAmount priorBalance, STAmount const &amount, beast::Journal j)
static TER accountSendMultiIOU(ApplyView &view, AccountID const &senderID, Issue const &issue, MultiplePaymentDestinations const &receivers, beast::Journal j, WaiveTransferFee waiveFee)
bool hasExpired(ReadView const &view, std::optional< std::uint32_t > const &exp)
Determines whether the given expiration time has passed.
static TER rippleSendMPT(ApplyView &view, AccountID const &uSenderID, AccountID const &uReceiverID, STAmount const &saAmount, STAmount &saActual, beast::Journal j, WaiveTransferFee waiveFee)
@ expired
List is expired, but has the largest non-pending sequence seen so far.
std::uint64_t constexpr maxMPTokenAmount
The maximum amount of MPTokenIssuance.
void forEachItem(ReadView const &view, Keylet const &root, std::function< void(std::shared_ptr< SLE const > const &)> const &f)
Iterate all items in the given directory.
bool isAnyFrozen(ReadView const &view, std::initializer_list< AccountID > const &accounts, MPTIssue const &mptIssue, int depth=0)
STAmount accountHolds(ReadView const &view, AccountID const &account, Currency const ¤cy, AccountID const &issuer, FreezeHandling zeroIfFrozen, beast::Journal j, SpendableHandling includeFullBalance=shSIMPLE_BALANCE)
Number root(Number f, unsigned d)
static TER accountSendMPT(ApplyView &view, AccountID const &uSenderID, AccountID const &uReceiverID, STAmount const &saAmount, beast::Journal j, WaiveTransferFee waiveFee)
static TER rippleCreditMPT(ApplyView &view, AccountID const &uSenderID, AccountID const &uReceiverID, STAmount const &saAmount, beast::Journal j)
bool cdirNext(ReadView const &view, uint256 const &root, std::shared_ptr< SLE const > &page, unsigned int &index, uint256 &entry)
Returns the next entry in the directory, advancing the index.
STAmount multiply(STAmount const &amount, Rate const &rate)
base_uint< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
TER authorizeMPToken(ApplyView &view, XRPAmount const &priorBalance, MPTID const &mptIssuanceID, AccountID const &account, beast::Journal journal, std::uint32_t flags=0, std::optional< AccountID > holderID=std::nullopt)
TER deleteAMMTrustLine(ApplyView &view, std::shared_ptr< SLE > sleState, std::optional< AccountID > const &ammAccountID, beast::Journal j)
Delete trustline to AMM.
STAmount creditLimit(ReadView const &view, AccountID const &account, AccountID const &issuer, Currency const ¤cy)
Calculate the maximum amount of IOUs that an account can hold.
static TER rippleCreditIOU(ApplyView &view, AccountID const &uSenderID, AccountID const &uReceiverID, STAmount const &saAmount, bool bCheckIssuer, beast::Journal j)
bool isDeepFrozen(ReadView const &view, AccountID const &account, Currency const ¤cy, AccountID const &issuer)
bool cdirFirst(ReadView const &view, uint256 const &root, std::shared_ptr< SLE const > &page, unsigned int &index, uint256 &entry)
Returns the first entry in the directory, advancing the index.
static TER rippleSendIOU(ApplyView &view, AccountID const &uSenderID, AccountID const &uReceiverID, STAmount const &saAmount, STAmount &saActual, beast::Journal j, WaiveTransferFee waiveFee)
static TER rippleSendMultiMPT(ApplyView &view, AccountID const &senderID, MPTIssue const &mptIssue, MultiplePaymentDestinations const &receivers, STAmount &actual, beast::Journal j, WaiveTransferFee waiveFee)
TER verifyDepositPreauth(STTx const &tx, ApplyView &view, AccountID const &src, AccountID const &dst, std::shared_ptr< SLE > const &sleDst, beast::Journal j)
@ current
This was a new validation and was added.
bool areCompatible(ReadView const &validLedger, ReadView const &testLedger, beast::Journal::Stream &s, char const *reason)
Return false if the test ledger is provably incompatible with the valid ledger, that is,...
bool isPseudoAccount(std::shared_ptr< SLE const > sleAcct, std::set< SField const * > const &pseudoFieldFilter={})
static std::uint32_t confineOwnerCount(std::uint32_t current, std::int32_t adjustment, std::optional< AccountID > const &id=std::nullopt, beast::Journal j=beast::Journal{beast::Journal::getNullSink()})
TER accountSend(ApplyView &view, AccountID const &from, AccountID const &to, STAmount const &saAmount, beast::Journal j, WaiveTransferFee waiveFee=WaiveTransferFee::No)
Calls static accountSendIOU if saAmount represents Issue.
std::optional< STAmount > assetsToSharesDeposit(std::shared_ptr< SLE const > const &vault, std::shared_ptr< SLE const > const &issuance, STAmount const &assets)
STAmount accountFunds(ReadView const &view, AccountID const &id, STAmount const &saDefault, FreezeHandling freezeHandling, beast::Journal j)
bool isGlobalFrozen(ReadView const &view, AccountID const &issuer)
std::optional< uint256 > hashOfSeq(ReadView const &ledger, LedgerIndex seq, beast::Journal journal)
Return the hash of a ledger by sequence.
std::optional< STAmount > assetsToSharesWithdraw(std::shared_ptr< SLE const > const &vault, std::shared_ptr< SLE const > const &issuance, STAmount const &assets, TruncateShares truncate=TruncateShares::no)
static TER rippleSendMultiIOU(ApplyView &view, AccountID const &senderID, Issue const &issue, MultiplePaymentDestinations const &receivers, STAmount &actual, beast::Journal j, WaiveTransferFee waiveFee)
bool canAdd(STAmount const &amt1, STAmount const &amt2)
Safely checks if two STAmount values can be added without overflow, underflow, or precision loss.
TERSubset< CanCvtToTER > TER
void adjustOwnerCount(ApplyView &view, std::shared_ptr< SLE > const &sle, std::int32_t amount, beast::Journal j)
Adjust the owner count up or down.
static STAmount getTrustLineBalance(ReadView const &view, SLE::const_ref sle, AccountID const &account, Currency const ¤cy, AccountID const &issuer, bool includeOppositeLimit, beast::Journal j)
static TER withdrawToDestExceedsLimit(ReadView const &view, AccountID const &from, AccountID const &to, STAmount const &amount)
AuthHandling
Controls the treatment of unauthorized MPT balances.
Rate transferRate(ReadView const &view, AccountID const &issuer)
Returns IOU issuer transfer fee as Rate.
static SLE::const_pointer getLineIfUsable(ReadView const &view, AccountID const &account, Currency const ¤cy, AccountID const &issuer, FreezeHandling zeroIfFrozen, beast::Journal j)
majorityAmendments_t getMajorityAmendments(ReadView const &view)
bool after(NetClock::time_point now, std::uint32_t mark)
Has the specified time passed?
STAmount creditBalance(ReadView const &view, AccountID const &account, AccountID const &issuer, Currency const ¤cy)
Returns the amount of IOUs issued by issuer that are held by an account.
TER requireAuth(ReadView const &view, Issue const &issue, AccountID const &account, AuthType authType=AuthType::Legacy)
Check if the account lacks required authorization.
TER canTransfer(ReadView const &view, MPTIssue const &mptIssue, AccountID const &from, AccountID const &to)
Check if the destination account is allowed to receive MPT.
bool isFrozen(ReadView const &view, AccountID const &account, Currency const ¤cy, AccountID const &issuer)
TER transferXRP(ApplyView &view, AccountID const &from, AccountID const &to, STAmount const &amount, beast::Journal j)
std::function< void(SLE::ref)> describeOwnerDir(AccountID const &account)
constexpr std::uint32_t const tfMPTUnauthorize
TER dirLink(ApplyView &view, AccountID const &owner, std::shared_ptr< SLE > &object, SF_UINT64 const &node=sfOwnerNode)
bool isIndividualFrozen(ReadView const &view, AccountID const &account, Currency const ¤cy, AccountID const &issuer)
TER offerDelete(ApplyView &view, std::shared_ptr< SLE > const &sle, beast::Journal j)
Delete an offer.
AccountID const & noAccount()
A placeholder for empty accounts.
static bool updateTrustLine(ApplyView &view, SLE::pointer state, bool bSenderHigh, AccountID const &sender, STAmount const &before, STAmount const &after, beast::Journal j)
TER redeemIOU(ApplyView &view, AccountID const &account, STAmount const &amount, Issue const &issue, beast::Journal j)
static TER accountSendIOU(ApplyView &view, AccountID const &uSenderID, AccountID const &uReceiverID, STAmount const &saAmount, beast::Journal j, WaiveTransferFee waiveFee)
bool canSubtract(STAmount const &amt1, STAmount const &amt2)
Determines if it is safe to subtract one STAmount from another.
bool isTesSuccess(TER x) noexcept
std::optional< STAmount > sharesToAssetsWithdraw(std::shared_ptr< SLE const > const &vault, std::shared_ptr< SLE const > const &issuance, STAmount const &shares)
TER rippleLockEscrowMPT(ApplyView &view, AccountID const &uGrantorID, STAmount const &saAmount, beast::Journal j)
LedgerEntryType
Identifiers for on-ledger objects.
AccountID const & xrpAccount()
Compute AccountID from public key.
@ tecNO_LINE_INSUF_RESERVE
@ tecINSUFFICIENT_RESERVE
bool forEachItemAfter(ReadView const &view, Keylet const &root, uint256 const &after, std::uint64_t const hint, unsigned int limit, std::function< bool(std::shared_ptr< SLE const > const &)> const &f)
Iterate all items after an item in the given directory.
static TER accountSendMultiMPT(ApplyView &view, AccountID const &senderID, MPTIssue const &mptIssue, MultiplePaymentDestinations const &receivers, beast::Journal j, WaiveTransferFee waiveFee)
TER enforceMPTokenAuthorization(ApplyView &view, MPTID const &mptIssuanceID, AccountID const &account, XRPAmount const &priorBalance, beast::Journal j)
Enforce account has MPToken to match its authorization.
TER canWithdraw(ReadView const &view, AccountID const &from, AccountID const &to, SLE::const_ref toSle, STAmount const &amount, bool hasDestinationTag)
Checks that can withdraw funds from an object to itself or a destination.
Expected< std::shared_ptr< SLE >, TER > createPseudoAccount(ApplyView &view, uint256 const &pseudoOwnerKey, SField const &ownerField)
Create pseudo-account, storing pseudoOwnerKey into ownerField.
TER checkDestinationAndTag(SLE::const_ref toSle, bool hasDestinationTag)
Validates that the destination SLE and tag are valid.
TER accountSendMulti(ApplyView &view, AccountID const &senderID, Asset const &asset, MultiplePaymentDestinations const &receivers, beast::Journal j, WaiveTransferFee waiveFee=WaiveTransferFee::No)
Like accountSend, except one account is sending multiple payments (with the same asset!...
TER trustDelete(ApplyView &view, std::shared_ptr< SLE > const &sleRippleState, AccountID const &uLowAccountID, AccountID const &uHighAccountID, beast::Journal j)
bool isLPTokenFrozen(ReadView const &view, AccountID const &account, Issue const &asset, Issue const &asset2)
Rate const parityRate
A transfer rate signifying a 1:1 exchange.
bool dirNext(ApplyView &view, uint256 const &root, std::shared_ptr< SLE > &page, unsigned int &index, uint256 &entry)
TER cleanupOnAccountDelete(ApplyView &view, Keylet const &ownerDirKeylet, EntryDeleter const &deleter, beast::Journal j, std::optional< std::uint16_t > maxNodesToDelete=std::nullopt)
Cleanup owner directory entries on account delete.
TER rippleCredit(ApplyView &view, AccountID const &uSenderID, AccountID const &uReceiverID, STAmount const &saAmount, bool bCheckIssuer, beast::Journal j)
Calls static rippleCreditIOU if saAmount represents Issue.
XRPAmount accountReserve(std::size_t ownerCount) const
Returns the account reserve given the owner count, in drops.
A pair of SHAMap key and LedgerEntryType.
Represents a transfer rate.
A field with a type known at compile time.
Returns the RIPEMD-160 digest of the SHA256 hash of the message.
T time_since_epoch(T... args)