Testnet Mode — switch back to Production in the menuheader when you're done.
VarnirTokenRegistry extends Event
Register an ERC20/TRC20 token so deposits of it are credited and it can be sent - the registry is what makes a token exist to this system at all.
{
"$sigs": {
"<registry stream id>": "<base64 signature of $tx, signed with the registry owner's private key>"
},
"$tx": {
"$contract": "<Varnir.TokenRegistry's deployed contract id>",
"$namespace": "varnir",
"$entry": "add",
"$i": {
"registry": {
"$stream": "<registry stream id>",
"network": "SEP",
"address": "4ea636f3ba863577dcced852b749f618951f2cca",
"symbol": "USDT",
"decimals": 6,
"chargeable": true
}
}
}
}/** * Voting round. * * Unlike Varnir.Rates - the closest existing singleton-stream contract - * this validates rather than resolving true unconditionally. A registry * entry decides whether a deposit is credited and what a raw balance is * worth, so a bad one is not a display bug. * * After the social-recovery guard: `create` needs a stake-100, non-read * key on `$i.owner`; `mod` goes to voteMod; otherwise the registry signer * must be stake 100 and not read-only, the entry one of add / update / * disable, the network and address valid, and `add` must be new with * integer `decimals` 0-36 and a `symbol`, while `update` / `disable` need * an existing entry and may not send `decimals`. */
public vote(): Promise<boolean> {
return new Promise<boolean>(async (resolve, reject) => {
// Social recovery (spec §4.5): a recovered identity is dead, a frozen one cannot move money.
const recoveryRefusal = this.refuseRecoveredStreams([]);
if (recoveryRefusal) return reject(recoveryRefusal);
const entryName = this.transactions.$entry;
// Creating the registry is the one entry with no registry to point at
// yet, so it is authorised against the identity doing the creating
// rather than against a stream that does not exist.
if (entryName === "create") {
const creator = this.getActivityStreams(this.transactions.$i.owner);
if (this.isReadOnlyKey(creator)) {
return reject("Stake Permission Error - Read Only 9000");
}
// >>> owner-gate
if (!this.isSingleOwnerKey(creator)) {
return reject("Only a stake-100 key may create the token registry");
}
// <<< owner-gate
if (!this.hasAuthorityStake(100, creator)) {
return reject("Only a stake-100 key may create the token registry");
}
return resolve(true);
}
if (entryName === "mod") {
try {
return resolve(await this.voteMod());
} catch (e) {
return reject(typeof e === "string" ? e : "Runtime Vote Revert");
}
}
const input = this.transactions.$i.registry;
if (!input) {
return reject("No registry input");
}
// Only a full owner may change what counts as money here. Read-only
// keys (read-labelled) are rejected the same way every other contract
// rejects them.
const registry = this.getActivityStreams(input);
if (this.isReadOnlyKey(registry)) {
return reject("Stake Permission Error - Read Only 9000");
}
// >>> owner-gate
if (!this.isSingleOwnerKey(registry)) {
return reject("Only a stake-100 key may change the token registry");
}
// <<< owner-gate
if (!this.hasAuthorityStake(100, registry)) {
return reject("Only a stake-100 key may change the token registry");
}
const entry = entryName;
if (entry !== "add" && entry !== "update" && entry !== "disable") {
return reject(`Unknown entry ${entry}`);
}
const network = input.network;
const address = input.address;
if (typeof network !== "string" || !network.length) {
return reject("network is required");
}
let evmDataNetwork = false;
try {
evmDataNetwork = NETWORKS.indexOf(network) === -1 && this.isEvmDataNetwork(network, entryName === "add");
} catch (e) {
return reject(typeof e === "string" ? e : "Runtime Vote Revert");
}
if (NETWORKS.indexOf(network) === -1 && !evmDataNetwork) {
return reject(
`network must be one of ${NETWORKS.join(", ")} - "${network}" would be stored as its own bucket and silently credit nothing`
);
}
if (typeof address !== "string" || !ADDRESS_PATTERN.test(address)) {
// Rejected rather than normalised here, deliberately. minigate
// normalises what it sees off the wire (strip 0x / 41, lowercase);
// if the registry accepted some other spelling the two would differ
// and every deposit of that token would silently miss its entry.
// Better a loud no now than a token that looks registered and never
// credits.
return reject(
"address must be lowercase hex with no 0x or 41 prefix, matching minigate's normalised form"
);
}
const state = registry.getState();
const existing = state.tokens?.[network]?.[address];
if (entry === "add") {
if (existing) {
return reject(`${address} is already registered on ${network}`);
}
const decimals = input.decimals;
if (
typeof decimals !== "number" ||
!Number.isInteger(decimals) ||
decimals < 0 ||
decimals > MAX_DECIMALS
) {
return reject("decimals must be an integer between 0 and 36");
}
if (typeof input.symbol !== "string" || !input.symbol.length) {
return reject("symbol is required");
}
return resolve(true);
}
if (!existing) {
return reject(`${address} is not registered on ${network}`);
}
// decimals is absent from update on purpose, and refused if sent.
// Balances are stored raw, so changing decimals reprices every holding
// of that token retroactively and silently - a 6 to 18 correction turns
// someone's 5 USDT into 0.000000000005. A token registered wrongly is
// disabled and re-added at a new entry, never edited into correctness.
if (input.decimals !== undefined) {
return reject(
"decimals cannot be changed - balances are stored raw, so this would reprice every holding. Disable and re-add instead."
);
}
return resolve(true);
});
}/**
* Commit round. `create`: writes the registry stream (`tokens: {}`) and
* emits `token-registry-created`. `mod`: commitMod. `add`: writes
* `tokens[network][address] = {symbol, decimals, chargeable, enabled:
* true, addedAt, addedBy}`. `update` / `disable`: sets `enabled` (false on
* disable; on update, false only when `enabled: false` is sent), and
* optionally `symbol` and `chargeable`, with `updatedAt` / `updatedBy`.
* Every token change emits `token-registry-set`.
*/ public commit(): Promise<any> {
return new Promise<any>(async (resolve, reject) => {
if (this.transactions.$entry === "create") {
const creator = this.getActivityStreams(this.transactions.$i.owner);
const created = this.newActivityStream("varnir.tokenregistry");
// The creating identity's own authorities carry over, so whoever
// could create it can go on to add tokens to it. Without this the
// registry would be born unowned and immediately unusable.
created.setAuthorities(creator.getAuthorities());
created.setState({tokens: {}, createdAt: this.cDate, createdBy: this.umid});
this.event.emit("token-registry-created", {stream: created.getId()});
return resolve(true);
}
if (this.transactions.$entry === "mod") {
return resolve(await this.commitMod());
}
const input = this.transactions.$i.registry;
const registry = this.getActivityStreams(input);
const state = registry.getState();
const entry = this.transactions.$entry;
if (!state.tokens) {
state.tokens = {};
}
if (!state.tokens[input.network]) {
state.tokens[input.network] = {};
}
if (entry === "add") {
state.tokens[input.network][input.address] = {
symbol: input.symbol,
decimals: input.decimals,
// Legacy label, kept for readers. It replaced the old CHARGABLETOKENS
// list, but no fee decision reads it any more - Varnir.CryptoTransfer
// takes no on-ledger fee on any transfer or withdrawal.
chargeable: input.chargeable === true,
enabled: true,
addedAt: this.cDate,
addedBy: this.umid,
};
} else {
const token = state.tokens[input.network][input.address];
// Never deleted. A disabled entry still describes balances already
// credited under it - drop the row and a holding becomes unreadable,
// since nothing else records what those raw units meant.
token.enabled = entry === "disable" ? false : input.enabled !== false;
if (typeof input.symbol === "string" && input.symbol.length) {
token.symbol = input.symbol;
}
if (input.chargeable !== undefined) {
token.chargeable = input.chargeable === true;
}
token.updatedAt = this.cDate;
token.updatedBy = this.umid;
}
registry.setState(state);
// So minigate and l1-relay can refresh their watch lists without
// polling the stream - the same shape Varnir.Rates emits for rates.
this.event.emit("token-registry-set", {
stream: registry.getId(),
entry,
network: input.network,
address: input.address,
token: state.tokens[input.network][input.address],
});
resolve(true);
});
} private refuseRecoveredIdentity(state: any, outgoing: boolean): string | null {
if (state && state.recoveredTo) {
// A dead identity may still RECEIVE: the credit lands and is swept to recoveredTo.
return outgoing
? `Identity recovered - new identity is ${state.recoveredTo}; your keys are still valid`
: null;
}
if (outgoing && state && state.recovery && state.recovery.frozen) {
return "Identity frozen - a social recovery is in its 48h waiting period";
}
return null;
} private refuseRecoveredStreams(incomingOnly: string[] | "all-outputs"): string | null {
// Never getActivityStreams(ref): an unloaded ref CREATES a stream. The
// no-argument form returns only the streams this transaction loaded.
const ctx: any = this as any;
const loaded: any = ctx.getActivityStreams() || {};
const outputs: any = (ctx.transactions && ctx.transactions.$o) || {};
const toId = (label: string, ref: any): string | null => {
const raw = ref && typeof ref === "object" ? ref.$stream : typeof ref === "string" ? ref : /^[0-9a-f]{64}$/i.test(label) ? label : null;
return typeof raw === "string" ? raw.split(":")[0].slice(-64) : null;
};
const outputIds: string[] = [];
const incomingIds: string[] = [];
for (const label of Object.keys(outputs)) {
const id = toId(label, outputs[label]);
if (!id) continue;
outputIds.push(id);
if (incomingOnly === "all-outputs" || incomingOnly.indexOf(label) !== -1) incomingIds.push(id);
}
for (const id of Object.keys(loaded)) {
const activity = loaded[id];
if (!activity || typeof activity.getState !== "function") continue;
const signed = typeof activity.hasSignature === "function" && activity.hasSignature();
const incoming = !signed && outputIds.indexOf(id) !== -1 && incomingIds.indexOf(id) !== -1;
const refusal = this.refuseRecoveredIdentity(activity.getState(), !incoming);
if (refusal) return refusal;
}
return null;
}/** The `evmNetworks` fields this contract stores and reads (evm-registry block). */
private evmFieldSpec(): {required: string[]; optional: string[]}/**
* A registry bucket for a chain from this contract's own `evmNetworks` data,
* spelled as the ledger code upper-cased - the form every
* NETWORKS entry already takes ("TBNB" for tBNB) and the one
* toRegistryNetworkKey (packages/network-codes) looks tokens up under. The
* constant chains are not added here; NETWORKS stays exactly as it was.
* Adding a token needs the chain ENABLED; updating or disabling one already
* registered needs only the entry, so a switched-off chain's tokens can
* still be disabled.
*/ private isEvmDataNetwork(network: string, requireEnabled: boolean): boolean {
const stored = this.evmStoredNetworks();
const key = network.toLowerCase();
if (Object.keys(stored).indexOf(key) === -1) {
return false;
}
this.assertEvmNetworkEntry(key, stored[key]);
return (stored[key].enabled === true || !requireEnabled) && stored[key].ledger.toUpperCase() === network;
}/** * True when one of the contract stream's authorities has `public` equal to * `identity` (voteMod passes the signing identity's stream id). */
private hasContractOwnership(contract: any, identity: string): boolean {
return contract.getAuthorities().some((v: any) => v.public === identity);
}/** * Owner-only `mod` (the contract's owner, not the registry stream's): * writes this contract's `evmNetworks`. The whole map is validated first; * one bad field refuses the write. */
private async voteMod(): Promise<boolean> {
if (!this.transactions.$o || !this.transactions.$o.contract) {
throw "Missing Contract Output";
}
const contract = this.getActivityStreams(this.transactions.$o.contract);
if (this.transactions.$contract.substring(0, 64) !== contract.getId()) {
throw "Contract Not Matching";
}
const modId = this.getActivityStreams(this.transactions.$i.owner).getId();
if (!this.hasContractOwnership(contract, modId)) {
throw "No Contract Authority";
}
this.assertEvmNetworks(this.transactions.$i.owner.evmNetworks);
return true;
}/** `mod` commit: stores `evmNetworks` (replaced whole, else kept), `umid` and `updated`. */
private async commitMod(): Promise<boolean> {
const wrapper: any = this.getContractData();
const cd: any = wrapper && wrapper.data ? wrapper.data : {};
// Replaced whole, never merged here: the write script merges first.
cd.evmNetworks = this.transactions.$i.owner.evmNetworks ?? cd.evmNetworks ?? null;
cd.umid = this.umid;
cd.updated = this.cDate;
this.setContractData(cd);
return true;
}/** The chains known before contract data existed. Returned fresh, never shared. */
private evmConstants(): {[code: string]: any}/** Codes of the non-EVM chains, in every spelling a contract sees. Never an `evmNetworks` key. */
private evmNonEvmCodes(): string[] {
return ["trx", "trx-nile", "niles", "trx-shasta", "shasta", "sol", "soldev"];
}/** This contract's stored `evmNetworks` map ({} when unset). Throws when it is not an object. */ private evmStoredNetworks(): {[code: string]: any}/** * The chain facts for `code` (any casing of the canonical or ledger code), * with `code` set to the lower-case key; null when `code` is not an EVM chain * this contract knows. Throws when the stored entry for it is malformed. */
private evmNetworkData(code: string): any | null {
const raw = String(code === undefined || code === null ? "" : code);
// ASCII only, checked BEFORE lower-casing: toLowerCase folds some non-ASCII
// letters onto ASCII ones (the Kelvin sign U+212A becomes "k"), which would
// let a look-alike spelling reach a real chain's entry.
if (!/^[A-Za-z0-9-]+$/.test(raw)) {
return null;
}
const key = raw.toLowerCase();
if (this.evmNonEvmCodes().indexOf(key) !== -1) {
return null;
}
const stored = this.evmStoredNetworks();
if (Object.keys(stored).indexOf(key) !== -1) {
this.assertEvmNetworkEntry(key, stored[key]);
if (stored[key].enabled === true) {
return {...stored[key], code: key};
}
}
const constants = this.evmConstants();
if (Object.keys(constants).indexOf(key) !== -1) {
return {...constants[key], code: key};
}
return null;
}/** evmNetworkData, failing closed. */
private requireEvmNetwork(code: string): any {
const found = this.evmNetworkData(code);
if (!found) {
throw `Unknown EVM network ${code}`;
}
return found;
}/** * The `mod` validator for a whole `evmNetworks` map. Absent (undefined/null) * leaves the stored map alone. One bad field refuses the whole write. */
private assertEvmNetworks(value: any): void {
if (value === undefined || value === null) {
return;
}
if (typeof value !== "object" || Array.isArray(value)) {
throw "evmNetworks must be an object keyed by canonical network code";
}
const byChainId: {[chainId: string]: string} = {};
for (const code of Object.keys(value)) {
this.assertEvmNetworkEntry(code, value[code]);
const chainId = String(value[code].chainId);
if (Object.keys(byChainId).indexOf(chainId) !== -1) {
throw `evmNetworks: chain id ${chainId} is used by both ${byChainId[chainId]} and ${code}`;
}
byChainId[chainId] = code;
}
const constants = this.evmConstants();
for (const code of Object.keys(constants)) {
const chainId = String(constants[code].chainId);
if (Object.keys(byChainId).indexOf(chainId) !== -1 && byChainId[chainId] !== code) {
throw `evmNetworks.${byChainId[chainId]}: chain id ${chainId} belongs to ${code}`;
}
}
}/** One `evmNetworks` entry, against this contract's evmFieldSpec. */
private assertEvmNetworkEntry(code: string, entry: any): void {
if (typeof code !== "string" || !/^[a-z][a-z0-9-]{1,15}$/.test(code)) {
throw `evmNetworks: ${code} is not a canonical network code`;
}
if (this.evmNonEvmCodes().indexOf(code) !== -1) {
throw `evmNetworks: ${code} is not an EVM network`;
}
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
throw `evmNetworks.${code} must be an object`;
}
const spec = this.evmFieldSpec();
const fields = Object.keys(entry);
for (const field of fields) {
if (spec.required.indexOf(field) === -1 && spec.optional.indexOf(field) === -1) {
throw `evmNetworks.${code}.${field} is not a field this contract uses`;
}
}
for (const field of spec.required) {
if (fields.indexOf(field) === -1) {
throw `evmNetworks.${code}.${field} is required`;
}
}
if (typeof entry.ledger !== "string" || !/^[A-Za-z][A-Za-z0-9-]{1,15}$/.test(entry.ledger) || entry.ledger.toLowerCase() !== code) {
throw `evmNetworks.${code}.ledger must spell ${code} in the ledger's own casing`;
}
if (typeof entry.chainId !== "number" || !Number.isSafeInteger(entry.chainId) || entry.chainId <= 0) {
throw `evmNetworks.${code}.chainId must be a positive integer`;
}
if (typeof entry.enabled !== "boolean") {
throw `evmNetworks.${code}.enabled must be true or false`;
}
const constants = this.evmConstants();
if (Object.keys(constants).indexOf(code) !== -1 &&
(entry.ledger !== constants[code].ledger || entry.chainId !== constants[code].chainId)) {
throw `evmNetworks.${code} must keep ledger code ${constants[code].ledger} and chain id ${constants[code].chainId}`;
}
if (fields.indexOf("rpc") !== -1) {
const rpc = entry.rpc;
if (!Array.isArray(rpc) || rpc.length < 1 || rpc.length > 4) {
throw `evmNetworks.${code}.rpc must list 1 to 4 URLs`;
}
for (const url of rpc) {
if (
typeof url !== "string" ||
url.length > 200 ||
!/^https:\/\/[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+(:[0-9]{1,5})?(\/[A-Za-z0-9._~-]+)*\/?$/.test(url)
) {
throw `evmNetworks.${code}.rpc: ${url} is not a plain https URL`;
}
// Contract data is public: a keyed provider URL (Alchemy /v2/<key>,
// Infura /v3/<key>, QuickNode /<token>/) must never land here.
const urlPath = url.slice(8).indexOf("/") === -1 ? "" : url.slice(8 + url.slice(8).indexOf("/"));
if (/[A-Za-z0-9_-]{24,}/.test(urlPath)) {
throw `evmNetworks.${code}.rpc: ${url} looks like it carries an API key`;
}
}
}
if (fields.indexOf("gasLimits") !== -1) {
const limits = entry.gasLimits;
if (!limits || typeof limits !== "object" || Array.isArray(limits)) {
throw `evmNetworks.${code}.gasLimits must be {native, token, cancel}`;
}
const names = Object.keys(limits);
if (names.length !== 3 || names.indexOf("native") === -1 || names.indexOf("token") === -1 || names.indexOf("cancel") === -1) {
throw `evmNetworks.${code}.gasLimits must be {native, token, cancel}`;
}
for (const name of names) {
const units = limits[name];
if (typeof units !== "number" || !Number.isSafeInteger(units) || units < 21000 || units > 5000000) {
throw `evmNetworks.${code}.gasLimits.${name} must be an integer from 21000 to 5000000`;
}
}
}
for (const field of ["gasPriceCap", "l1FeeCap"]) {
if (fields.indexOf(field) !== -1 && (typeof entry[field] !== "string" || !/^[1-9][0-9]{0,29}$/.test(entry[field]))) {
throw `evmNetworks.${code}.${field} must be a positive integer string (wei)`;
}
}
}/** * The hash of the key that signed for this identity - `sigs` is keyed by * stream id, and a Varnir transaction carries one signature per input. */
private signingKeyHash(stream: any): string | null {
const currentAuth = (this as any).sigs?.[stream.getId()];
if (!currentAuth) {
return null;
}
const keys = Object.keys(currentAuth);
return keys.length ? keys[0] : null;
}/** * The label on the authority that signed this transaction - "read" or * null if it cannot be matched. Stake alone cannot distinguish a * read-only key once its stake is repurposed as pure voting weight; the * label is what a Varnir.Keys read key carries. */
private signingKeyLabel(stream: any): string | null {
const hash = this.signingKeyHash(stream);
if (!hash) {
return null;
}
const authority = stream
.getAuthorities()
.find((candidate: any) => candidate.hash === hash);
const label = authority?.label;
return label ? String(label).toLowerCase().trim() : null;
}/** * Whether the key that signed for `stream` is a read-only * (customer-service tier) key. Label-first, with the legacy stake-9000 * check OR'd in as a fail-safe for authorities that predate labels - one * method so both read gates in this contract cannot drift apart. */
private isReadOnlyKey(stream: any): boolean {
return (
this.signingKeyLabel(stream) === "read" || this.hasAuthorityStake(9000, stream)
);
}/** * Exactly one key signed for `stream` in this transaction, and it is a live owner key: stake exactly 100, not * expired, not labelled read, offledger or verifier. hasAuthorityStake(100) SUMS the stake of every key that signed, * and the engine accepts several signatures for one input, so two stake-80 co-sign keys signing together pass it * (docs/tenancy/legacy-read-key-audit.md). Reads only this.sigs and the authorities already loaded. */
private isSingleOwnerKey(stream: any): boolean {
const signed = (this as any).sigs && (this as any).sigs[stream.getId()];
const hashes = signed ? Object.keys(signed) : [];
if (hashes.length !== 1) return false;
const a = (stream.getAuthorities() || []).find((x: any) => x.hash === hashes[0]);
if (!a || a.stake !== 100) return false;
// As the engine's isAuthorityExpired and Swap's liveAuthority: `expire: null` (read as the epoch) is expired.
if (a.expire !== undefined) {
const t = new Date(a.expire).getTime();
if (Number.isNaN(t) || !(t > new Date(this.cDate).getTime())) return false;
}
const label = a.label ? String(a.label).toLowerCase().trim() : null;
return label !== "read" && label !== "offledger" && label !== "verifier";
}