From 9330811f454a107bf77bc5aa645dd14c0b8428e0 Mon Sep 17 00:00:00 2001 From: EnzinoBB Date: Fri, 30 Oct 2026 15:32:38 +0100 Subject: [PATCH 1/3] samples: a token template and a Python client that calls contracts with the declared types samples/contracts/Token.java is a token to start from: SmartContract v3 and ExtensionTokenStandard v1 (token standard 4). Every amount is checked (positive, at most the token's decimals), balances and allowances are kept at the token's scale, approve() sets the allowance as ERC-20 does instead of adding to it, payable() sells tokens for CS at a price. The executor harness runs it on every executor (template_token). samples/python/token_client.py lists a contract's methods (SmartContractGet, then ContractAllMethodsGet), reads a getter through TransactionFlow with forgetNewState (free, nothing sent) and signs and sends a call; each argument is converted to the type the method declares (String, BigDecimal, int, long, boolean, double and wrappers, byte[]), which the executor requires. --- ci/contracts/token_scenarios.py | 31 ++++- docs/CHANGES.md | 1 + docs/tokens.md | 15 +++ samples/contracts/Token.java | 203 ++++++++++++++++++++++++++++++++ samples/python/token_client.py | 170 ++++++++++++++++++++++++++ 5 files changed, 419 insertions(+), 1 deletion(-) create mode 100644 samples/contracts/Token.java create mode 100644 samples/python/token_client.py diff --git a/ci/contracts/token_scenarios.py b/ci/contracts/token_scenarios.py index dfae04d74..9b79f581d 100644 --- a/ci/contracts/token_scenarios.py +++ b/ci/contracts/token_scenarios.py @@ -385,6 +385,35 @@ def token_v1_lifecycle(ex, rec, Contract): severity="info") +def template_token(ex, rec, Contract): + """The token template of samples/contracts/Token.java""" + path = os.path.join(HERE, "..", "..", "samples", "contracts", "Token.java") + if not os.path.exists(path): + rec.step("template not found", path=path) + return + with open(path) as f: + t = Contract(ex, "Token", f.read(), OWNER, rec) + if not rec.expect((t.deploy() or {}).get("ok"), "the template deploys"): + return + r = t.get_methods() + rec.expect(r.tokenStandard == 4, f"the template is an ExtensionTokenStandard token (got {r.tokenStandard})") + get = lambda m, *p: t.get(m, *p)["ret"] + rec.expect(t.call(OWNER, "transfer", v_str(b58(ALICE)), v_dec("100"))["ok"], "transfer") + rec.expect(get("balanceOf", v_str(b58(ALICE))) == "100.000", "balances are kept at the token's scale") + rec.expect(not t.call(ALICE, "transfer", v_str(b58(BOB)), v_dec("1.0001"))["ok"], "an amount with too many decimals fails") + rec.expect(not t.call(ALICE, "transfer", v_str(b58(BOB)), v_dec("-1"))["ok"], "a negative amount fails") + rec.expect(not t.call(ALICE, "transfer", v_str(b58(BOB)), v_dec("100.001"))["ok"], "more than the balance fails") + t.call(ALICE, "approve", v_str(b58(BOB)), v_dec("10")) + t.call(ALICE, "approve", v_str(b58(BOB)), v_dec("4")) + rec.expect(get("allowance", v_str(b58(ALICE)), v_str(b58(BOB))) == "4.000", "approve sets the allowance, it does not add") + rec.expect(t.call(BOB, "transferFrom", v_str(b58(ALICE)), v_str(b58(CAROL)), v_dec("4"))["ok"], "transferFrom within the allowance") + rec.expect(not t.call(BOB, "transferFrom", v_str(b58(ALICE)), v_str(b58(CAROL)), v_dec("0.001"))["ok"], "the allowance is used up") + rec.expect(t.call(ALICE, "payable", v_dec("2.5"), v_bytes(b""))["ok"], "payable buys tokens") + rec.expect(get("balanceOf", v_str(b58(ALICE))) == "98.500", "96 + 2.5 bought") + rec.expect(not t.call(ALICE, "setFrozen", v_bool(True))["ok"], "only the owner freezes") + rec.expect(t.call(OWNER, "burn", v_dec("1000"))["ok"] and get("totalSupply") == "9999000.000", "burn") + + def token_v0_lifecycle(ex, rec, Contract): """A v0 token (amounts as strings), including the legacy payable(String, String)""" t = Contract(ex, "TokenV0", source("TokenV0"), OWNER, rec) @@ -535,6 +564,6 @@ def general_double(x): return general.Variant(v_double=x) -SCENARIOS = [token_standards, token_v1_lifecycle, token_v0_lifecycle, failed_call_state, getter_writes, +SCENARIOS = [token_standards, token_v1_lifecycle, template_token, token_v0_lifecycle, failed_call_state, getter_writes, reserved_names, root_class, platform_calls, emitted_precision, contract_calls, slow_token_name, serialization_hang] diff --git a/docs/CHANGES.md b/docs/CHANGES.md index 816f8ef07..ee2414a33 100644 --- a/docs/CHANGES.md +++ b/docs/CHANGES.md @@ -45,6 +45,7 @@ lines under the new release. | #127 | ci: token tests: `ci/contracts/executor_harness.py` compares contract executors on token contracts without a node, and `TOKENS=1` runs `ci/testnet/tokens.py` (v1 and v0 tokens, balances and states on every node, the token API; `TOKENS_VIA` through another node) on the private network | | #128 | api: the token cache (`[api] tokens_cache=true`, any build) follows v1/v2 tokens (BigDecimal amounts, standards 3 and 4) and only successful calls. It reads balances from the contract for the wallets a call involves, refreshes them in the background at start, and is rebuilt from the chain when the checkpoint holds none. `approve()` without arguments no longer reads out of bounds. `TokensListGet` filters before paging, and the token lists sort without exceptions or invalid orderings. `TokenTransfersListGet` reports the signer as the sender. See [tokens.md](tokens.md) | | #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) | +| — | 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`) | ## community.14 — 2026-10-27 diff --git a/docs/tokens.md b/docs/tokens.md index 580ff80db..1d0499b58 100644 --- a/docs/tokens.md +++ b/docs/tokens.md @@ -29,6 +29,21 @@ call fails with "Cannot find a method by name and parameters specified", and the fee is still charged. The reverse applies to v0 tokens. A wallet reads the types from `ContractMethodsGet` (or `SmartContractGet`) before it builds the call. +## A template and a client + +- `samples/contracts/Token.java`: a token to start from (ExtensionTokenStandard v1, token standard + 4). It checks every amount (positive, no more decimals than the token has), keeps balances at the + token's scale, sets allowances with `approve()` as ERC-20 does, and sells tokens for CS through + `payable()`. The executor harness runs it (`template_token`). +- `samples/python/token_client.py`: lists a contract's methods, reads a getter for free, and signs + and sends a call, converting each argument to the type the method declares: + + ```sh + python3 samples/python/token_client.py methods + python3 samples/python/token_client.py get balanceOf + python3 samples/python/token_client.py --seed call transfer 12.5 + ``` + ## The token cache - `[api] tokens_cache=true` turns the cache on. It is off by default. The RelMonitor and diff --git a/samples/contracts/Token.java b/samples/contracts/Token.java new file mode 100644 index 000000000..440b32507 --- /dev/null +++ b/samples/contracts/Token.java @@ -0,0 +1,203 @@ +import com.credits.scapi.annotations.Getter; +import com.credits.scapi.v1.ExtensionTokenStandard; +import com.credits.scapi.v3.SmartContract; + +import java.math.BigDecimal; +import java.util.HashMap; +import java.util.Map; + +import static java.math.BigDecimal.ZERO; + +/** + * A token template for the Credits network: SmartContract v3 and ExtensionTokenStandard v1, so that + * wallets and the node's token API (token standard 4) recognise it. + * + * What it does that older templates did not: + * - every amount is checked: positive, and with no more decimals than the token has (a call with + * 1.0001 on a 3-decimal token fails instead of creating dust nobody can move); + * - every balance and allowance is stored with the token's scale, so 5 and 5.000 are the same value; + * - approve() sets the allowance (ERC-20 semantics), it does not add to it; + * - transfer() to oneself and transferFrom() with from == to do nothing but still check the amount. + * + * Calls pass amounts as BigDecimal (Variant v_big_decimal) and addresses as base58 strings + * (v_string): the node refuses a call whose arguments do not match (docs/tokens.md). + * Change NAME, SYMBOL, DECIMALS, SUPPLY and PRICE before deploying; "CS" and "CS Credits" are refused. + */ +public class Token extends SmartContract implements ExtensionTokenStandard { + + private static final String NAME = "My Token"; + private static final String SYMBOL = "MYT"; + private static final int DECIMALS = 3; + private static final long SUPPLY = 10_000_000L; + // CS paid for one token through payable() (a CS transfer to the contract); 0 = not for sale + private static final String PRICE = "1"; + + private final String owner; + private final HashMap balances = new HashMap<>(); + private final HashMap> allowed = new HashMap<>(); + private BigDecimal totalCoins; + private boolean frozen; + + public Token() { + super(); + owner = initiator; + totalCoins = scaled(new BigDecimal(SUPPLY)); + balances.put(owner, totalCoins); + } + + @Getter + @Override + public String getName() { + return NAME; + } + + @Getter + @Override + public String getSymbol() { + return SYMBOL; + } + + @Getter + @Override + public int getDecimal() { + return DECIMALS; + } + + @Getter + @Override + public BigDecimal totalSupply() { + return totalCoins; + } + + @Getter + @Override + public BigDecimal balanceOf(String owner) { + return balance(owner); + } + + @Getter + @Override + public BigDecimal allowance(String owner, String spender) { + Map spenders = allowed.get(owner); + BigDecimal amount = spenders == null ? null : spenders.get(spender); + return amount == null ? scaled(ZERO) : amount; + } + + @Getter + public String getOwner() { + return owner; + } + + @Override + public boolean setFrozen(boolean isFrozen) { + onlyOwner(); + frozen = isFrozen; + return true; + } + + @Override + public boolean transfer(String to, BigDecimal amount) { + notFrozen(); + BigDecimal value = checked(amount); + if (!to.equals(initiator)) { + move(initiator, to, value); + } + return true; + } + + @Override + public boolean transferFrom(String from, String to, BigDecimal amount) { + notFrozen(); + BigDecimal value = checked(amount); + BigDecimal allowance = allowance(from, initiator); + if (allowance.compareTo(value) < 0) { + throw new RuntimeException("allowance of " + initiator + " is " + allowance.toPlainString() + ", less than " + value.toPlainString()); + } + if (!from.equals(to)) { + move(from, to, value); + } + allowed.get(from).put(initiator, allowance.subtract(value)); + return true; + } + + @Override + public void approve(String spender, BigDecimal amount) { + BigDecimal value = amount.signum() == 0 ? scaled(ZERO) : checked(amount); + allowed.computeIfAbsent(initiator, k -> new HashMap<>()).put(spender, value); + } + + @Override + public boolean burn(BigDecimal amount) { + notFrozen(); + BigDecimal value = checked(amount); + BigDecimal balance = balance(initiator); + if (balance.compareTo(value) < 0) { + throw new RuntimeException("balance of " + initiator + " is " + balance.toPlainString() + ", less than " + value.toPlainString()); + } + balances.put(initiator, balance.subtract(value)); + totalCoins = totalCoins.subtract(value); + return true; + } + + @Override + public void register() { + balances.putIfAbsent(initiator, scaled(ZERO)); + } + + // a CS transfer to the contract buys tokens from the owner at PRICE + @Override + public String payable(BigDecimal amount, byte[] userData) { + notFrozen(); + BigDecimal price = new BigDecimal(PRICE); + if (price.signum() <= 0) { + throw new RuntimeException("the token is not for sale"); + } + BigDecimal tokens = amount.divide(price, DECIMALS, BigDecimal.ROUND_DOWN); + if (tokens.signum() <= 0) { + throw new RuntimeException("the amount buys no token"); + } + move(owner, initiator, tokens); + return "bought " + tokens.toPlainString() + " " + SYMBOL; + } + + private void move(String from, String to, BigDecimal value) { + BigDecimal source = balance(from); + if (source.compareTo(value) < 0) { + throw new RuntimeException("balance of " + from + " is " + source.toPlainString() + ", less than " + value.toPlainString()); + } + balances.put(from, source.subtract(value)); + balances.put(to, balance(to).add(value)); + } + + // a positive amount with at most DECIMALS decimals, at the token's scale + private BigDecimal checked(BigDecimal amount) { + if (amount == null || amount.signum() <= 0) { + throw new RuntimeException("the amount must be positive"); + } + if (amount.stripTrailingZeros().scale() > DECIMALS) { + throw new RuntimeException("the amount has more than " + DECIMALS + " decimals"); + } + return scaled(amount); + } + + private BigDecimal balance(String address) { + BigDecimal balance = balances.get(address); + return balance == null ? scaled(ZERO) : balance; + } + + private static BigDecimal scaled(BigDecimal value) { + return value.setScale(DECIMALS, BigDecimal.ROUND_UNNECESSARY); + } + + private void onlyOwner() { + if (!initiator.equals(owner)) { + throw new RuntimeException("only the owner " + owner + " can do this"); + } + } + + private void notFrozen() { + if (frozen) { + throw new RuntimeException("the token is frozen"); + } + } +} diff --git a/samples/python/token_client.py b/samples/python/token_client.py new file mode 100644 index 000000000..9e84c860c --- /dev/null +++ b/samples/python/token_client.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Call a Credits smart contract from the command line, with arguments of the types it declares. + + token_client.py [--api 127.0.0.1:9090] methods + token_client.py [--api ...] get [args...] read, free, nothing is sent + token_client.py [--api ...] --seed call [args...] + +Arguments are given as text and converted to the type the method declares, which the executor +requires (a BigDecimal amount must be a v_big_decimal, not a v_string): String, BigDecimal, int, +long, boolean, double and their wrappers, byte[] as hex. With overloads, the method with as many +arguments as given is used. + + token_client.py methods 9xJ...TOKEN + token_client.py get 9xJ...TOKEN balanceOf 4Fv...WALLET + token_client.py --seed 3Ab...KEY call 9xJ...TOKEN transfer 4Fv...WALLET 12.5 + +Needs thriftpy2, base58 and pynacl (pip install thriftpy2 base58 pynacl) and the Thrift definitions +of the node (third-party/thrift-interface-definitions, or --idl). +""" +import argparse +import math +import os +import struct +import sys +import time + +import base58 +import nacl.signing +import thriftpy2 +from thriftpy2.protocol import TBinaryProtocolFactory +from thriftpy2.rpc import make_client +from thriftpy2.transport import TBufferedTransportFactory +from thriftpy2.utils import serialize + +HERE = os.path.dirname(os.path.abspath(__file__)) +CURRENCY_CS = 1 +TT_EXECUTE = 2 # api.TransactionType + + +def encode_max_fee(value): + """csdb::AmountCommission(double) as its uint16 bit pattern.""" + v = abs(value) + expf = math.log10(v) + expi = int(expf + 0.5) if expf >= 0 else int(expf - 0.5) + v /= 10 ** expi + if v >= 1.0: + v *= 0.1 + expi += 1 + return (((expi + 18) & 0x1F) << 10) | (int(round(v * 1024)) & 0x3FF) + + +def variant(general, declared, text): + """The Variant the executor matches with a declared Java type.""" + converters = { + "java.lang.String": lambda t: general.Variant(v_string=t), + "java.math.BigDecimal": lambda t: general.Variant(v_big_decimal=str(t)), + "int": lambda t: general.Variant(v_int=int(t)), + "java.lang.Integer": lambda t: general.Variant(v_int_box=int(t)), + "long": lambda t: general.Variant(v_long=int(t)), + "java.lang.Long": lambda t: general.Variant(v_long_box=int(t)), + "boolean": lambda t: general.Variant(v_boolean=t.lower() in ("true", "1", "yes")), + "java.lang.Boolean": lambda t: general.Variant(v_boolean_box=t.lower() in ("true", "1", "yes")), + "double": lambda t: general.Variant(v_double=float(t)), + "java.lang.Double": lambda t: general.Variant(v_double_box=float(t)), + "byte[]": lambda t: general.Variant(v_byte_array=bytes.fromhex(t)), + } + if declared not in converters: + sys.exit(f"arguments of type {declared} are not supported by this client") + return converters[declared](text) + + +def plain(v): + if v is None: + return None + for name in ("v_string", "v_big_decimal", "v_boolean", "v_boolean_box", "v_int", "v_int_box", "v_long", + "v_long_box", "v_double", "v_double_box", "v_byte", "v_short"): + value = getattr(v, name, None) + if value is not None: + return value + if v.v_byte_array is not None: + return v.v_byte_array.hex() + if v.v_void is not None: + return "(void)" + return v + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--api", default="127.0.0.1:9090", help="host:port of the node's Thrift API") + parser.add_argument("--idl", default=os.path.join(HERE, "..", "..", "third-party", "thrift-interface-definitions")) + parser.add_argument("--seed", help="base58 private key (64 bytes, or its 32-byte seed) that signs a call") + parser.add_argument("--max-fee", type=float, default=1.0, help="most CS the call may cost (default 1)") + parser.add_argument("command", choices=["methods", "get", "call"]) + parser.add_argument("contract") + parser.add_argument("method", nargs="?") + parser.add_argument("args", nargs="*") + a = parser.parse_args() + + general = thriftpy2.load(os.path.join(a.idl, "general.thrift"), module_name="general_thrift", include_dirs=[a.idl]) + api = thriftpy2.load(os.path.join(a.idl, "api.thrift"), module_name="api_thrift", include_dirs=[a.idl]) + host, port = a.api.rsplit(":", 1) + client = make_client(api.API, host=host, port=int(port), proto_factory=TBinaryProtocolFactory(), + trans_factory=TBufferedTransportFactory(), timeout=120000) + contract = base58.b58decode(a.contract) + + # the methods of the contract: its byte code (SmartContractGet), listed by the node's executor + deployed = client.SmartContractGet(contract) + if deployed.status.code != 0: + sys.exit(f"SmartContractGet: {deployed.status.message}") + methods = client.ContractAllMethodsGet(deployed.smartContract.smartContractDeploy.byteCodeObjects) + if methods.code != 0: + sys.exit(f"ContractAllMethodsGet: {methods.message}") + if a.command == "methods": + for m in sorted(methods.methods, key=lambda m: m.name): + print(f" {m.returnType} {m.name}({', '.join(arg.type + ' ' + arg.name for arg in m.arguments)})") + return + + candidates = [m for m in methods.methods if m.name == a.method and len(m.arguments) == len(a.args)] + if not candidates: + known = [f"{m.name}({', '.join(x.type for x in m.arguments)})" for m in methods.methods if m.name == a.method] + sys.exit(f"no method {a.method} with {len(a.args)} arguments" + (f"; there is {', '.join(known)}" if known else "")) + method = candidates[0] + params = [variant(general, arg.type, text) for arg, text in zip(method.arguments, a.args)] + + if a.command == "get": + # TransactionFlow with forgetNewState: run by the node's executor on the current state, nothing + # is sent and no fee is paid; no signature is checked + sci = api.SmartContractInvocation(method=a.method, params=params, usedContracts=[], forgetNewState=True, + smartContractDeploy=None, version=1) + source = bytes(32) if not a.seed else nacl.signing.SigningKey(base58.b58decode(a.seed)[:32]).verify_key.encode() + t = api.Transaction(id=0, source=source, target=contract, amount=general.Amount(integral=0, fraction=0), + balance=general.Amount(integral=0, fraction=0), currency=CURRENCY_CS, signature=bytes(64), + smartContract=sci, fee=api.AmountCommission(commission=encode_max_fee(a.max_fee)), + timeCreation=int(time.time() * 1000), type=TT_EXECUTE) + r = client.TransactionFlow(t) + if r.status.code != 0: + sys.exit(r.status.message) + print(plain(r.smart_contract_result)) + return + + if not a.seed: + sys.exit("call needs --seed: the call is a transaction signed by its sender") + key = nacl.signing.SigningKey(base58.b58decode(a.seed)[:32]) + pk = key.verify_key.encode() + inner_id = int(client.WalletTransactionsCountGet(pk).lastTransactionInnerId or 0) + 1 + max_fee = encode_max_fee(a.max_fee) + # every non-optional field set, so that the bytes signed are those the node serializes + sci = api.SmartContractInvocation(method=a.method, params=params, usedContracts=[], forgetNewState=False, + smartContractDeploy=None, version=1) + code = serialize(sci, TBinaryProtocolFactory()) + signed = b"".join([ + inner_id.to_bytes(6, "little"), pk, contract, + struct.pack(" Date: Fri, 30 Oct 2026 15:32:56 +0100 Subject: [PATCH 2/3] docs: CHANGES line for #135 --- docs/CHANGES.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CHANGES.md b/docs/CHANGES.md index ee2414a33..88bbf146b 100644 --- a/docs/CHANGES.md +++ b/docs/CHANGES.md @@ -45,7 +45,7 @@ lines under the new release. | #127 | ci: token tests: `ci/contracts/executor_harness.py` compares contract executors on token contracts without a node, and `TOKENS=1` runs `ci/testnet/tokens.py` (v1 and v0 tokens, balances and states on every node, the token API; `TOKENS_VIA` through another node) on the private network | | #128 | api: the token cache (`[api] tokens_cache=true`, any build) follows v1/v2 tokens (BigDecimal amounts, standards 3 and 4) and only successful calls. It reads balances from the contract for the wallets a call involves, refreshes them in the background at start, and is rebuilt from the chain when the checkpoint holds none. `approve()` without arguments no longer reads out of bounds. `TokensListGet` filters before paging, and the token lists sort without exceptions or invalid orderings. `TokenTransfersListGet` reports the signer as the sender. See [tokens.md](tokens.md) | | #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) | -| — | 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`) | +| #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`) | ## community.14 — 2026-10-27 From 42664b5067c00710483709088f3f7e1877dce214 Mon Sep 17 00:00:00 2001 From: EnzinoBB Date: Fri, 30 Oct 2026 15:33:38 +0100 Subject: [PATCH 3/3] docs: RelMonitor/RelWallet are not built or tested; tokens_cache replaces them for the token API --- docs/tokens.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/tokens.md b/docs/tokens.md index 1d0499b58..59597c191 100644 --- a/docs/tokens.md +++ b/docs/tokens.md @@ -49,6 +49,10 @@ fee is still charged. The reverse applies to v0 tokens. A wallet reads the types - `[api] tokens_cache=true` turns the cache on. It is off by default. The RelMonitor and RelWallet builds always have it on, as the official monitor and wallet nodes do. With the cache off, the token methods answer "This node doesn't provide such info". +- **RelMonitor and RelWallet builds.** These are the official monitor and wallet configurations + (`-DMONITOR_NODE`, `-DWEB_WALLET_NODE`). The community CI neither builds nor tests them, and a + private network of RelWallet nodes did not get past its first round in our tests. Use a normal + build with `tokens_cache=true` instead: it serves the same token methods. - **What it records.** A token is recorded at its deploy. After each successful call, the node records: - the initiator, and every argument that is a wallet address, as holders of the token;