Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions api/include/apihandler.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,7 @@ class APIHandler : public APIHandlerInterface {
::csdb::Transaction makeTransaction(const ::api::Transaction&);
void dumbTransactionFlow(api::TransactionFlowResult& _return, const csdb::Transaction& tr);
void smartTransactionFlow(api::TransactionFlowResult& _return, const ::api::Transaction&, csdb::Transaction& send_transaction);
SmartOperationState operationState(const csdb::TransactionID& id);
std::vector<general::MethodDescription> contractMethods(const csdb::Address& contract, const std::vector<general::ByteCodeObject>& byteCode);
std::mutex contractMethodsLock_;
std::unordered_map<csdb::Address, std::vector<general::MethodDescription>> contractMethods_;
Expand Down
51 changes: 36 additions & 15 deletions api/src/apihandler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2504,6 +2504,13 @@ void APIHandler::ContractAllMethodsGet(ContractAllMethodsGetResult& _return, con
}
}

// the state of a contract call the API knows, Pending for one it does not (never adds an entry)
SmartOperationState APIHandler::operationState(const csdb::TransactionID& id) {
auto opers = cs::lockedReference(this->smart_operations);
const auto it = opers->find(id);
return static_cast<SmartOperationState>(it == opers->end() ? SmartOperation::State::Pending : it->second.state);
}

