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
31 changes: 30 additions & 1 deletion ci/contracts/token_scenarios.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -581,6 +610,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, abandoned_call, slow_token_name,
serialization_hang]
1 change: 1 addition & 0 deletions docs/CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ lines under the new release.
| #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) |
| #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`) |

## community.14 — 2026-10-27

Expand Down
19 changes: 19 additions & 0 deletions docs/tokens.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,30 @@ not have, a wrong number of arguments, or an argument whose Variant cannot match
mismatches are refused: with types other than `String`, `BigDecimal`, `boolean`, `int`, `long`,
`double` (and their wrappers) and `byte[]` the call goes on as before.

## 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 <token>
python3 samples/python/token_client.py get <token> balanceOf <wallet>
python3 samples/python/token_client.py --seed <private key> call <token> transfer <wallet> 12.5
```

## The token cache

- `[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;
Expand Down
203 changes: 203 additions & 0 deletions samples/contracts/Token.java
Original file line number Diff line number Diff line change
@@ -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<String, BigDecimal> balances = new HashMap<>();
private final HashMap<String, Map<String, BigDecimal>> 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<String, BigDecimal> 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");
}
}
}
Loading
Loading