void APIHandler::addTokenResult(api::TokenTransfersResult& _return, const csdb::Address& token, const std::string& code, const csdb::Pool& pool, const csdb::Transaction& tr,
const api::SmartContractInvocation& smart, const std::pair<csdb::Address, csdb::Address>& addrPair) {
api::TokenTransfer transfer;
Expand All @@ -2525,8 +2532,7 @@ void APIHandler::addTokenResult(api::TokenTransfersResult& _return, const csdb::
if (ufd.is_valid()) {
transfer.__set_userFields(ufd.value<std::string>());
}
auto opers = cs::lockedReference(this->smart_operations);
transfer.state = static_cast<SmartOperationState>((*opers)[tr.id()].state);
transfer.state = operationState(tr.id());

if (transfer.state == SOS_Success) {
_return.transfers.push_back(transfer);
Expand All @@ -2544,21 +2550,25 @@ void APIHandler::addTokenResult(api::TokenTransactionsResult& _return, const csd
trans.method = smart.method;
trans.params = smart.params;

auto opers = cs::lockedReference(this->smart_operations);
trans.state = static_cast<SmartOperationState>((*opers)[tr.id()].state);
trans.state = operationState(tr.id());

_return.transactions.push_back(trans);
}

// a 64-bit counter in an i32 field of the API: the largest i32 instead of a wrapped value
static int32_t toInt32(uint64_t value) {
return static_cast<int32_t>(std::min<uint64_t>(value, static_cast<uint64_t>(std::numeric_limits<int32_t>::max())));
}

void putTokenInfo(api::TokenInfo& ti, const general::Address& addr, const Token& token) {
ti.address = addr;
ti.code = token.symbol;
ti.name = token.name;
ti.totalSupply = token.totalSupply;
ti.owner = fromByteArray(token.owner.public_key());
ti.transfersCount = int32_t(token.transfersCount);
ti.transactionsCount = int32_t(token.transactionsCount);
ti.holdersCount = int32_t(token.realHoldersCount);
ti.transfersCount = toInt32(token.transfersCount);
ti.transactionsCount = toInt32(token.transactionsCount);
ti.holdersCount = toInt32(token.realHoldersCount);
ti.tokenStandard = decltype(api::TokenInfo::tokenStandard)(uint32_t((token.tokenStandard)));
}

Expand All @@ -2582,15 +2592,15 @@ void APIHandler::tokenTransactionsInternal(ResultType& _return, APIHandler& hand
//cslog() << __func__ << ": Tokens found";
code = it->second.symbol;
if (transfersOnly && !filterByWallet) {
_return.count = static_cast<int32_t>(it->second.transfersCount);
_return.count = toInt32(it->second.transfersCount);
}
else if (!transfersOnly) {
_return.count = static_cast<int32_t>(it->second.transactionsCount);
_return.count = toInt32(it->second.transactionsCount);
}
else if (transfersOnly && filterByWallet) {
auto hIt = it->second.holders.find(wallet);
if (hIt != it->second.holders.end()) {
_return.count = static_cast<int32_t>(hIt->second.transfersCount);
_return.count = toInt32(hIt->second.transfersCount);
}
else {
_return.count = 0;
Expand All @@ -2616,6 +2626,10 @@ void APIHandler::tokenTransactionsInternal(ResultType& _return, APIHandler& hand
if (filterByWallet && addrPair.first != wallet && addrPair.second != wallet) {
return true;
}
// a failed transfer moved nothing and is not listed: it must not take a place in the page
if (transfersOnly && handler.operationState(tr.id()) != SOS_Success) {
return true;
}

if (--offset >= 0) {
return true;
Expand Down Expand Up @@ -2843,14 +2857,21 @@ void APIHandler::TokenTransferGet(api::TokenTransfersResult& _return, const gene
return;
}

const auto pool = executor_.loadBlockApi(trxn.id().pool_seq());
if (!trxn.is_valid() || !is_smart(trxn) || blockchain_.getAddressByType(trxn.target(), BlockChain::AddressType::PublicKey) != addr) {
SetResponseStatus(_return.status, APIRequestStatusType::NOT_FOUND, "no call to this token with this id");
return;
}
const auto smart = fetch_smart(trxn);
if (!TokensMaster::isTransfer(smart.method, smart.params)) {
SetResponseStatus(_return.status, APIRequestStatusType::NOT_FOUND, "the transaction is not a transfer of this token");
return;
}
const auto pool = executor_.loadBlockApi(trxn.id().pool_seq());
const auto addr_pk = blockchain_.getAddressByType(trxn.source(), BlockChain::AddressType::PublicKey);
const auto addrPair = TokensMaster::getTransferData(addr_pk, smart.method, smart.params);

_return.count = 1;

addTokenResult(_return, addr, code, pool, trxn, smart, addrPair);
_return.count = static_cast<int32_t>(_return.transfers.size());
SetResponseStatus(_return.status, APIRequestStatusType::SUCCESS);
}

Expand Down Expand Up @@ -3088,7 +3109,7 @@ void APIHandler::TokenHoldersGet(api::TokenHoldersResult& _return, const general
auto tIt = tm_.find(addr);
if (tIt != tm_.end()) {
found = true;
_return.count = static_cast<int32_t>(tIt->second.realHoldersCount);
_return.count = toInt32(tIt->second.realHoldersCount);

applyToSortedMap(tIt->second.holders, comparator, [&offset, &limit, &_return, &token](const HMap::value_type& t) {
if (TokensMaster::isZeroAmount(t.second.balance)) {
Expand All @@ -3103,7 +3124,7 @@ void APIHandler::TokenHoldersGet(api::TokenHoldersResult& _return, const general
th.holder = fromByteArray(t.first.public_key());
th.token = token;
th.balance = t.second.balance;
th.transfersCount = static_cast<int32_t>(t.second.transfersCount);
th.transfersCount = toInt32(t.second.transfersCount);

_return.holders.push_back(th);

Expand Down
14 changes: 14 additions & 0 deletions ci/testnet/tokens.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,20 @@ def main():
f"listed {len(tr.transfers or [])}", flush=True)
run.check(tr.status.code == 0 and len(tr.transfers or []) >= 3,
f"TokenTransfersGet lists the v1 transfers (got {len(tr.transfers or [])})", kind="api")
# a page of 2 transfers: the failed transfer in between takes no place in it
page = c.TokenTransfersGet(v1, 0, 2)
run.check(len(page.transfers or []) == 2, f"TokenTransfersGet with limit 2 lists 2 transfers (got {len(page.transfers or [])})",
kind="api")
if tr.transfers:
one = c.TokenTransferGet(v1, tr.transfers[0].transaction)
run.check(one.status.code == 0 and len(one.transfers or []) == 1 and one.count == 1,
"TokenTransferGet of a transfer returns it", kind="api")
txs = c.TokenTransactionsGet(v1, 0, 100)
approve = next((t for t in (txs.transactions or []) if t.method == "approve"), None)
if approve is not None:
other = c.TokenTransferGet(v1, approve.transaction)
run.check(other.status.code != 0 and not other.transfers, "TokenTransferGet of an approve() is not a transfer",
kind="api")
holders = c.TokenHoldersGet(v1, 0, 100, 0, True)
print(f" TokenHoldersGet TokenV1: status {holders.status.code} "
f"{[(b58(h.holder)[:8], h.balance) for h in (holders.holders or [])]}", flush=True)
Expand Down
3 changes: 3 additions & 0 deletions csnode/include/csnode/tokens_serializer.hpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#ifndef TOKENS_SERIALIZER_HPP
#define TOKENS_SERIALIZER_HPP
#include <filesystem>
#include <mutex>

#include <boost/serialization/serialization.hpp>
#include <boost/serialization/unordered_map.hpp>
Expand Down Expand Up @@ -74,6 +75,8 @@ class TokensMaster_Serializer {

TokensMap *tokens_;
HoldersMap *holders_;
// TokensMaster::dataMut_: the API updates the cache from other threads (block store, refresh)
std::mutex* mutex_ = nullptr;
};
} // namespace cs
#endif // TOKENS_SERIALIZER_HPP
5 changes: 5 additions & 0 deletions csnode/src/tokens_serializer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,19 @@ namespace cs {
void TokensMaster_Serializer::bind(TokensMaster& tokens) {
tokens_ = reinterpret_cast<decltype(tokens_)>(&tokens.tokens_);
holders_ = reinterpret_cast<decltype(holders_)>(&tokens.holders_);
mutex_ = &tokens.dataMut_;
csdebug() << "TokensMaster bindings made";
}

void TokensMaster_Serializer::clear(const std::filesystem::path& rootDir) {
(void)rootDir;
std::lock_guard lock(*mutex_);
tokens_->clear();
holders_->clear();
}

void TokensMaster_Serializer::save(const std::filesystem::path& rootDir) {
std::lock_guard lock(*mutex_);
std::ofstream ofs(rootDir / kDataFileName, std::ios::binary);
boost::archive::text_oarchive oa(ofs);
oa << *tokens_;
Expand All @@ -39,6 +42,7 @@ void TokensMaster_Serializer::save(const std::filesystem::path& rootDir) {

::cscrypto::Hash TokensMaster_Serializer::hash() {
{
std::lock_guard lock(*mutex_);
std::ofstream ofs(kDataFileName, std::ios::binary); // text mode on Windows would write \r\n and change the hash
ofs.imbue(std::locale::classic()); // with no_codecvt the archive formats numbers in the stream's locale
boost::archive::text_oarchive oa(
Expand All @@ -62,6 +66,7 @@ ::cscrypto::Hash TokensMaster_Serializer::hash() {
}

void TokensMaster_Serializer::load(const std::filesystem::path& rootDir) {
std::lock_guard lock(*mutex_);
std::ifstream ifs(rootDir / kDataFileName, std::ios::binary);
boost::archive::text_iarchive ia(ifs);
ia >> *tokens_;
Expand Down
1 change: 1 addition & 0 deletions docs/CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ lines under the new release.
| #131 | packaging: a guided set-up in every package (`setup.sh`, `setup.bat`): pruned or full, database, how the first start gets the chain, snapshot sharing, and the contract executor (community or official: it shows the build in the folder, can download either, checked, and sets `executor_commit_min/max` so that the node starts it; an upgrade by copying only the node binary keeps the old executor) |
| #132 | api: `TransactionFlow` refuses a contract call that no method of the contract matches (unknown method, wrong argument count, or a Variant that cannot match the declared type, such as a token amount as `v_string` for a `BigDecimal`), which would fail on every node with its fee paid; ci: `testnet.yml` inputs `tokens`/`tokens_via`, the executor harness compares only the answers |
| #135 | samples: a token template (`samples/contracts/Token.java`: checked amounts and decimals, balances at the token's scale, ERC-20 `approve()`, sale through `payable()`), run by the executor harness, and a Python client that calls a contract with the argument types it declares (`samples/python/token_client.py`) |
| #134 | api: token API leftovers: a failed transfer no longer takes a place in the pages of `TokenTransfersGet`/`TokenWalletTransfersGet`; `TokenTransferGet` answers only for a transfer of that token (it listed any transaction and added entries to the operations map); token counters above 2^31 report the largest i32 instead of wrapping; the token cache is saved, loaded and hashed under its lock (the background refresh could change it during a checkpoint) |

## community.14 — 2026-10-27

Expand Down
Loading