diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0a99991..d2c7440 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -7,8 +7,11 @@ Thanks for helping improve the Superhero developer docs. 1. `pnpm install` and `pnpm dev` to preview at http://localhost:3000. 2. Run `python3 scripts/lint-mdx.py`. It must report 0 issues. MDX errors break the whole build. 3. Every fact (an address, an endpoint, a fee, a parameter) must trace to source: the - `superhero-com/superhero` web app, `superhero-com/superhero-agent-skill`, or the live API at - `api.superhero.com`. Link the source in your pull request. + `superhero-com/superhero` web app, `superhero-com/superhero-agent-skill`, + `superhero-com/superhero-api`, or the live API at `api.superhero.com`. For chain-level + behavior, use the relevant æternity protocol, Sophia, SDK, AEX or middleware source listed + in [README.md](./README.md#where-the-content-comes-from). Link the source and its release or + commit in your pull request, and distinguish upstream behavior from production behavior. 4. New pages go in the right folder and in that folder's `_meta.json`. ## Writing style diff --git a/README.md b/README.md index e2a952d..e35d6a1 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,8 @@ # Superhero developer docs -The developer documentation for [Superhero](https://superhero.com), the on-chain attention -market where you can discover, trade, and govern the trends you believe in. +Developer documentation for [Superhero](https://superhero.com), a social application and +community-token market on the æternity blockchain. It covers the REST API, Sophia smart +contracts, wallet integrations and agent tools, with user guides for context. Built with [Nextra](https://nextra.site) (docs theme, `pages/` router). @@ -14,12 +15,12 @@ pnpm build # production build ``` > **Note on dependencies:** the Nextra versions are pinned to the `2.x` line, which is the -> line that supports this repository's `pages/` + `_meta.json` layout. `nextra@latest` now -> resolves to the 4.x line, which requires the App Router and a different meta format, so -> do not "upgrade" these specifiers without migrating the whole site first. +> line that supports this repository's `pages/` + `_meta.json` layout. Moving to a newer major +> version requires checking its router and metadata requirements and migrating the site. > > `pnpm-lock.yaml` is committed and resolved against those pinned versions, so -> `pnpm install --frozen-lockfile` (the default on Vercel and most CI) works as-is. +> use `pnpm install --frozen-lockfile` for a reproducible local dependency install. The current +> GitHub Pages workflow uses `npm install` and does not consume the pnpm lockfile. ### Deployment @@ -75,12 +76,12 @@ pages/ ## Editing Every page follows the same shape: double-quoted `title` and `description` frontmatter, an H1, -one to three sentences of opening prose, task-oriented sections, and a `## Read more` section of -internal links. Plain MDX only, with no imports and no components. +one to three sentences of opening prose, task-oriented sections, and a `## Related` section of +links. Plain MDX only, with no imports and no components. -Five things break the build, and `scripts/lint-mdx.py` catches all of them: unquoted -frontmatter, a bare `{` or `<` in prose, a `|` inside inline code inside a table row, a broken -internal link, and a page missing from its directory's `_meta.json`. Run it before every push. +`scripts/lint-mdx.py` checks frontmatter, bare MDX braces and JSX hazards, table pipes, +imports and exports, internal links, static assets, and `_meta.json` entries. Run it before +every push, then run `pnpm build` to check compilation and static export. ## Where the content comes from @@ -89,9 +90,18 @@ internal link, and a page missing from its directory's `_meta.json`. Run it befo | `superhero-com/superhero` | The web app: routes, features, `src/config.ts` endpoints and addresses, the FAQ copy in `server/lib/faq-content.cjs`, the landing copy in `src/locales/en.json`, and the full technical whitepaper in `src/views/Whitepaper.tsx` | | `superhero-com/superhero-agent-skill` | The AI agent skill: `SKILL.md`, the task guides in `guides/`, the CLI scripts in `scripts/`, and the vendored contract ACIs in `contracts/` | | `api.superhero.com` | The live REST API, inventoried in `superhero/docs/api-superhero-com-endpoints-and-fields.md` | - -Facts in these docs should trace back to one of those. Do not write economic parameters, -addresses or endpoints from memory. +| [`superhero-com/superhero-api`](https://github.com/superhero-com/superhero-api) | API controllers, authentication, validation and rate-limit guards | +| [`aeternity/docs`](https://github.com/aeternity/docs) | The developer documentation hub, aggregating documentation from ecosystem repositories | +| [`aeternity/protocol`](https://github.com/aeternity/protocol) | Protocol rules for transactions, API encoding, AENS and state channels | +| [`aeternity/aesophia`](https://github.com/aeternity/aesophia) | Sophia language rules, standard library and compiler documentation | +| [`aeternity/aepp-sdk-js`](https://github.com/aeternity/aepp-sdk-js) | JavaScript SDK APIs, account handling, signing and transaction options | +| [`aeternity/AEXs`](https://github.com/aeternity/AEXs) | Application standards, including AEX-9 tokens and AEX-10 wallet derivation | +| [`aeternity/ae_mdw`](https://github.com/aeternity/ae_mdw) | Middleware routes, indexed data and API specifications | + +Facts in these docs should trace back to the relevant implementation or specification. Use +Superhero sources for application behavior and æternity sources for chain behavior. Record the +release or commit when behavior depends on a version; an upstream branch may differ from +production. Do not write economic parameters, addresses or endpoints from memory. ## Contributing diff --git a/pages/aeternity/accounts-and-keys.mdx b/pages/aeternity/accounts-and-keys.mdx index dade261..838e262 100644 --- a/pages/aeternity/accounts-and-keys.mdx +++ b/pages/aeternity/accounts-and-keys.mdx @@ -1,18 +1,19 @@ --- title: "Accounts & Keys" -description: "Every æternity address prefix, the Ed25519 keypair behind an account, and the secret-key encoding the SDK expects." +description: "Common æternity identifier prefixes, the Ed25519 keypair behind an account, and the secret-key encoding the SDK expects." --- # Accounts & Keys -Every identifier on æternity carries a two-letter prefix that says what it is: a token sale -address is a `ct_`, a wallet is an `ak_`, a trade receipt is a `th_`. +Encoded æternity identifiers carry a two-letter prefix that identifies their type: a token sale +has a `ct_` contract address, an account has an `ak_` address, and a trade transaction has a +`th_` hash. A wallet manages accounts and keys; it is not itself an address. ## Address prefixes Identifiers are a raw byte array, base-encoded, with a prefix describing what the bytes are. -Base58 with a checksum is used for short identifiers meant to be read and pasted; base64 for -longer binary payloads. +Base58Check is used for short identifiers meant to be read and pasted; base64 with a checksum +is used for longer binary payloads. ### Base58: the ones you paste @@ -23,7 +24,7 @@ longer binary payloads. | `th_` | Transaction hash | Trade and post receipts; what you paste into an explorer | | `kh_` | Key-block hash | Block references in explorer links | | `mh_` | Micro-block hash | Block references in explorer links | -| `sg_` | Signature | Delegated-posting payloads, address-link claims | +| `sg_` | Encoded signature | Returned by the SDK's `signTypedData` and `signDelegation` and by the wallet `unsafeSign` RPC; `signMessage` returns raw bytes, and AddressLink REST submit requires 128-character hex | | `nm_` | Name (AENS) | The on-chain object behind a `.chain` name | | `cm_` | Commitment | The salted preclaim hash in AENS registration | | `ok_` | Oracle public key | Not used by Superhero | @@ -60,7 +61,8 @@ contracts verify with `Crypto.verify_sig`. ### Secret-key encoding -Superhero's tooling uses `@aeternity/aepp-sdk` v14. From v14, `MemoryAccount` takes the secret +The Superhero agent skill pins `@aeternity/aepp-sdk` v14; the web app, API and Superhero Wallet +use v15. From v14, `MemoryAccount` takes the secret key as an `sk_`-prefixed encoded 32-byte secret, not raw hex. The web app's built-in wallet normalises older persisted values (raw hex, or a longer keypair payload) by taking the first 32 bytes and encoding them as `sk_`. The agent skill does not: it passes `AE_PRIVATE_KEY` straight diff --git a/pages/aeternity/ae-and-gas.mdx b/pages/aeternity/ae-and-gas.mdx index 0206a99..43783b3 100644 --- a/pages/aeternity/ae-and-gas.mdx +++ b/pages/aeternity/ae-and-gas.mdx @@ -6,8 +6,8 @@ description: "The native coin, the 10^18 aetto conversion, and what a transactio # AE & Gas AE is æternity's native coin. It pays for gas, it is the base currency of every bonding curve, -and it is what a tip is denominated in. Most integration bugs in this ecosystem are unit bugs, so -start here. +and tips are denominated in it. Check units before passing amounts between the API, SDK and +contracts. ## 1 AE = 10^18 aettos @@ -18,16 +18,17 @@ An **aetto** (plural *aettos*) is the smallest unit of AE: 1 aetto = 0.000000000000000001 AE = 10^-18 AE ``` -**Every amount crossing a chain boundary is in aettos.** Node balances, contract call `amount` -options, bonding-curve prices, event arguments: all aettos, all integers. AE is a presentation -format. +**Native AE amounts use aettos at the protocol level.** Node balances and contract-call values +are integers in aettos. Token balances use the token's own decimal units, and other contract +arguments and event fields use the units defined by their interface. SDK amount options can +also accept AE when you explicitly set the denomination. ### Convert safely Never use JavaScript floating point for this. `10^18` is past `Number.MAX_SAFE_INTEGER` (about -`9.007 × 10^15`), so a balance held as a `Number` silently loses precision. Use `BigNumber` or -`BigInt` for every value you send or receive, and divide by `1e18` with a plain `Number` only for -display. +`9.007 × 10^15`), so a balance held as a `Number` can lose precision. Use `BigInt` for integer +arithmetic and a decimal library such as `BigNumber` for conversion and display. Keep the +result as a string until you pass it to the UI or SDK. ```js import BigNumber from 'bignumber.js'; @@ -66,19 +67,17 @@ An æternity transaction has two separate charges: | Charge | Applies to | How it is set | | --- | --- | --- | | `fee` | Every transaction | Size- and type-dependent base fee; the SDK computes it | -| gas | Contract create and contract call transactions | `gasLimit` × `gasPrice`, charged on top of `fee` | +| gas | Contract create and contract call transactions | `gasUsed` × `gasPrice`, charged on top of `fee`; capped by `gasLimit` × `gasPrice` | -Gas is charged on top of `fee`, up to the limit in the transaction. At a routine 5M gas limit -that ceiling is around thirty times the fee, so the Superhero wallet shows a separate -"Gas, at most" row, computed as `gasLimit × gasPrice`. When you approve a contract call, that -row, not "Network fee", is your worst case. +The wallet's "Gas, at most" row is `gasLimit × gasPrice`. Add the transaction `fee` to get the +maximum network charge. Any AE transferred to the contract is a separate amount. ### Gas price -`gasPrice` is quoted in aettos per unit of gas. The SDK's default follows network demand, using -the consensus minimum the node reports as the floor and `1e9` aettos (1 Gaetto) per gas unit as -the fallback when the node does not report one. Under load, the same call costs more for the same -`gasUsed`. +`gasPrice` is quoted in aettos per unit of gas. SDK v14.1.0 uses a minimum of `1e9` aettos +(1 Gaetto) per gas unit. Its default estimation reads the node's recent gas prices and can +increase the price under load. A higher `gasPrice` increases the cost for the same `gasUsed`. +Later SDK releases can use different estimation rules. Worked example at the floor price, for a contract deploy: @@ -88,22 +87,23 @@ gasPrice 1 000 000 000 aettos max gas = 76 000 × 1e9 = 7.6e13 aettos = 0.000076 AE ``` -A contract call typically carries a `gasLimit` of 5 000 000. - -Superhero does not override the SDK's gas defaults: no contract call in the web app sets -`gasPrice` or `gasLimit`, so a call that runs out of gas does so at the SDK's default limit. +The SDK normally estimates `gasLimit` with a dry-run. Inspect the estimate for the specific +call rather than assuming every contract call uses a fixed limit. See +[Calling contracts](/contracts/calling-contracts) for setting an explicit limit. ### Running out of gas Gas is debited up front: the protocol subtracts `gas × gas_price` from the caller before -execution, then refunds the unused portion and pays the used portion to the miner. A call that -exhausts its `gasLimit` refunds nothing: the transaction is still mined, the state change is -rolled back, and you pay the full limit. A generous `gasLimit` costs nothing when the call -succeeds and everything when it does not. +execution, then refunds the unused portion and pays the used portion to the miner. A successful +call, or one that reverts through `abort` or `require` (return type `revert`), is charged only +the gas it used. Any other failure (return type `error`: running out of gas, an arithmetic or +type error, value sent to a non-payable entrypoint, a reentrant call) is charged the full gas +limit. Either way a failed transaction is still mined, its state change is rolled back, and you +pay the transaction fee. ## Transactions per Superhero action -Each transaction pays gas at the network's current gas price: +Every transaction pays a transaction fee; contract execution also consumes gas: | Action | Transactions | | --- | --- | @@ -113,7 +113,7 @@ Each transaction pays gas at the network's current gas price: | Revoke a vote | 1 | | Delegate / revoke delegation | 1 | | Create a governance poll | 2 | -| Create a token | 1, plus any initial buy | +| Create a token | 1, including any initial buy | | Redeem an invitation | 1 | The agent skill confirms a balance of **at least 0.01 AE** before doing anything on chain. @@ -137,7 +137,7 @@ AE. ## Related - [Fees & slippage](/tokens/fees-and-slippage): the protocol fees layered on top of gas when you trade. -- [Curve parameters & units](/tokens/curve-parameters): where aettos meets bonding-curve math. +- [Curve parameters & units](/tokens/curve-parameters): where aettos meet bonding-curve math. - [Accounts & Keys](/aeternity/accounts-and-keys): the account these balances belong to. - [Fund your wallet](/getting-started/fund-wallet): the practical route to a funded account. - [SDK transaction options](https://github.com/aeternity/aepp-sdk-js/blob/develop/docs/transaction-options.md): `gasLimit`, `gasPrice`, `fee` and their defaults. diff --git a/pages/aeternity/aens.mdx b/pages/aeternity/aens.mdx index 2c72efc..69f87cc 100644 --- a/pages/aeternity/aens.mdx +++ b/pages/aeternity/aens.mdx @@ -25,18 +25,19 @@ claim screen, another æternity wallet, or `@aeternity/aepp-sdk` directly. ## Register a name: preclaim, then claim -Registration is two transactions in two different blocks. +The preclaim-and-claim flow uses two transactions at different key-block heights. 1. **Preclaim.** Pick a random salt, hash it together with the name, and publish only the hash as a commitment (`cm_…`). The name itself is not in this transaction, so nobody watching the mempool learns what you are claiming. -2. **Claim.** In a *later* block, publish the name and the salt. The protocol recomputes the +2. **Claim.** At a *later* key-block height, publish the name and the salt. The protocol recomputes the hash, matches it against your commitment, and awards the name or opens an auction. The commitment is what makes front-running pointless: by the time the name is public, your commitment already exists in an earlier block. Three protocol rules constrain the pair: -- The claim must not be in the same block as its preclaim, and must follow within **300 blocks**. +- The claim must land at a later key-block height than its preclaim, within **300 key blocks**. + A later micro block at the same key-block height is not enough. - Only the **first** claim has to be signed by the key that made the preclaim. A later claim in the same auction is a bid from anyone, and from Lima it must carry `name_salt = 0`. - From **Ceres** the preclaim is optional: a claim with `name_salt = 0` can open an auction or @@ -47,9 +48,9 @@ The agent CLI waits for the block height to advance after the preclaim is mined, then adds a third transaction, a `NameUpdateTx` pointing the name at your wallet: ```bash -node scripts/superhero-name.mjs available myagentname # check first -node scripts/superhero-name.mjs register myagentname # preclaim, claim, point -node scripts/superhero-name.mjs resolve myagentname.chain +node scripts/superhero-name.mjs available myagentname123 # check first +node scripts/superhero-name.mjs register myagentname123 # preclaim, claim, point +node scripts/superhero-name.mjs resolve myagentname123.chain ``` A freshly claimed name points nowhere until that update lands. Claiming and pointing are separate @@ -57,7 +58,7 @@ protocol operations. ## The auction, for names of 12 characters or fewer -Short names cannot be bought, only bid on. +Registering an available short name requires an auction. - **Format:** first-price auction. The highest bid at close pays what it bid and takes the name. - **Starting bid:** scales with length, steeply. See the table below. @@ -73,10 +74,11 @@ Short names cannot be bought, only bid on. | 1 to 4 | 29,760 blocks | 2,400 blocks | ~62 days, now ~5 days | Before Ceres a bid restarted the full timeout. From Ceres a bid extends the auction **by up to -120 key blocks**: there are always at least 120 generations (roughly six hours) left to outbid +240 key blocks**: there are always at least 240 generations (roughly twelve hours) left to outbid after any successful bid, so the end moves only when it would otherwise fall inside that window. -A one-to-four-character auction is a 2,400-block race from the opening claim, with a six-hour -floor after each bid. +A one-to-four-character auction is a 2,400-block race from the opening claim, with a twelve-hour +floor after each bid. The AENS protocol specification still gives 120; the node that mainnet +runs uses 240. A bid is a claim transaction on a name that already has an auction running; it needs no preclaim of its own and may come from any account. Nothing settles until the window elapses with no higher @@ -115,8 +117,8 @@ The values are Fibonacci numbers running backwards from length 31: private key, on top of the ordinary transaction fee. It does not go to a miner. In code, call the SDK rather than transcribing the table. `getMinimumNameFee` implements the -length-to-fee function, including the punycode measurement and the 31-character clamp, and stays -correct across a hard fork that changes the coefficients: +length-to-fee function, including the punycode measurement and the 31-character clamp. Use +an SDK version whose fee rules match the network: ```js import { getMinimumNameFee, computeBidFee } from '@aeternity/aepp-sdk'; @@ -158,15 +160,17 @@ A name is a lease, not a purchase. 50,000 (roughly 100 days). - Extending is a `NameUpdateTx`. No additional name fee is required; you pay only the transaction fee. -- Let it lapse and the name becomes claimable by anyone. There is no ownership memory. +- After expiry, the name passes through the protocol's revoked state before becoming + claimable again. Previous ownership does not reserve it for you. ```bash -node scripts/superhero-name.mjs extend myagentname.chain +node scripts/superhero-name.mjs extend myagentname123.chain ``` -Superhero surfaces the expiry it knows about in the claim status (`expires_at` / -`approximate_expire_time`), and the AddressLink contract stores a chain name together with an -expiration timestamp (see [AddressLink](/contracts/address-link)). +The claim-status response carries no expiry. AddressLink stores the preferred name as a link +value; it does not store or automatically follow its AENS expiry. Check current ownership and +expiry through AENS, for example the middleware's `GET /v3/names/{name}.chain` +(`expire_height`, `approximate_expire_time`); see [Chain Names](/identity/chain-names). ## Read names without a wallet diff --git a/pages/aeternity/aex-standards.mdx b/pages/aeternity/aex-standards.mdx index 28d23cb..19a2946 100644 --- a/pages/aeternity/aex-standards.mdx +++ b/pages/aeternity/aex-standards.mdx @@ -12,16 +12,19 @@ standard, and touches a few others through its wallet stack. ## AEX-9: fungible tokens Every Superhero community token and the ProtocolDAO token is an AEX-9 contract. That is why a -token you mint on Superhero shows up in any æternity wallet and on [æScan](https://aescan.io/) -without Superhero having to integrate with them. +token can be read by compatible æternity wallets, middleware and explorers such as +[æScan](https://aescan.io/) through a shared interface. Discovery and display still depend +on the client and its indexer. AEX-9 is inspired by ERC-20 but deliberately smaller: the base interface is the read functions plus `transfer`, and everything else (allowances, minting, burning, swapping) is an optional extension. A contract advertises which extensions it implements through `aex9_extensions()`. -### The interface +### The Superhero token interface -Non-stateful entrypoints can be dry-run for free; stateful ones need a signed transaction. +The tables below describe Superhero's full token implementation, including optional +extensions. They are not the minimum interface every AEX-9 token must implement. Dry-runs +simulate calls without network fees; persisting changes requires a signed transaction. **Reads** @@ -36,7 +39,7 @@ Non-stateful entrypoints can be dry-run for free; stateful ones need a signed tr | `allowance(accounts)` | `option(int)` | Keyed on a from/for pair | | `allowance_for_caller(from)` | `option(int)` | Convenience for the common case | | `allowances()` | map | Every allowance at once | -| `swapped()` | map of address to int | Migration bookkeeping | +| `swapped()` | map of address to int | Amounts burned through `swap()` | **Writes (all stateful)** @@ -49,8 +52,8 @@ Non-stateful entrypoints can be dry-run for free; stateful ones need a signed tr | `transfer_allowance(from, to, value)` | allowance | Spend someone else's authorised balance | | `mint(account, value)` | mintable | Owner only | | `burn(value)` | burnable | Destroy your own | -| `swap()` | swappable | Migrate a legacy balance | -| `check_swap(account)` | swappable | Inspect a migration | +| `swap()` | swappable | Burn your entire balance and record it in `swapped`; pays nothing | +| `check_swap(account)` | swappable | Read the amount recorded by `swap()` | `init(name, decimals, symbol, initial_owner_balance)` is the deploy-time constructor; `initial_owner_balance` is an `option(int)`. @@ -99,10 +102,11 @@ The middleware indexes AEX-9 holdings, so a wallet view needs one paged request contract call per token: ```text -GET /v2/aex9/account-balances/ak_...?limit=100 +GET /v3/accounts/ak_.../aex9/balances?limit=100 ``` -Note the `v2`: the AEX-9 balance route is on middleware v2, while transaction lookups use `v3`. +The older v2 form, `/v2/aex9/account-balances/ak_...`, returns the same data; Superhero's web app +still calls it. See [Networks & Endpoints](/aeternity/networks). ## The other AEX standards @@ -117,8 +121,8 @@ See [Networks & Endpoints](/aeternity/networks). | AEX-130 | æpp meta-information format | Draft | Not used | | AEX-141 | Non-fungible tokens | Review | Not used; Superhero has no NFT feature | -AEX-9's status is Review and nothing supersedes it. Every æternity wallet, explorer and the -middleware's AEX-9 indexing are built against it as written. +AEX-9 is marked Review in the specification and is used by Superhero and the middleware's +token indexing. Check each client's supported extensions rather than assuming universal support. ## Related diff --git a/pages/aeternity/explorers.mdx b/pages/aeternity/explorers.mdx index ec899da..c33c522 100644 --- a/pages/aeternity/explorers.mdx +++ b/pages/aeternity/explorers.mdx @@ -66,8 +66,9 @@ Status · Microblock Hash · Created · Fee · Nonce · API Links the entrypoint and the decoded arguments. - **API Links** gives you the middleware query behind the page. -If the hash returns nothing, the transaction is not on chain yet. Superhero treats a middleware -`404` as "still pending" rather than as an error; wait for a block before concluding anything. +If the hash returns nothing, the middleware has no record of it: the transaction may be pending or +not yet indexed, or it may have been dropped or never broadcast. Superhero's app keeps polling a +middleware `404` as pending; check the node and your submission result before concluding anything. ## Check what a contract call did diff --git a/pages/aeternity/index.mdx b/pages/aeternity/index.mdx index eb24f74..140ca72 100644 --- a/pages/aeternity/index.mdx +++ b/pages/aeternity/index.mdx @@ -28,7 +28,7 @@ handful of chain features, listed below, and the ## In this section - [Why æternity](/aeternity/why-aeternity): the chain properties Superhero depends on. -- [Accounts & Keys](/aeternity/accounts-and-keys): every address prefix, the key type, and the secret-key encoding the SDK expects. +- [Accounts & Keys](/aeternity/accounts-and-keys): the common identifier prefixes, the key type, and the secret-key encoding the SDK expects. - [AE & Gas](/aeternity/ae-and-gas): aettos, the 10^18 conversion, and what transactions cost. - [AENS](/aeternity/aens): preclaim and claim, pointers, expiry, and the short-name auction. - [Sophia & FATE](/aeternity/sophia-and-fate): a Solidity-to-Sophia orientation, and what an ACI is. diff --git a/pages/aeternity/networks.mdx b/pages/aeternity/networks.mdx index 449a84e..a10dab7 100644 --- a/pages/aeternity/networks.mdx +++ b/pages/aeternity/networks.mdx @@ -5,18 +5,24 @@ description: "Mainnet and testnet hosts for the Superhero API, node, middleware, # Networks & Endpoints -Superhero runs on æternity mainnet (`ae_mainnet`) or testnet (`ae_uat`). The network is selected +Superhero can be configured for æternity mainnet (`ae_mainnet`) or testnet (`ae_uat`). The network is selected at build time with `VITE_NETWORK`, and a deployed container can override any individual endpoint at runtime through `window.__SUPERCONFIG__`. ## Endpoints +The table lists network endpoints. There is no public Superhero testnet API or Socket.IO +endpoint: the app's +[`src/config.ts`](https://github.com/superhero-com/superhero/blob/85a6510d0/src/config.ts) +still names a testnet backend URL, but that host does not serve the API. A full testnet +application requires a separately deployed backend. + | | Mainnet (`ae_mainnet`) | Testnet (`ae_uat`) | | --- | --- | --- | -| Superhero API | `https://api.superhero.com` | Not publicly documented | +| Superhero API | `https://api.superhero.com` | No public endpoint documented | | Node | `https://mdw.wordcraft.fun` | `https://testnet.aeternity.io` | | Middleware | `https://mdw.wordcraft.fun/mdw` | `https://testnet.aeternity.io/mdw` | -| WebSocket | `https://api.superhero.com` | Not publicly documented | +| WebSocket | `https://api.superhero.com` | No public endpoint documented | | Compiler | `https://v7.compiler.aepps.com` | `https://v7.compiler.aepps.com` | | Explorer | `https://aescan.io` | `https://testnet.aescan.io` | | Governance API | `https://governance-server-mainnet.prd.service.aepps.com/` | `https://governance-server-testnet.prd.service.aepps.com/` | @@ -47,20 +53,21 @@ GET /v3/transactions/ GET https://mainnet.aeternity.io/mdw/v3/names?owned_by=ak_... ``` -Middleware routes are not all on the same version. Check the call you need: +Common middleware calls: | Call | Path | | --- | --- | | Transaction status | `/v3/transactions/...` | -| AEX-9 account balances | `/v2/aex9/account-balances/...` | +| AEX-9 account balances | `/v3/accounts/.../aex9/balances` (v2 alias: `/v2/aex9/account-balances/...`) | | Owned names | `/v3/names?owned_by=...` | ## Rate limits -`api.superhero.com` allows **10 requests per minute** per client IP and route path, in a fixed -60-second window, and returns HTTP 429 with a `retryAfter` field when you exceed it. The limit -applies to the generic entity endpoints and to the profile, notification-feed and room -endpoints. See [the developer FAQ](/concepts/faq) for what that means for a polling client. +The Superhero backend's guarded routes allow **10 requests per minute** per client IP and +route path in a fixed 60-second window. Exceeding that limit returns HTTP 429 with a +`retryAfter` field. It is not a blanket limit on every API route. See the +[guarded-route list](/api-reference/conventions#guarded-routes) and handle `429` responses +wherever they occur. No limit is documented for the node, middleware, compiler, governance or DEX-backend hosts. Treat them as best-effort, back off on failure, and cache what you can. diff --git a/pages/aeternity/sophia-and-fate.mdx b/pages/aeternity/sophia-and-fate.mdx index b98d677..b95a51e 100644 --- a/pages/aeternity/sophia-and-fate.mdx +++ b/pages/aeternity/sophia-and-fate.mdx @@ -6,7 +6,7 @@ description: "æternity's smart-contract language and the VM that runs it, orien # Sophia & FATE **Sophia** is æternity's smart-contract language: functional, strongly and statically typed, with -no mutable global state. **FATE** (the Fast æternity Transaction Engine) is the virtual machine +contract-local mutable state. **FATE** (the Fast æternity Transaction Engine) is the virtual machine that executes it. Every Superhero contract is written in Sophia and runs on FATE. If you are arriving from Ethereum, most of your instincts transfer. The table covers the ones @@ -19,7 +19,7 @@ that do not. | `contract C` with a body in braces | `contract C =` with an indented body | Layout is significant, like Python or Haskell | | `public` / `external` function | `entrypoint` | Only entrypoints are callable from outside | | `internal` / `private` function | `function` | A local function, invisible off-chain | -| `view` / `pure` | a plain `entrypoint` | Non-stateful is the default | +| `view` / `pure` | a plain `entrypoint` | Closest syntax, but not a guarantee of global purity; see below | | state-mutating function | `stateful entrypoint` | You must opt in; see below | | `payable` | `payable entrypoint` | Contracts are non-payable by default | | `msg.sender` | `Call.caller` | The calling entity, possibly another contract | @@ -38,34 +38,41 @@ that do not. Three differences do real work: -**No mutable global state.** A Sophia contract has exactly one `state` value. A stateful function +**Contract-local mutable state.** A Sophia contract has exactly one `state` value. A stateful function reads it and calls `put` with a new one; there is no assignment to a storage slot anywhere. This -is what reduces the surface for reentrancy and state-corruption bugs. +is the language's state-update model. FATE separately rejects remote calls back into a contract +already executing on the call stack; that runtime check prevents reentrant contract calls. **No floating point.** Sophia omits it. Every price, fee and curve value in Superhero is an integer in aettos or token-decimals. See [AE & Gas](/aeternity/ae-and-gas). **Types are checked, then checked again.** The compiler is strict, and FATE re-checks at runtime: -each FATE operation is typed, and a type mismatch raises an exception that reverts the call. A -malformed call does not corrupt state; it fails. +each FATE operation is typed, and a type mismatch is a runtime error: the call fails with return +type `error`, its state changes are discarded, and it is charged its full gas limit. A malformed +call does not corrupt state; it fails. ## Entrypoint annotations -Three orthogonal properties, all opt-in, all visible in the ACI: +Entrypoints are non-stateful and non-payable by default. The ACI records both flags: | Annotation | Meaning | Omit it and… | | --- | --- | --- | -| (none) | Read-only. Can be dry-run without a transaction. | This is the default | -| `stateful` | May modify contract state, emit events, or call another contract with a non-zero value | The compiler rejects any `put`, any `Chain.event`, any value-carrying call | -| `payable` | May receive coins in the call | Spending to the contract fails outright | +| (none) | Cannot directly update this contract's state; normally called through a dry-run | This is the default | +| `stateful` | May update state, use stateful primitives, or call another contract with a non-zero value | The compiler rejects these operations | +| `payable` | May receive AE through this entrypoint | Calls with a non-zero value fail | + +Emitting an event does not require `stateful`. A non-stateful entrypoint can also call a +stateful entrypoint in another contract with zero value. The flag alone does not prove that +an on-chain call has no effects. `payable` also applies to the contract itself: a contract is non-payable unless declared otherwise, so a plain AE transfer to a `ct_` address fails by default. These map straight onto how you call a contract. A non-stateful entrypoint can be answered by a -dry-run with no transaction, no gas and no wallet prompt. That is how Superhero prices a trade before -you confirm it. A `stateful` entrypoint needs a signed contract-call transaction. A `payable` one -also takes an `amount` option: +dry-run without broadcasting a transaction, paying a network fee or prompting the wallet. +Dry-runs still execute under gas limits, and can also simulate stateful calls. Persisting a +call's effects requires a signed contract-call transaction. To attach AE to a payable call, +pass an `amount` option: ```js // Calling a payable, stateful entrypoint @@ -126,8 +133,8 @@ const ACI = JSON.parse(fs.readFileSync('./contracts/FungibleTokenFull.aci.json', await Contract.initialize({ aci: ACI, address: tokenAddress, onAccount: aeSdk, onNode: aeSdk.api }); ``` -Keep a vendored ACI in step with the deployed contract. A stale ACI does not fail loudly; it -encodes arguments against the wrong signature. +Keep a vendored ACI in step with the deployed contract. A stale ACI can encode arguments or +decode results incorrectly, causing errors or misleading results. The `@compiler >= N` pragma at the top of a `.aes` file is a minimum compiler version, not the version the contract was built with. @@ -137,10 +144,9 @@ version the contract was built with. FATE runs directly on æternity's state tree rather than on a general byte-code machine bolted on top of one. -- **Typed instructions.** Type errors raise an exception and revert, rather than reinterpreting - bytes. -- **A restricted memory model and high-level instructions.** Contracts are smaller and use less - gas than equivalent EVM contracts. +- **Typed instructions.** Type errors fail the call rather than reinterpreting bytes. +- **A restricted memory model and high-level instructions.** æternity's FATE documentation + reports that contracts tend to be smaller than their EVM equivalents. - **Native access to chain features.** AENS names and oracles are reachable from contract code as protocol primitives, not through a precompile. @@ -150,5 +156,5 @@ top of one. - [Calling contracts](/contracts/calling-contracts): using an ACI to make a real call. - [Contract security](/contracts/security): where Sophia's guarantees stop and yours start. - [AEX Standards](/aeternity/aex-standards): AEX-9 read from a Sophia ACI. -- [Sophia language features](https://docs.aeternity.com/aesophia/v6.1.0/sophia_features/): the canonical reference for `stateful`, `payable`, state and events. +- [Sophia language features](https://github.com/aeternity/aesophia/blob/master/docs/sophia_features.md): the language reference for `stateful`, `payable`, state and events; use the compiler's matching release for version-specific behavior. - [FATE VM](https://docs.aeternity.com/aeternity-core-concepts/protocol/fast-aeternity-transaction-engine-fate-vm): the official description of the VM. diff --git a/pages/aeternity/state-channels.mdx b/pages/aeternity/state-channels.mdx index e59a62f..0ae5805 100644 --- a/pages/aeternity/state-channels.mdx +++ b/pages/aeternity/state-channels.mdx @@ -5,8 +5,9 @@ description: "æternity's layer-2 mechanism in brief, and that Superhero does no # State Channels -State channels are æternity's layer-2 scaling mechanism: a private, two-party ledger that settles -on chain only at its endpoints. **Superhero does not use them.** Posts, tips, trades and votes are +State channels are æternity's layer-2 scaling mechanism: a two-party ledger whose agreed updates +usually happen off chain. Opening, closing and some other operations use on-chain transactions. +**Superhero does not use them.** Posts, tips, trades and votes are individual on-chain transactions; chat runs on Nostr relays and video calls on Jitsi. ## How a channel works @@ -19,14 +20,15 @@ or waits for a block. **Closing** is on chain again. In the happy path the participants co-sign a final state and settle mutually. If one party disappears or misbehaves, the other can close unilaterally with -`channel_solo_close_tx`, publishing the state they claim is current. If a party publishes an +`channel_close_solo_tx`, publishing the state they claim is current. If a party publishes an *old* state, the counterparty answers with `channel_slash_tx`, supplying a co-signed state with a -higher round number, and `channel_settle` then pays out. The honest party always holds a newer -co-signed state than a cheater can produce, so cheating is unprofitable. +higher round number within the agreed `lock_period`. After that period, `channel_settle_tx` +pays out. Participants must retain the latest signed state and monitor the chain so they can +challenge an outdated closing state in time. -The economics: two on-chain transactions, amortised over as many off-chain updates as the -participants make. A channel used for two updates is worse than doing it on chain; a channel used -for ten thousand is dramatically better. +Opening and mutually closing a channel requires two on-chain transactions. Deposits, +withdrawals, disputes and forced progress can require more. The cost per update depends on +how many updates stay off chain and how often on-chain intervention is needed. ## Superhero and channels diff --git a/pages/aeternity/why-aeternity.mdx b/pages/aeternity/why-aeternity.mdx index 2ea1bc8..c4a2f88 100644 --- a/pages/aeternity/why-aeternity.mdx +++ b/pages/aeternity/why-aeternity.mdx @@ -12,8 +12,9 @@ to the protocol, and lets contracts verify user signatures. æternity provides a ## Affordable on-chain writes æternity keeps each write light enough that every post, comment, tip, trade and vote can be its -own transaction. A post or a comment pays gas only, with no posting fee, and gas price follows -network demand. See [AE & Gas](/aeternity/ae-and-gas) for how a fee is computed. +own transaction. A post or comment pays a network transaction fee and execution gas, with no +additional posting fee. Gas price follows network demand. See [AE & Gas](/aeternity/ae-and-gas) +for how a fee is computed. ## Protocol-level names @@ -24,17 +25,18 @@ is portable rather than Superhero-specific. See [AENS](/aeternity/aens) and ## Native signature verification in contracts -Sophia exposes `Crypto.verify_sig`, and æternity defines a signed-message prefix -(`"aeternity Signed Message:\n"`, with a fixed 28-byte header) that a contract can reconstruct. -Superhero's Tipping and AddressLink contracts hash a message with Blake2b, prepend the prefix -to produce a 60-byte payload, and verify it with `Crypto.verify_sig`. That is what makes -[delegated posting](/social/delegated-posting) possible: a user signs off chain, a relayer pays -the gas, and the contract still attributes authorship to the signer. +Sophia exposes `Crypto.verify_sig`, and æternity defines personal-message framing that a +contract can reconstruct. Tipping v3 hashes the post content to 32 bytes, adds a 28-byte +header containing the signed-message prefix and length bytes, then hashes that 60-byte +payload and verifies its signature. See [the full construction](/contracts/tipping#the-full-construction). +This supports [delegated posting](/social/delegated-posting): a user signs off chain, a +relayer pays the network charges, and the contract attributes authorship to the signer. ## Sophia's safety properties -Sophia is strongly and statically typed with no mutable global state, which reduces the surface -for reentrancy and state-corruption bugs. See [Sophia & FATE](/aeternity/sophia-and-fate) and +Sophia is strongly and statically typed, with contract-local mutable state. FATE rejects +reentrant calls into a contract already executing on the call stack. See +[Sophia & FATE](/aeternity/sophia-and-fate) and [Contract security](/contracts/security). ## AEX-9 as the token standard diff --git a/pages/agents/cli-reference.mdx b/pages/agents/cli-reference.mdx index 4fcd83f..1b21cc1 100644 --- a/pages/agents/cli-reference.mdx +++ b/pages/agents/cli-reference.mdx @@ -299,12 +299,12 @@ from `GET /api/factory` and the first collection in the response is used. ```json // check { "collection": "WORDS-ak_...", "name": "MYTOKEN", "exists": false, - "allowed_name_length": 20, "allowed_chars": "A-Z, 0-9, - (dash)" } + "allowed_name_length": "20", "allowed_chars": "A-Z, 0-9, - (dash)" } // create { "success": true, "token_name": "MYTOKEN", "collection": "WORDS-ak_...", "sale_address": "ct_...", "dao_address": "ct_...", "community_management_address": "ct_...", - "initial_buy_ae": 0.1, "estimated_tokens": "812.41", "tx_hash": "th_..." } + "initial_buy_ae": 0.1, "estimated_tokens": "132247.81", "tx_hash": "th_..." } ``` `allowed_name_length` comes from the collection record; `allowed_chars` is a fixed string diff --git a/pages/agents/creating-tokens.mdx b/pages/agents/creating-tokens.mdx index 845915a..0114ae3 100644 --- a/pages/agents/creating-tokens.mdx +++ b/pages/agents/creating-tokens.mdx @@ -5,7 +5,7 @@ description: "The guarded token-creation workflow, the confirmation wait, and wh # Creating Tokens with an Agent -Creating a token deploys three contracts, takes minutes rather than seconds, and cannot be +Creating a token deploys the community contracts, takes time to confirm, and cannot be undone. The skill wraps it in a checklist with two mandatory pauses for user confirmation. ## The workflow @@ -41,7 +41,7 @@ needs the wallet to be funded. ```json { "collection": "WORDS-ak_...", "name": "MYTOKEN", "exists": false, - "allowed_name_length": 20, "allowed_chars": "A-Z, 0-9, - (dash)" } + "allowed_name_length": "20", "allowed_chars": "A-Z, 0-9, - (dash)" } ``` `allowed_name_length` comes from the collection record returned by `GET /api/factory`. @@ -58,8 +58,10 @@ exposed by `allowed_name_chars(collection_name)`. Mainnet has four collections: | RUSSIAN | 20 | Uppercase Cyrillic U+0410–U+042F plus Ё (U+0401), and the dash | None permits lowercase, and only WORDS permits digits or Latin letters. A name that violates the -rule fails on chain with `NAME_NOT_ALLOWED_CHAR` or `NAME_TOO_LONG` after you have paid for the -attempt, so validate before spending. +rule makes `create_community` abort with `NAME_NOT_ALLOWED_CHAR` or `NAME_TOO_LONG`. The script +sets no `gasLimit`, so the SDK's gas-estimation dry-run fails before signing and nothing is paid; +a caller that sets `gasLimit` itself broadcasts the call and pays for the failed attempt. Validate +first either way. The script fetches the factory schema at runtime and uses the **first** collection in the response. You cannot specify a different one, so the skill creates WORDS tokens. @@ -80,12 +82,13 @@ metadata at creation, call `create_community` yourself with a populated map. See ```json { "success": true, "token_name": "MYTOKEN", "collection": "WORDS-ak_...", "sale_address": "ct_...", "dao_address": "ct_...", "community_management_address": "ct_...", - "initial_buy_ae": 0.1, "estimated_tokens": "812.41", "tx_hash": "th_..." } + "initial_buy_ae": 0.1, "estimated_tokens": "132247.81", "tx_hash": "th_..." } ``` -One transaction, three contracts: the **sale** contract holding the bonding curve and the -reserve, the **DAO** contract receiving the community's share of the spread, and the -**community management** contract governing moderation. See +The result returns three addresses: the **sale** contract holding the reserve, the **DAO** +contract receiving the community's share of the spread, and the **community management** +contract governing moderation. These are not a count of all contracts involved: the sale also +has an AEX-9 token and references the factory's shared bonding curve. See [Community Factory](/contracts/community-factory) and [Token sale](/contracts/token-sale). `sale_address` is the one you need afterwards for buying, selling, transaction history and @@ -98,11 +101,12 @@ the token's page on the app. 1. Estimates the token count client-side by bisecting the integral of the curve's price function, `0.001 * exp(0.00000001 * x) - 0.0009999`. 2. Asks the on-chain bonding curve for the exact price of that token count. -3. Attaches that on-chain price multiplied by **1.05**, a 5% buffer for price drift between - quote and mine. +3. Attaches that on-chain price multiplied by **1.05**. The quote excludes the 0.5% affiliation + fee, so the extra covers the fee and the factory refunds the rest in the same transaction. A + new token starts at supply 0, so there is no price drift. -So `create "MYTOKEN" 0.1` sends roughly 1.05 times the on-chain cost of however many tokens -0.1 AE was estimated to buy. `estimated_tokens` is the client-side estimate; check the real +So `create "MYTOKEN" 0.1` attaches about 1.05 times the curve cost of however many tokens 0.1 AE +was estimated to buy, is charged about 1.005 times that cost, and gets the rest back. `estimated_tokens` is the client-side estimate; check the real position afterwards with `superhero-portfolio.mjs holdings`. Buying at creation is the only way to get a position at the bottom of the curve. If the agent @@ -189,7 +193,7 @@ run returns. | --- | --- | | Gas | around 0.001 AE | | Pre-flight balance | at least 0.01 AE | -| Initial buy | whatever you specify, times roughly 1.05 | +| Initial buy | about 1.005 × the curve cost of the estimated count; the wallet must briefly hold about 1.05× | The factory is `ct_25cqTw85wkF5cbcozmHHUCuybnfH9WaRZXSgEcNNXG9LsCJWTN`. See [Contract addresses](/contracts/addresses). diff --git a/pages/agents/governance.mdx b/pages/agents/governance.mdx index 63548be..908dfca 100644 --- a/pages/agents/governance.mdx +++ b/pages/agents/governance.mdx @@ -196,7 +196,7 @@ A good default: let the agent **read and summarise** polls on a schedule, and no ## Transactions -Each transaction pays gas at the network's current gas price. +Each transaction pays a transaction fee plus execution gas; see [AE & Gas](/aeternity/ae-and-gas). | Action | Transactions | | --- | --- | diff --git a/pages/agents/index.mdx b/pages/agents/index.mdx index 34a63f9..680c3ba 100644 --- a/pages/agents/index.mdx +++ b/pages/agents/index.mdx @@ -10,8 +10,8 @@ network: an identity, a self-custodial wallet, and the ability to post, trade an it into OpenClaw, Claude Code, GitHub Copilot or any runtime that can run `node`, hand the agent one sentence, and it walks itself through setup. -> Post tamperproof content. Own a self-custodial wallet. Trade trending topics and earn real -> money, fully autonomously. +Agent actions use the same contracts and network fees as other clients. Start with a dedicated +wallet and review [Agent Safety & Limits](/agents/safety) before enabling unattended writes. ## What an agent gets diff --git a/pages/agents/posting.mdx b/pages/agents/posting.mdx index 249a288..7ae89db 100644 --- a/pages/agents/posting.mdx +++ b/pages/agents/posting.mdx @@ -26,7 +26,7 @@ array. The call goes to the `Tipping_v3` contract at "links": [], "tx_hash": "th_..." } ``` -Each post pays gas. Check the balance first if the agent has been trading: +Each post pays a transaction fee and gas. Check the balance first if the agent has been trading: ```bash node scripts/superhero-wallet.mjs balance diff --git a/pages/agents/strategies.mdx b/pages/agents/strategies.mdx index 3f59e95..26ecdbe 100644 --- a/pages/agents/strategies.mdx +++ b/pages/agents/strategies.mdx @@ -35,8 +35,10 @@ so it is the same method as moderate with a materially higher hurdle rate. global constants, an absolute floor is directly comparable across tokens. Pair the floor with a relative condition: enter only tokens whose score is higher than at your -previous scan. A rising score means buying pressure is accelerating, and the relative rule -adapts as the platform's overall activity level changes. To calibrate a floor for your own +previous scan. A rising score means activity around the token is rising: trades in either +direction, mentions, comments, tips and reads, with social signals carrying most of the weight. +It is not a buy-pressure signal, so compare buy and sell counts if you need direction. The +relative rule adapts as the platform's overall activity level changes. To calibrate a floor for your own wallet, run `node scripts/superhero-trending.mjs tokens 50`, read the `trending_score` values, and pick a floor within the observed distribution; re-check it periodically. diff --git a/pages/agents/trading.mdx b/pages/agents/trading.mdx index a5b5f49..d5aa031 100644 --- a/pages/agents/trading.mdx +++ b/pages/agents/trading.mdx @@ -8,8 +8,9 @@ description: "The scan, filter, size, enter, monitor, exit loop — and the 1% s The trading loop comes down to one idea: enter tokens whose trending score is rising, size positions as a fraction of balance, and exit when momentum fades. Read [Bonding curves](/tokens/bonding-curve) first: price rises as buyers accumulate and falls as -sellers exit, and there is always a bid because the sale contract holds the reserve to buy the -entire supply back. +sellers exit. The sale contract quotes from supply and pays sellers from its reserve. See +[Reserve accounting and rounding](/concepts/value-flow#reserve-accounting-and-rounding) for the +continuous-model redemption argument and its implementation limits. ## The loop diff --git a/pages/agents/wallet-and-keys.mdx b/pages/agents/wallet-and-keys.mdx index 40dfe8f..363e1d3 100644 --- a/pages/agents/wallet-and-keys.mdx +++ b/pages/agents/wallet-and-keys.mdx @@ -123,7 +123,8 @@ derived from the key, so a new key is a new identity. ``` Selling crosses the 1% spread. For a large position, moving the AEX-9 balance directly with - a wallet or CLI that supports AEX-9 transfers costs only gas. See + a wallet or CLI that supports AEX-9 transfers pays the network transaction fee and gas + without the bonding-curve spread. See [AEX-9 tokens](/wallets/aex9-tokens). 3. **Repoint any `.chain` name while the old key is still set:** diff --git a/pages/api-reference/accounts.mdx b/pages/api-reference/accounts.mdx index 6cbe1e1..217c18b 100644 --- a/pages/api-reference/accounts.mdx +++ b/pages/api-reference/accounts.mdx @@ -47,19 +47,18 @@ curl -s "https://api.superhero.com/api/accounts/ak_2ruXgsLy9jMwEqsgyQgEsxw8chYDf | `links` | object or null | Verified address links, see below | | `profile` | object or null | Profile payload, see [Profile](/api-reference/profile) | | `public_name` | string or null | Resolved display name | -| `x_username` | string or null | Legacy X handle field | `links` holds the current, verified identity: | Key | Meaning | | --- | --- | | `x` | Verified X handle | -| `bio` | Verified bio text | +| `bio` | Self-declared bio text, wallet-signed | | `prefaens` (also `prefered_aens_name`) | Preferred `.chain` name | -| `site` | Verified website | +| `site` | Self-declared website, wallet-signed | `links`, `profile` and the top-level fields are three generations of the same data; read -`links.x`, then `profile.x_username`, then `x_username`, and strip a leading `@`. +`links.x`, then `profile.x_username`, and strip a leading `@`. ## `GET /api/accounts` @@ -240,32 +239,35 @@ height. - **Custom period.** Pass `startDate` **and** `endDate` together. Leaders are ranked by performance in that range among accounts that traded in it, with metrics and buy/sell counts scoped to it. `tradingOnly=true` bases period PnL and ROI on realized token-trading PnL only, - excluding transfer-driven portfolio changes. + excluding transfer-driven portfolio changes. The end must follow the start, and the period + must not exceed 14 days. Supplying both dates selects this path even if `window` is also set. | Parameter | Notes | | --- | --- | | `sortBy` | `pnl`, `roi`, `mdd` or `aum` | | `sortDir` | Defaults to `DESC`, except `sortBy=mdd` which defaults to `ASC` | | `minAumUsd` | Exclude leaders below this USD AUM | -| `page`, `limit` | Standard pagination | -| `points`, `maxCandidates` | Deprecated and ignored | +| `page`, `limit` | Page defaults to 1; limit defaults to 18 and must be 1–50 | +| `points` | Ignored for snapshot windows; custom periods use 2–12 sparkline points, default 8 | +| `maxCandidates` | Ignored for snapshot windows; custom periods default to 100, clamp the requested value to 500, then raise it to at least the page offset plus limit | ```bash curl -s "https://api.superhero.com/api/accounts/leaderboard?window=30d&sortBy=roi&sortDir=DESC&limit=18&page=1" ``` Items carry `address`, `chain_name`, `aum_usd`, `pnl_usd`, `roi_pct`, `mdd_pct`, `buy_count`, -`sell_count`, `volume_usd`, `created_tokens_count`, `owned_trends_count` and -`portfolio_value_usd_sparkline` (an array of `[timestamp, value]` pairs). +`sell_count`, `created_tokens_count`, `owned_trends_count` and `portfolio_value_usd_sparkline` +(an array of `[timestamp, value]` pairs). Custom-period items also carry `volume_usd`, and +report `created_tokens_count` and `owned_trends_count` as `0`. `mdd_pct` is **maximum drawdown as a positive percentage**: the largest `(peak - value) / peak` along the sparkline, times 100. 0 means the portfolio never fell from a peak; larger is worse, which is why `sortDir` defaults to `ASC` for it. `meta` is **not** the standard envelope: `page` (not `currentPage`), `limit`, `totalItems`, -`totalPages`, `window`, `sortBy`, `sortDir` and a `timeFilter` of `value`, `unit`, `start` and -`end`. Snapshot windows are rebuilt every ten minutes; responses are cached for up to 60 -seconds, and `meta.timeFilter.start` / `end` reflect when the cache entry was filled. +`totalPages`, `window`, `sortBy` and `sortDir`. Custom-period responses also carry +`timeFilter: { start, end }` with the requested ISO timestamps; snapshot responses omit it. +Snapshot windows are rebuilt every ten minutes; responses are cached for up to 60 seconds. ## Related diff --git a/pages/api-reference/analytics.mdx b/pages/api-reference/analytics.mdx index 471357e..2ff251e 100644 --- a/pages/api-reference/analytics.mdx +++ b/pages/api-reference/analytics.mdx @@ -32,7 +32,7 @@ All paths are relative to `https://api.superhero.com`. Reads need no authenticat | `GET /api/coins/aeternity/market-data` | `currency` | Market data object | Posting activity has its own set under `/api/posts/analytics*` and referral activity under -`/api/bcl-affiliation/analytics*`. See [Posts](/api-reference/posts) and +`/api/bcl-affiliation/analytics*` (operator session required). See [Posts](/api-reference/posts) and [Invitations & Affiliations](/api-reference/invitations-and-affiliations). Date parameters are snake_case `start_date` / `end_date` in `YYYY-MM-DD` format. @@ -108,7 +108,7 @@ day's end. Do not divide by 1e18. - The range is clamped to **365 days**; a wider `start_date` is moved forward, not rejected. - With neither date, `start_date` and `end_date` both default to today, so you get a single row. -- Each day is an aggregate query; a full year is 365 of them. Cached for 20 seconds. +- Each day is an aggregate query; a full year is 365 of them. May be cached for up to 20 seconds. - `token_sale_addresses` is accepted but the series is always platform-wide. For a per-token series use `GET /api/tokens/{address}/history`. @@ -130,7 +130,7 @@ aettos scale too. `total-unique-users` accepts `token_sale_addresses` (at most 100; more is a 400) to restrict the count to traders of those tokens. Unknown addresses are dropped; if none resolves to a token the -answer is `{ "total_users": 0 }`. Cached for 20 seconds. +answer is `{ "total_users": 0 }`. Not cached. `total-created-tokens` is scoped to the current factory, so it does not match `total_tokens` from `past-24-hours`, which counts every token. @@ -208,12 +208,12 @@ omitting them makes it all-time. | Endpoint | Freshness | | --- | --- | -| `past-24-hours`, `summary` | Computed live on every request | +| `past-24-hours`, `summary` | Computed on request (`past-24-hours` may be cached for up to 60 seconds) | | `analytics` without `force_pull` | Read from the daily table, rebuilt **hourly** (re-pulling the last 7 days each tick) | | `analytics` with `force_pull=true` | Recomputed synchronously for the whole requested range first, which is slow for a wide range | | `analytics` with `address` | Always live; `force_pull` irrelevant | -| `daily-market-cap-sum`, `total-unique-users` | Live, cached 20 seconds | -| `daily-trade-volume`, `daily-unique-active-users`, `daily-created-tokens-count`, `total-market-cap`, `total-created-tokens` | Live on every request, uncached | +| `daily-market-cap-sum` | Live; may be cached for up to 20 seconds | +| `daily-trade-volume`, `daily-unique-active-users`, `daily-created-tokens-count`, `total-market-cap`, `total-created-tokens`, `total-unique-users` | Live on every request, uncached | | `coins/aeternity/*` | From a snapshot refreshed from CoinGecko every **10 minutes** | ## `GET /api/analytics/challenge` diff --git a/pages/api-reference/conventions.mdx b/pages/api-reference/conventions.mdx index 0bcb230..12eee7e 100644 --- a/pages/api-reference/conventions.mdx +++ b/pages/api-reference/conventions.mdx @@ -5,18 +5,20 @@ description: "Pagination, ordering, units, errors, rate limits and authenticatio # API Conventions -Every endpoint on `api.superhero.com` is plain JSON over HTTPS. The rules below (base URLs, -pagination, shared query parameters, units, errors, rate limits and the signature-based write -flow) apply everywhere and are not repeated on the endpoint pages. +The REST API on `api.superhero.com` serves JSON over HTTPS. This page explains base URLs, +pagination, shared query parameters, units, errors and rate limits. Authentication varies by +endpoint; the exceptions are listed below. ## Base URLs | Network | Base URL | Chain id | | --- | --- | --- | | Mainnet | `https://api.superhero.com` | `ae_mainnet` | -| Testnet | Not publicly documented | `ae_uat` | +| Testnet | No public endpoint documented | `ae_uat` | -Both hosts serve the same paths. Every path is relative to the base and begins with `/api/`. The +Testnet API integrations require a separately deployed backend and its base URL. + +REST paths are relative to the configured base URL and begin with `/api/`. The only versioned prefix is `/api/v2/mdw/*`, the indexed chain mirror. See [Node & Middleware](/api-reference/node-and-middleware). @@ -25,22 +27,25 @@ Outside production the server also serves Swagger UI at `/api` and the OpenAPI 3 ## Authentication -**Reads need no credentials.** No API key, bearer token, cookie or session: +**Public data reads need no credentials.** Token, post and account queries need no API key +or bearer token. Private notifications require authentication, as described below: ```bash curl -s "https://api.superhero.com/api/tokens?limit=3&order_by=market_cap&order_direction=DESC" ``` -**Writes are authorised by wallet signature.** There is no login endpoint and no token to store. -Every mutating flow is three steps: +**Profile and address-link writes use wallet signatures.** The usual flow has three steps: -1. `POST` the challenge endpoint with your `ak_...` address. It returns a `nonce` (or - `verification_token`), a human-readable `message` and an expiry. +1. `POST` the claim or challenge endpoint with your `ak_...` address and the flow's required + inputs. It usually returns a `nonce` and a human-readable `message`; some flows also return + a verification token or an expiry. The notification device and preference challenges are the + exception: they return only `{ nonce, expiresAt }` (see below). 2. Sign `message` with the private key for that address. 3. `POST` the submit endpoint with the nonce, the signature and the value you are claiming. -The server verifies the signature against the address in the request. Endpoints that use this -pattern: +For address links, the AddressLink contract verifies the signature when the server submits the +transaction; the other flows verify it on the server. Either way a bad signature is a `400`. +Endpoints that use this pattern: | Flow | Challenge | Submit | | --- | --- | --- | @@ -54,9 +59,18 @@ pattern: | Push-notification device | `POST /api/notifications/devices/challenge` | `POST /api/notifications/devices` | | Notification preferences | `POST /api/notifications/preferences/challenge` | `POST /api/notifications/{address}/preferences` | -Each `claim` flow has a matching `unclaim` and `unclaim/submit` pair, signed the same way. See +Each address-link `claim` flow has a matching `unclaim` and `unclaim/submit` pair, signed the same way. See [Profile](/api-reference/profile) for request bodies. +Nostr submission additionally requires a signed `nostr_event` instead of a verification +token. Preferred-name messages use the owned `.chain` name as principal rather than the +address. Sign the returned text exactly. + +The notification device and preference challenges return no message. The client builds it +from the fixed templates in the API's +[`notifications.constants.ts`](https://github.com/superhero-com/superhero-api/blob/9013fd1ba3e61844cbb76653ea9f5960ca0a23c7/src/notifications/notifications.constants.ts) +and signs that; the feed-session template is shown in [Notifications](/social/notifications). + **The notification feed uses a bearer session token.** One wallet signature is exchanged for a token, which is then sent as a normal `Authorization: Bearer` header: @@ -69,6 +83,11 @@ GET /api/notifications/{address}/feed?limit=50 -> Authorization: Bearer {to `GET /api/notifications/web-push/vapid-public-key` is public and needs no token. +**Operator dashboards need a session cookie.** `/api/bcl-affiliation/analytics*`, +`/api/bcl-affiliation/tree`, their `/preview` pages and the `GET /api/analytics/journey/*` reports +require an operator login through `/api/bcl-affiliation/auth/login`; without it they return +`401`. + **Two endpoints take an API key.** `POST /api/trending-tags` and `PATCH /api/dex/tokens/{address}/listed` accept it as either header: @@ -113,8 +132,10 @@ Pass `page` (1-based) and `limit` to walk it. ### The `limit` cap is 100 -100 is both the default and the maximum. What happens when you exceed it depends on the endpoint -family: +For most list endpoints 100 is both the default and the maximum. Exceptions include `/api/feed` +(default 20, silently clamped to 50) and the search routes (`/api/search` defaults to 5 and +`/api/accounts/search` to 8, both capped at 20); topics, comments and token rankings also use +smaller defaults. What happens when you exceed 100 depends on the endpoint family: | Endpoint family | `limit=101` | `page=0` | | --- | --- | --- | @@ -123,7 +144,8 @@ family: | `/api/dex/*` lists | Silently clamped to 100 | Silently clamped to 1 | Read `meta.itemsPerPage` rather than assuming your `limit` was honoured. `page` on -`/api/v2/mdw/*` is capped at 1,000,000. +`/api/v2/mdw/txs` and `/api/v2/mdw/key-blocks` is capped at 1,000,000, and on the other mirror +routes at 500. ### Invalid `order_by` @@ -137,7 +159,7 @@ to `market_cap` and an unrecognised `order_direction` to `DESC`, with no error. | --- | --- | | `GET /api/tokens/{address}/history` | A bare JSON array. Still takes `page` and `limit`; you have reached the end when a page comes back empty | | `GET /api/accounts/{address}/portfolio/history` | A bare JSON array of snapshots, bounded by `startDate`, `endDate` and `interval` rather than by pages | -| `GET /api/accounts/leaderboard` | `items` plus a different `meta`: `page`, `limit`, `totalItems`, `totalPages`, `window`, `sortBy`, `sortDir` and `timeFilter`. Note `page`, not `currentPage` | +| `GET /api/accounts/leaderboard` | `items` plus a different `meta`: `page`, `limit`, `totalItems`, `totalPages`, `window`, `sortBy`, `sortDir` and, for custom periods only, `timeFilter: { start, end }`. Note `page`, not `currentPage` | | `GET /api/feed` | Keyset pagination: `items` plus `next_cursor`. Pass the cursor back as `cursor`; there is no page number | The analytics series endpoints return bare arrays and the totals endpoints return a scalar or a @@ -242,18 +264,21 @@ on each guarded endpoint. | Route | | --- | -| `GET` and `GET {id}` on `/api/v2/mdw/txs`, `/api/v2/mdw/micro-blocks`, `/api/v2/mdw/key-blocks`, `/api/v2/mdw/sync-state`, `/api/v2/mdw/plugin-sync-state` | +| `GET` and `GET {id}` on `/api/v2/mdw/txs`, `/api/v2/mdw/key-blocks`, `/api/v2/mdw/sync-state`, `/api/v2/mdw/plugin-sync-state` | | `GET /api/announcements` | | `POST /api/notifications/devices/challenge`, `POST /api/notifications/devices`, `DELETE /api/notifications/devices` | | `POST /api/notifications/preferences/challenge`, `GET` and `POST /api/notifications/{address}/preferences` | | `POST /api/notifications/{address}/feed/challenge`, `POST /api/notifications/{address}/feed/session` | +| `POST /api/notifications/{address}/price-alerts`, `DELETE /api/notifications/{address}/price-alerts/{id}` | | `GET /api/notifications/web-push/vapid-public-key` | -| `GET /api/profile/{address}/x-posting-reward`, `POST /api/profile/x-posting-reward/recheck-challenge`, `POST /api/profile/{address}/x-posting-reward/recheck`, `POST /api/profile/{address}/x-reward/referral-link` | +| `GET /api/profile/{address}/x-posting-reward`, `GET /api/profile/{address}/x-posting-reward/history`, `POST /api/profile/x-posting-reward/recheck-challenge`, `POST /api/profile/{address}/x-posting-reward/recheck`, `POST /api/profile/{address}/x-reward/referral-link` | | `POST /api/profile/chain-name/challenge`, `POST /api/profile/chain-name/claim` | | `/api/rooms/*` and the token-gated-room recheck and metrics routes | +| Internal dashboard login/setup: `POST /api/bcl-affiliation/auth/login`, `POST /api/bcl-affiliation/auth/setup` | -Everything else (tokens, transactions, accounts, analytics, DEX, posts, trending tags, -affiliations, search and feed) is unthrottled. Poll considerately and prefer the +The public token, transaction, account, analytics, DEX, post, trending-tag, affiliation, search and +feed controllers do not use this guard. Deployment infrastructure can impose additional +limits, so handle `429` responses on any endpoint. Poll considerately and prefer the [WebSocket](/api-reference/websocket) for change notification. ## CORS @@ -282,8 +307,7 @@ Several endpoints are served from an in-process cache rather than recomputed per | `GET /api/tokens/{address}/performance`, `.../performance-raw` | 60 seconds | | `GET /api/accounts` | 60 seconds | | `GET /api/feed` | 15 seconds | -| `GET /api/analytics/total-unique-users` | 20 seconds | -| `GET /api/accounts/leaderboard` | up to 60 seconds. `meta.timeFilter.start` / `.end` are the times the cache entry was filled | +| `GET /api/accounts/leaderboard` | up to 60 seconds; snapshot windows are rebuilt every ten minutes | Some values are recomputed on a schedule: token performance and `rank` every five minutes, the daily analytics rows hourly, AE fiat rates every ten minutes, and trending scores as described on @@ -291,18 +315,19 @@ daily analytics rows hourly, AE fiat rates every ten minutes, and trending score ## Versioning and deprecation -There is no version negotiation. The OpenAPI document declares version `1.0`, `GET /api/stats` -reports the deployed package version as `apiVersion`, and no header or path segment selects a -version. `/api/v2/mdw/*` is a name inherited from the middleware's own API. +There is no version negotiation. The OpenAPI document declares version `1.0`. `GET /api/stats` +includes `apiVersion` only when the server is started through npm, and api.superhero.com omits +it. No header or path segment selects a version. `/api/v2/mdw/*` is a name inherited from the middleware's own API. -Deprecation is by annotation. A retired parameter keeps validating and stops having an effect: +Deprecation is by annotation. Check each parameter's scope: an annotation does not necessarily +mean it is ignored in every request mode. | What | Status | | --- | --- | | `GET /api/contracts` | Deprecated. Still returns a single-element array naming the community factory. Use `GET /api/factory` | | `includeOnChain` on both profile read endpoints | Accepted and ignored; profiles are served from indexed data | | `window` on `GET /api/posts/popular` | Accepted and ignored; popular ranking is all-time | -| `points` and `maxCandidates` on `GET /api/accounts/leaderboard` | Accepted and ignored | +| `points` and `maxCandidates` on `GET /api/accounts/leaderboard` | Deprecated in the schema; ignored for snapshot windows but still affect custom-period requests | ## Related diff --git a/pages/api-reference/dex.mdx b/pages/api-reference/dex.mdx index cecc86d..de686c9 100644 --- a/pages/api-reference/dex.mdx +++ b/pages/api-reference/dex.mdx @@ -110,7 +110,8 @@ when one side of the pair is WAE. ## `PairTransactionDto` -One row per swap or liquidity event. +One row per router transaction, keyed by `tx_hash`. A multi-hop swap is recorded once, against +the last hop's pair; earlier hops get no row and no volume. | Field | Type | Meaning | | --- | --- | --- | @@ -120,18 +121,27 @@ One row per swap or liquidity event. | `pair` | `PairDto` | The pair, inlined | | `tx_type` | string | The router entrypoint that was called (see below) | | `reserve0` / `reserve1` | string | Reserves **after** the transaction, in base units | -| `ratio0` | string | Price of `token0` quoted in `token1`: `reserve0 / reserve1` | -| `ratio1` | string | Price of `token1` quoted in `token0` | -| `total_supply` | string | LP supply after the transaction | +| `ratio0` | string | Raw reserve ratio: `reserve0 / reserve1` | +| `ratio1` | string | Raw reserve ratio: `reserve1 / reserve0` | +| `total_supply` | string | Sum of raw reserves: `reserve0 + reserve1` | | `volume0` / `volume1` | string | Traded volume per side for swaps; `0` for liquidity operations | -| `market_cap0` / `market_cap1` | string | Market cap denominated in each token | -| `market_cap` | string | Pool market cap | +| `market_cap0` / `market_cap1` | string | Not populated; always `"0"` | +| `market_cap` | string | Not populated; always `"0"` | | `swap_info` | `SwapInfoDto` or null | Present for swaps | | `pair_mint_info` | `LiquidityInfoDto` or null | Present for liquidity operations | | `created_at` | string | ISO 8601 | `LiquidityInfoDto` is `type` (`PairMint` or `PairBurn`) plus `amount0` and `amount1`. +The ratios use base-unit reserves. For positive reserves, convert them to whole-token prices: + +- Price of `token0` in `token1`: `ratio1 * 10^(token0.decimals - token1.decimals)`. +- Price of `token1` in `token0`: `ratio0 * 10^(token1.decimals - token0.decimals)`. + +A ratio is `"0"` when its denominator reserve is zero; that pool cannot provide a usable price. +The transaction's `total_supply` is a legacy reserve sum, not an LP supply or a pool valuation. +The inlined `pair.total_supply` on `PairDto` remains the LP token supply. + ### `tx_type` `tx_type` is the name of the router entrypoint that was called. The complete set: @@ -234,15 +244,15 @@ Sets the `listed` flag. Body is `{ "listed": true }` or `{ "listed": false }`; r updated `DexTokenDto`, or 404 for an unknown token. Requires the API key, sent as `x-api-key: YOUR_KEY` or `Authorization: Bearer YOUR_KEY`. A -missing or wrong key is a `401`. Every other write in the API uses a wallet signature. See +missing or wrong key is a `401`. Authentication for other endpoints is described in [Conventions](/api-reference/conventions#authentication). ## Pagination on `/api/dex/*` `limit` defaults to 100 and is capped at 100. Unlike the rest of the API, exceeding the cap does -not error: `limit=500` is silently clamped to 100, `page=0` to 1, and a non-numeric `limit` falls -back to 100. Read `meta.itemsPerPage` rather than assuming your `limit` was honoured, and never -infer "no more results" from getting fewer rows than you asked for. +not error: `limit=500` is silently clamped to 100 and `page=0` to 1. A non-numeric `limit` returns +`400` during integer parsing. Read `meta.itemsPerPage` rather than assuming your `limit` was +honoured, and never infer "no more results" from getting fewer rows than you asked for. ## Related diff --git a/pages/api-reference/factory-and-contracts.mdx b/pages/api-reference/factory-and-contracts.mdx index d32480c..35ff5ec 100644 --- a/pages/api-reference/factory-and-contracts.mdx +++ b/pages/api-reference/factory-and-contracts.mdx @@ -152,7 +152,7 @@ curl -s "https://api.superhero.com/api/stats" | `syncingLatestBlocks` | boolean | Same value as `fullSyncing` | | `lastSyncedBlockNumber` | number | How far down from the tip the backward sync has reached | | `remainingBlocksToSync` | number | `lastSyncedBlockNumber` minus 0, because the backward sync targets genesis | -| `apiVersion` | string | The deployed package version | +| `apiVersion` | string, optional | The package version; omitted unless the server is started through npm (absent on api.superhero.com) | | `mdwConnected` | boolean | Whether the middleware WebSocket subscription is up | | `uptime` | string | Human-readable, e.g. `3d 4h 12m 8s` | | `uptimeDurationSeconds` | number | The same as a number | diff --git a/pages/api-reference/index.mdx b/pages/api-reference/index.mdx index f00ae70..8ab9872 100644 --- a/pages/api-reference/index.mdx +++ b/pages/api-reference/index.mdx @@ -6,24 +6,27 @@ description: "Base URLs, authentication and the endpoint index for the api.super # API Reference `api.superhero.com` is the read API behind Superhero: tokens and their prices, posts and topics, -accounts and portfolios, the DEX, trending and analytics. Reads need no credential. Writes are -authorised by a wallet signature over a server-issued challenge, not by an API key. +accounts and portfolios, the DEX, trending and analytics. Public data reads need no credentials. +Profile and address-link writes usually use a wallet-signed challenge; private notifications +and administrative endpoints have separate authentication requirements. See +[Conventions](/api-reference/conventions#authentication). ```bash curl -s "https://api.superhero.com/api/tokens?order_by=trending_score&order_direction=DESC&limit=5" ``` -Start with [Conventions](/api-reference/conventions). Pagination, units, errors, rate limits and -the write flow are shared by every endpoint and are not repeated per page. +Start with [Conventions](/api-reference/conventions) for common pagination, units, errors and +the endpoint-specific authentication and rate limits. ## Base URLs | Network | Base URL | Chain id | | --- | --- | --- | | Mainnet | `https://api.superhero.com` | `ae_mainnet` | -| Testnet | Not publicly documented | `ae_uat` | +| Testnet | No public endpoint documented | `ae_uat` | -Both hosts serve identical paths. Every path begins with `/api/`. +For testnet, deploy a backend and configure its API base URL. REST paths begin with `/api/`; +available routes depend on the deployed backend version. ## Sections @@ -176,8 +179,6 @@ GET /api/profile/{address}/x-posting-reward POST /api/profile/x-posting-reward/recheck-challenge POST /api/profile/{address}/x-posting-reward/recheck POST /api/profile/{address}/x-reward/referral-link -POST /api/profile/{address}/challenge (deprecated) -PATCH /api/profile/{address} (deprecated) ``` ### Factory, invitations and affiliations @@ -198,6 +199,9 @@ GET /api/bcl-affiliation/analytics/x-invite GET /api/bcl-affiliation/tree ``` +The `/api/bcl-affiliation/*` reads are operator dashboards and need an operator session; see +[Invitations & Affiliations](/api-reference/invitations-and-affiliations). + ### DEX ```text @@ -244,18 +248,27 @@ GET /api/notifications/{address}/preferences POST /api/notifications/{address}/preferences ``` -The notification feed routes are the only bearer-authenticated part of the API: +The notification feed routes are the only bearer-authenticated part of the API. A wallet-signed +challenge and session issue the token (these two, and the public VAPID key, need no token): ```text POST /api/notifications/{address}/feed/challenge POST /api/notifications/{address}/feed/session -GET /api/notifications/{address}/feed -GET /api/notifications/{address}/feed/unread-count -POST /api/notifications/{address}/feed/read -POST /api/notifications/{address}/web-push/subscription GET /api/notifications/web-push/vapid-public-key ``` +These require the bearer token: + +```text +DELETE /api/notifications/{address}/feed/session +GET /api/notifications/{address}/feed +GET /api/notifications/{address}/feed/unread-count +POST /api/notifications/{address}/feed/read +POST /api/notifications/{address}/web-push/subscription +DELETE /api/notifications/{address}/web-push/subscription +GET /api/notifications/{address}/price-alerts +``` + Governance is documented under [Governance](/governance), chat rooms under [Chat](/social/chat) and notifications under [Notifications](/social/notifications). @@ -267,8 +280,6 @@ GET /api/v2/mdw/txs GET /api/v2/mdw/txs/{hash} GET /api/v2/mdw/key-blocks GET /api/v2/mdw/key-blocks/{hash} -GET /api/v2/mdw/micro-blocks -GET /api/v2/mdw/micro-blocks/{hash} GET /api/v2/mdw/sync-state GET /api/v2/mdw/plugin-sync-state ``` diff --git a/pages/api-reference/invitations-and-affiliations.mdx b/pages/api-reference/invitations-and-affiliations.mdx index 7d83898..06272e3 100644 --- a/pages/api-reference/invitations-and-affiliations.mdx +++ b/pages/api-reference/invitations-and-affiliations.mdx @@ -9,7 +9,10 @@ An invite link is a private key; the AE behind it sits in the `AffiliationTreasu until someone redeems it. This API is the indexed view: which invites an address has issued and which have been claimed. Creating or revoking an invite is a contract call, not a REST call. -All paths are relative to `https://api.superhero.com`. Reads need no authentication. +All paths are relative to `https://api.superhero.com`. The invitation and affiliation reads need no +authentication. The `/api/bcl-affiliation/*` analytics, tree and preview routes are internal operator dashboards: +they need an operator session cookie from `/api/bcl-affiliation/auth/login`. Without it a JSON +request gets `401` and a browser is redirected to the login page. ## Endpoints @@ -197,9 +200,7 @@ inviter · registered_count · redeemed_count · revoked_count · pending_count Ordered by `registered_count` descending, then `total_amount_ae`. All amounts in **AE**. -```bash -curl -s "https://api.superhero.com/api/bcl-affiliation/analytics/top-inviters?limit=10" -``` +This route needs the operator session described above; without it the response is `401`. ### `GET /api/bcl-affiliation/analytics/x-verification` and `/x-invite` diff --git a/pages/api-reference/node-and-middleware.mdx b/pages/api-reference/node-and-middleware.mdx index 097f53a..c840e20 100644 --- a/pages/api-reference/node-and-middleware.mdx +++ b/pages/api-reference/node-and-middleware.mdx @@ -89,7 +89,9 @@ The response is `{ data: [...], next }`. Each element carries `hash`, `block_hei `{ type, value }`) and `return`. Filter to `tx.function === 'post_without_tip'`, then read the post body from `arguments[0].value` and the attached links from `arguments[1].value`. -`next` is a **path**, not a full URL. Concatenate it onto the middleware origin to page. +`next` is a **path** relative to the middleware base URL, without its `/mdw` prefix. Append it to +the same base you queried (for example `https://mainnet.aeternity.io/mdw`); appending it to the +bare origin returns `405`. ### Name resolution @@ -103,8 +105,10 @@ resolves up to 25 at a time, and fall back to the middleware for names it does n ### Transaction confirmation -`GET /mdw/v3/transactions/{hash}` returning `404` means **pending**, not failed. Poll every 5 -seconds and compute confirmations as `currentHeight - blockHeight + 1`. +`GET /mdw/v3/transactions/{hash}` returning `404` means the middleware has no indexed record. +The transaction may be pending, not yet indexed, never broadcast or dropped. Check the node +and the submission result as well. For an included transaction, compute confirmations as +`currentHeight - blockHeight + 1`; poll while waiting for the required count. ## The middleware mirror on api.superhero.com @@ -116,22 +120,21 @@ The Superhero API re-indexes a slice of middleware data under its own paths: | `GET /api/v2/mdw/txs/{hash}` | One transaction | | `GET /api/v2/mdw/key-blocks` | Key blocks, filterable by `hash`, `height`, `beneficiary`, `miner`, `version` | | `GET /api/v2/mdw/key-blocks/{hash}` | One key block | -| `GET /api/v2/mdw/micro-blocks` | Micro blocks | -| `GET /api/v2/mdw/micro-blocks/{hash}` | One micro block | | `GET /api/v2/mdw/sync-state` | Indexer sync state | | `GET /api/v2/mdw/plugin-sync-state` | Per-plugin sync state | | `GET /api/mdw/health` | Middleware health check | These take an `includes` parameter for nested relations: `keyBlock`, `keyBlock.txs`, -`microBlocks`, `txs.keyBlock` and similar, comma-separated. An array relation is truncated to -**50** items per parent. Response shapes are the mirror's own `Tx`, `KeyBlock` and `MicroBlock` -records, not the upstream middleware's. +`txs.keyBlock` and similar, comma-separated. An array relation is truncated to **50** items per +parent. Response shapes are the mirror's own `Tx` and `KeyBlock` records, not the upstream +middleware's. Micro blocks are not mirrored; key blocks keep a `micro_blocks_count`. - **Rate-limited.** 10 requests per minute per IP per route path, returning `429` with a `retryAfter` field in the body. See [Conventions](/api-reference/conventions#rate-limits). - **`limit` is capped at 100** with `400 Maximum limit is 100 items per request`; an `order_by` outside the route's sortable set is a `400`. -- **`page` goes up to 1,000,000.** Deep paging still costs the database a scan of everything +- **`page` goes up to 1,000,000** on `txs` and `key-blocks`; `sync-state` and `plugin-sync-state` + stop at 500. Deep paging still costs the database a scan of everything before your page, so prefer a `height` or `block_height` filter where you can. Sortable fields on `sync-state`: `id`, `last_synced_height`, `tip_height`, `is_bulk_mode`, diff --git a/pages/api-reference/profile.mdx b/pages/api-reference/profile.mdx index cf67efe..d88952f 100644 --- a/pages/api-reference/profile.mdx +++ b/pages/api-reference/profile.mdx @@ -1,15 +1,16 @@ --- title: "Profile API" -description: "Read profiles, and the challenge-and-signature flow behind every write endpoint on api.superhero.com." +description: "Read profiles and use the challenge-and-signature flow for profile and identity updates." --- # Profile API -The write endpoints on `api.superhero.com` take no password, API key or session cookie. Every -write is authorised by a **wallet signature over a server-issued challenge**: request a +The profile and identity writes described here use a +**wallet signature over a server-issued challenge**: request a challenge, sign it with the key that owns the address, post the signature back. -All paths are relative to `https://api.superhero.com`. +All paths are relative to `https://api.superhero.com`. Other API endpoints have different +authentication requirements; see [Conventions](/api-reference/conventions#authentication). ## Reading a profile @@ -32,14 +33,14 @@ curl -s "https://api.superhero.com/api/profile/ak_2ruXgsLy9jMwEqsgyQgEsxw8chYDfv | `address` | string | The `ak_...` | | `public_name` | string | Resolved display name. **Never null**: it falls back to the address | | `profile.fullname` | string | Display name from the legacy profile cache. `""` when unset | -| `profile.bio` | string | The verified `links.bio` if present, else the cached bio, else `""` | -| `profile.site` | string or null | The verified `links.site` | +| `profile.bio` | string | The wallet-signed `links.bio` if present, else the cached bio, else `""` | +| `profile.site` | string or null | The wallet-signed `links.site` | | `profile.avatarurl` | string | `""` when unset | | `profile.username` | string or null | Legacy custom username | | `profile.prefered_aens_name` | string or null | The verified `links.prefaens`. Note the one-`r` spelling | | `profile.x_username` | string or null | The verified `links.x` | | `profile.chain_name` | string or null | The account's `chain_name` first, then the cached copy | -| `profile.chain_expires_at` | string or null | When the `.chain` name expires | +| `profile.chain_expires_at` | string or null | Legacy cached value, not refreshed; check expiry through AENS | | `profile.followers_count` / `following_count` | number | Single-profile read only, and only when the social-graph feature is enabled | The display name resolves as: @@ -49,7 +50,9 @@ public_name = prefered_aens_name || chain_name || username || address ``` An X handle never becomes the display name. `fullname`, `avatarurl` and `username` come from a -legacy profile cache; the account's `chain_name` is refreshed hourly and is the live one. +legacy profile cache; the account's `chain_name` is periodically refreshed from the middleware. +Stored preferred-name links take precedence independently of that refresh. See +[Names](/identity/names#how-the-chain-name-stays-fresh) for freshness limits. `includeOnChain` is accepted on both read endpoints and ignored; profiles are served from indexed data. @@ -75,7 +78,7 @@ curl -s "https://api.superhero.com/api/profile?addresses=ak_ONE,ak_TWO" ## The write pattern -Every write endpoint is one of two shapes: +Address-link writes generally follow this shape: ```text claim -> server returns { message, nonce, value, verification_token } @@ -91,13 +94,17 @@ sign -> wallet signs `message` submit -> server verifies, performs the action ``` -The nonce is single-use and the challenge expires. +X, bio, site and preferred-name claims return a verification token; Nostr uses a signed +event instead. AddressLink's on-chain nonce is consumed by a successful link or unlink and +has no built-in time expiry. Server-issued tokens and reward/sponsorship challenges have +their own expiration rules. ## Address links -An **address link** is a verified statement that an `ak_...` owns something off-chain: an X -handle, a bio, a website, a preferred `.chain` name, or a Nostr key. Five families, each with -the same four endpoints. +An **address link** records an account's consent to a provider value. X and Nostr add proof +of control of the external account or key; preferred-name links check AENS ownership. Bio +and website links are self-declared and do not prove ownership of a domain. Five families +use the same four endpoint suffixes. | Link | Base path | | --- | --- | @@ -125,12 +132,16 @@ curl -s -X POST "https://api.superhero.com/api/address-links/bio/claim" \ | `message` | string | The exact text the wallet must sign | | `nonce` | **number** | The address's current nonce on the `AddressLink` contract, echoed back on submit | | `value` | string | The normalised value the server will record | -| `verification_token` | string | Server-side proof that this claim was issued. **X only** | +| `verification_token` | string | Server-issued proof required on link submission for X, bio, site and preferred name. Nostr instead requires a signed `nostr_event` | `nonce` is the `AddressLink` contract's `get_nonce` counter for the address; it advances after a successful submit, and sending it as a string (`"42"`) is a 400. The chain-name and X-reward flows use a different, server-issued string `nonce`. +Nostr claim returns `message`, `nonce` and `value`, without a verification token. Its submit +body contains `address`, `value`, `nonce`, `signature` and a JSON-encoded `nostr_event` proving +control of the Nostr key. See [Chat](/social/chat#linking-your-nostr-key-to-your-address). + The message the wallet signs is deterministic: ```text @@ -138,8 +149,10 @@ link:
::: unlink:
:: ``` -`` is `x`, `bio`, `site`, `prefered-aens-name` or `nostr`. A signature over anything -else fails contract-side verification. +`` is `x`, `bio`, `site`, `prefaens` or `nostr`. The preferred-name REST path uses +`prefered-aens-name`, but its on-chain provider is `prefaens`. That flow uses the `.chain` +name as the message principal in place of `
`, for example +`link:hero.chain:prefaens:hero.chain:0`. Sign the exact `message` returned by the claim endpoint. ### Submit @@ -149,7 +162,7 @@ Sign `message` with the address's key, then post everything back: curl -s -X POST "https://api.superhero.com/api/address-links/bio/submit" \ -H "Content-Type: application/json" \ -d '{"address":"ak_YOUR_ADDRESS","value":"Building things on aeternity.", - "nonce":42,"signature":"sg_...","verification_token":"..."}' + "nonce":42,"signature":"<128-character-hex-signature>","verification_token":"..."}' ``` Response is `{ "txHash": "th_..." }`. The server broadcasts the on-chain write on your behalf. @@ -157,38 +170,42 @@ The API sponsors the transaction; your signature authorises it. `value` is cappe characters, `signature` is a hex-encoded wallet signature, and `address` is validated as an `ak_` account address. +Use exactly 128 hex characters for `signature`, without `0x` or `sg_`. Decode an encoded +signature before converting its 64 bytes to hex. + ### Unclaim `POST {base}/unclaim` with `{ "address": "ak_..." }` returns `{ message, nonce }`. Sign `message`, then `POST {base}/unclaim/submit` with `{ address, nonce, signature }` and receive a `txHash`. +For a preferred-name unlink, `unclaim` also returns `value` and `principal` containing the +linked `.chain` name. Include `value` in `unclaim/submit`; it is used to reconstruct the +name-based principal and check current AENS ownership. + ### Linking X -The X value comes from an OAuth round trip rather than being typed. Two accepted claim bodies: - -```json -{ "address": "ak_...", "x_access_token": "..." } -``` +The X value comes from an OAuth round trip rather than being typed. The claim body is the PKCE +form; any other property, such as `x_access_token`, is a `400`: ```json { "address": "ak_...", "x_code": "...", "x_code_verifier": "...", "x_redirect_uri": "https://superhero.com/profile/x/callback" } ``` -The second is the PKCE form: redirect the user to X, receive the code at your redirect URI, and +Redirect the user to X, receive the code at your redirect URI, and post the code, verifier and redirect URI; the backend exchanges the code itself. From there the flow is identical: claim returns `message` plus `verification_token`, the wallet signs it, `submit` returns a `txHash`. ```text -POST /api/address-links/x/claim { address, x_access_token } or { address, x_code, x_code_verifier, x_redirect_uri } +POST /api/address-links/x/claim { address, x_code, x_code_verifier, x_redirect_uri } POST /api/address-links/x/submit { address, value, nonce, signature, verification_token } POST /api/address-links/x/unclaim { address } POST /api/address-links/x/unclaim/submit { address, nonce, signature } ``` Read the result back from `GET /api/accounts/{address}` as `links.x`, falling back to -`profile.x_username` and then the legacy top-level `x_username`. +`profile.x_username`. ## Sponsored `.chain` name registration @@ -223,18 +240,19 @@ The claim body is `address`, `name`, `challenge_nonce`, `challenge_expires_at` a Registration is asynchronous and takes four on-chain transactions. Poll `GET /api/profile/{address}/chain-name-claim`, which returns `status` plus, as they happen, -`preclaim_tx_hash`, `claim_tx_hash`, `update_tx_hash`, `transfer_tx_hash`, an `error`, and the -name's expiry under `expires_at` (older responses use `approximate_expire_time`, -`approximateExpireTime`, `expire_time` or `expireTime`). +`preclaim_tx_hash`, `claim_tx_hash`, `update_tx_hash`, `transfer_tx_hash`, an `error` and a +`retry_count`. It carries no expiry: read `expire_height` or `approximate_expire_time` from the +middleware's `GET /v3/names/{name}`. ## X posting reward -All four routes carry the per-IP rate limit: 10 requests per minute per route, returning `429` +All five routes carry the per-IP rate limit: 10 requests per minute per route, returning `429` with a `retryAfter` field. See [Conventions](/api-reference/conventions#rate-limits). | Method & path | Purpose | | --- | --- | | `GET /api/profile/{address}/x-posting-reward` | Read status. No signature | +| `GET /api/profile/{address}/x-posting-reward/history` | List the X reward payouts sent to the address. No signature | | `POST /api/profile/x-posting-reward/recheck-challenge` | Get a challenge for `address` | | `POST /api/profile/{address}/x-posting-reward/recheck` | Run the capped scan | | `POST /api/profile/{address}/x-reward/referral-link` | Get a referral link | @@ -255,15 +273,10 @@ exceeding it returns `429` with `nextAllowedAt` in the body, and the scan is ski ## Deprecated: the legacy profile update -Two endpoints implement an older generic profile edit. Use the address-link endpoints instead. - -| Method & path | Body | Returns | -| --- | --- | --- | -| `POST /api/profile/{address}/challenge` | The editable payload | `challenge`, `payload_hash`, `expires_at`, `ttl_seconds` | -| `PATCH /api/profile/{address}` | The payload plus `challenge` and `signature` | The updated profile row | - -The editable payload is `fullname`, `bio`, `nostrkey`, `avatarurl`, `username`, `x_username`, -`chain_name`, `sol_name`; the response adds `address`, `created_at` and `updated_at`. +The generic `POST /api/profile/{address}/challenge` and `PATCH /api/profile/{address}` routes +have been removed from the API and are no longer supported. +Use the [address-link endpoints](#address-links) for bio, website, X, Nostr and preferred AENS +updates. `fullname`, `avatarurl` and legacy `username` remain read-only cached fields. ## Related diff --git a/pages/api-reference/tokens.mdx b/pages/api-reference/tokens.mdx index 266378b..bc9f15b 100644 --- a/pages/api-reference/tokens.mdx +++ b/pages/api-reference/tokens.mdx @@ -8,8 +8,9 @@ description: "Query community tokens: the TokenDto and its units, holders, price Community tokens are the centre of the API: the trending list, portfolios, charts and trade records all resolve to a token. Twelve endpoints return tokens and their derived data. -All paths are relative to `https://api.superhero.com`. Reads need no authentication and are not -rate-limited. +All paths are relative to `https://api.superhero.com`. Reads need no authentication. These +routes do not use the backend's 10-request-per-minute guard; handle deployment-level limits +and back off on `429` responses. See [Rate limits](/api-reference/conventions#rate-limits). ## Endpoints diff --git a/pages/api-reference/transactions.mdx b/pages/api-reference/transactions.mdx index 53de2a0..28083af 100644 --- a/pages/api-reference/transactions.mdx +++ b/pages/api-reference/transactions.mdx @@ -154,7 +154,8 @@ endpoint once, then update from the socket. See [WebSocket](/api-reference/webso | æScan (testnet) | `https://testnet.aescan.io/transactions/{tx_hash}` | | Middleware | `GET https://mainnet.aeternity.io/mdw/v3/transactions/{tx_hash}` | -While a trade is confirming, poll the middleware form and treat a `404` as "still pending". +While a trade is confirming, poll the middleware form and keep polling on a `404`, but time out +and check the node rather than treating it as pending forever. ## `GET /api/debug/failed-transactions` diff --git a/pages/api-reference/websocket.mdx b/pages/api-reference/websocket.mdx index d9facb5..773d3b9 100644 --- a/pages/api-reference/websocket.mdx +++ b/pages/api-reference/websocket.mdx @@ -6,14 +6,17 @@ description: "The Socket.IO channels that push token updates and trades in real # WebSocket API Superhero pushes live token data over **Socket.IO**. Two events carry token updates and trades on -the default namespace, and a separate authenticated namespace carries notifications. +the default namespace, which also emits a `social-graph-updated` invalidation hint, and a separate +authenticated namespace carries notifications. ## Connecting | Network | URL | | --- | --- | | Mainnet | `https://api.superhero.com` | -| Testnet | Not publicly documented | +| Testnet | No public endpoint documented | + +For testnet, use the Socket.IO origin of your separately deployed testnet backend. Same origin as the REST API, default namespace, default `/socket.io/` path. No authentication and no handshake beyond Socket.IO's own. @@ -37,6 +40,7 @@ Socket.IO client for your language. | --- | --- | | `token-updated` | A token's live price, supply, market cap or DAO balance has been re-read from chain and written back | | `token-history` | A buy, sell or token creation has been indexed **live** | +| `social-graph-updated` | The follow graph changed (also sent once on connect); a hint to refetch social-graph data | Both are broadcast to every connected client, so getting started takes two steps: connect and listen. Each payload carries the token's `sale_address`, so your process can route it to the views @@ -176,7 +180,7 @@ transports: ['polling'] with upgrade: false, forceNew: true | Authentication | None | Socket.IO `auth.token`, from the feed session flow | | Transport | Polling, upgrading to WebSocket | **Polling only**, upgrade disabled | | Reconnection | Library default | `reconnectionAttempts: 5` | -| Events | `token-updated`, `token-history` | `notification`, `unread-count` | +| Events | `token-updated`, `token-history`, `social-graph-updated` | `notification`, `unread-count` | | Fan-out | Broadcast to everyone | Only to the proven address's own room | The token comes from the feed session flow in diff --git a/pages/concepts/architecture.mdx b/pages/concepts/architecture.mdx index 5399409..fedacc6 100644 --- a/pages/concepts/architecture.mdx +++ b/pages/concepts/architecture.mdx @@ -6,8 +6,9 @@ description: "How the on-chain contracts, the indexer, the API and the clients f # Architecture Overview Superhero is a set of Sophia contracts on æternity, an off-chain indexer that turns their events -into a queryable API, and three clients that talk to both. Every write goes to the chain; every read -that needs to be fast goes to the API. +into a queryable API, and clients that talk to both. Posts, trades and governance actions are +written to the chain. Indexed reads, profile workflows, notifications and chat also use +off-chain services. ## The stack in one view @@ -35,24 +36,23 @@ that needs to be fast goes to the API. The Tipping and factory contracts are **singletons**: one address per network. The Tipping address is in [Deployed Addresses](/contracts/addresses); the active factory is returned by -`GET /api/factory`. Everything else is **per community**: creating a token deploys a fresh token, -curve, sale, DAO and management contract in a single transaction. +`GET /api/factory`. Each community has its own token, sale, DAO and management contracts. +The sale references the factory's shared bonding curve and affiliation treasury. -The factory's deployment sequence: +The community-creation flow: -1. A new AEX-9 token contract for the community. -2. A `BondingCurveExponential` contract with the community's pricing parameters. -3. An `AffiliationBondingCurveTokenSale` referencing the token and the curve. -4. A `DAO` contract, which becomes the sale's owner and beneficiary. -5. A `CommunityManagement` contract with initial moderator and threshold settings. -6. Registration of the community in the factory's on-chain registry. -7. An optional initial buy, executed in the same transaction. +1. Deploy a `CommunityManagement` contract and a `DAO` contract. +2. Deploy an `AffiliationBondingCurveTokenSale`, which creates the community's AEX-9 token + and references the shared curve and treasury. +3. Set the DAO as the sale's owner and beneficiary and the management contract's owner. +4. Execute any initial buy and register the community in the factory, all in the same + transaction. See [CommunityFactory](/contracts/community-factory) for the detailed flow. ## Off-chain layer The service behind `api.superhero.com` is one NestJS process doing several jobs: -- **Indexer**: a general-purpose chain indexer. It stores key blocks, micro blocks and transactions +- **Indexer**: a general-purpose chain indexer. It stores key blocks and transactions in Postgres and runs two loops: a **live indexer** fed by middleware WebSocket subscriptions for transactions and key blocks, and a **backward/bulk indexer** that backfills history, seeding its tip height from the middleware's `/v3/status` → `mdw_height`. The indexer reads the middleware, @@ -61,8 +61,8 @@ The service behind `api.superhero.com` is one NestJS process doing several jobs: - **Plugins**: all domain decoding. Each plugin declares a `startFromHeight()` and a `filters()` list matching contract calls by contract id and entrypoint name (or spend transactions by predicate), then receives `onTransactionsSaved(txs)`. The shipped set is `bcl` (token sales), - `bcl-affiliation`, `dex`, `governance`, `social` (posts), `social-tipping`, `social-graph` and - `address-links`. + `bcl-affiliation`, `dex`, `governance`, `social` (posts), `social-tipping`, `social-graph`, + `address-links`, and the token-gated-room plugins `aex9-transfer` and `community-room-state`. - **Reorg handling**: the chain is re-validated every 10 minutes. On a rollback, derived rows disappear automatically because plugin entities carry a foreign key to the transaction with `onDelete: 'CASCADE'`; a plugin can also implement `onReorg(rollBackToHeight)` for anything the @@ -148,12 +148,13 @@ The web app shows this as a two-step progress indicator; the agent CLI runs both ## The live-update path Token views do not poll. The web app opens a single socket.io connection to the `websocketUrl` from -config (`https://api.superhero.com` on mainnet). The backend emits two channels: +config (`https://api.superhero.com` on mainnet). The backend emits two token channels, plus a +`social-graph-updated` hint when the follow graph changes: | Channel | Emitted when | | --- | --- | | `token-updated` | A token's aggregate state changes; the payload carries `sale_address` | -| `token-history` | A new chart point exists for a `sale_address` | +| `token-history` | A buy, sell or create for a `sale_address` has been indexed live | Use `token-updated` as your signal to refresh token lists and transaction feeds from the REST endpoints. @@ -181,7 +182,7 @@ else is mainnet). A deployed container can override most of these at runtime thr | Key | Mainnet | Testnet | | --- | --- | --- | -| `BACKEND_URL` | `https://api.superhero.com` | Not publicly documented | +| `BACKEND_URL` | `https://api.superhero.com` | Configure your own testnet backend | | `NODE_URL` | `https://mdw.wordcraft.fun` | `https://testnet.aeternity.io` | | `MIDDLEWARE_URL` | `https://mdw.wordcraft.fun/mdw` | `https://testnet.aeternity.io/mdw` | | `EXPLORER_URL` | `https://aescan.io` | `https://testnet.aescan.io` | diff --git a/pages/concepts/attention-markets.mdx b/pages/concepts/attention-markets.mdx index 6dc0347..c5cac16 100644 --- a/pages/concepts/attention-markets.mdx +++ b/pages/concepts/attention-markets.mdx @@ -7,23 +7,24 @@ description: "Why pricing attention with a bonding curve produces a usable marke Attention already behaves like a market, but it has no price feed. Hashtags trend, communities form, and value accrues to platforms rather than participants. Superhero gives every trend a token whose price -is a deterministic function of how many people have bought in. +is a deterministic function of its circulating supply. ## Why a curve instead of an order book An order book needs two-sided interest. A brand-new hashtag has none: nobody is standing by to quote a price for `#ThingThatHappenedAnHourAgo`. A bonding curve removes the counterparty entirely. -- **No order book, no counterparty.** You always trade against the contract, so there is always - liquidity and a quotable price, from the first token onward. -- **Price is a function of supply and nothing else.** Supply only moves when someone buys or sells, - so price encodes net conviction rather than the temporary balance of resting orders. -- **Solvency is structural.** The sell curve sits strictly below the buy curve at every supply - level, so the reserve held by the sale contract is always enough to redeem the entire circulating - supply. There is no bank-run state. +- **No order book, no counterparty.** You trade against the contract, which computes quotes from + supply and holds the reserve used to pay sellers. +- **Curve price is a function of supply.** Buys mint tokens and sells burn them. Holders can + also burn their own tokens directly, reducing supply without a sale or an AE payout. The + curve uses the token contract's current `total_supply()`, rather than resting orders. +- **Buys fund the reserve.** Each buy retains the quote for immediately selling the newly minted + tokens. Full redemption follows in the ideal continuous model; integer rounding requires + separate analysis. See [Reserve accounting and rounding](/concepts/value-flow#reserve-accounting-and-rounding). -The cost of that guarantee is the spread. Superhero sets it at 1%: half to the token's DAO -treasury, half to the affiliation chain. See [Where the Money Goes](/concepts/value-flow). +Superhero sets the spread at 1% of curve value: on buys, half is allocated to the token's DAO +treasury and half to the affiliation chain, before integer rounding. See [Where the Money Goes](/concepts/value-flow). ## The curve @@ -33,10 +34,13 @@ Superhero uses one exponential curve for every community token: buy(x) = 0.001 * e^(0.00000001 * x) - 0.0009999 sell(x) = buy(x) * 0.995 -price paid for `amount` tokens = integral of buy(x) from supply to supply + amount +curve cost for `amount` tokens = integral of buy(x) from supply to supply + amount return for selling `amount` back = integral of sell(x) from supply - amount to supply ``` +The all-in buy payment adds the affiliation fee to that curve cost. These equations describe +the continuous model; contract quotes also apply integer rounding. + `x` is the circulating supply in whole tokens. The trade card's client-side estimator uses the same three constants (`a = 0.001`, `k = 0.00000001`, `c = 0.0009999`) to show you a quote before you sign. @@ -45,8 +49,8 @@ Two design consequences fall straight out of the constants: - At supply zero the marginal price is `0.001 - 0.0009999 = 0.0000001 AE`. The curve starts almost free, which makes being first meaningfully rewarding. - The exponent is small (`1e-8`), so the curve is nearly linear for the first few hundred thousand - tokens and then bends hard. Only 10–20% of the total supply is expected to be reached, which gives - a noticeable price increase right from the start of the curve. + tokens and becomes more curved as supply grows. There is no fixed maximum supply against + which to express a percentage sold. ## A worked example @@ -63,12 +67,12 @@ curve formula above. Now follow one buyer through it. -**The first buyer spends 1 AE.** Solving the integral for a 1 AE curve cost at supply 0 gives about -**437,014 tokens**. Their marginal price rose from 0.0000001 AE to roughly 0.0000053 AE per token -along the way, a 53× move in the marginal price, on a 1 AE trade, because the curve is steepest in +**The first buyer buys at a 1 AE curve cost.** Solving the integral at supply 0 gives about +**437,014 tokens**. Their marginal price rose from 0.0000001 AE to roughly 0.00000448 AE per token +along the way, about a 44.8× move in the marginal price, on a 1 AE curve cost, because the curve is steepest in relative terms at the very bottom. -**The next buyer spends the same 1 AE.** They start at supply 437,014, not 0, so the same AE buys +**The next buyer uses the same 1 AE curve cost.** They start at supply 437,014, not 0, so the same AE buys materially fewer tokens. The price encodes who was early. **Buying a million tokens at different points** shows the same thing from the other side: @@ -98,9 +102,10 @@ pressure on the related token; fading attention drains it. ## The trending score -`trending_score` is the momentum signal the product exposes. It is a field on every token returned -by `GET /api/tokens`, it is the default sort (`order_by=trending_score&order_direction=DESC`), and -there is a per-token endpoint at `GET /api/tokens/[address]/score`. +`trending_score` is the momentum signal the product exposes. It is a field on tokens returned +by `GET /api/tokens`. By default, the web app's main token list explicitly requests +`order_by=trending_score&order_direction=DESC`; the API defaults to `market_cap` when +`order_by` is omitted. There is a per-token endpoint at `GET /api/tokens/[address]/score`. It is computed off-chain by the backend: @@ -125,9 +130,9 @@ worth far more than the next few. Both work against brute-force manufacturing of | Trading | Sell count | 0.20 | 40 | | Trading | Volume in AE | 0.20 | 5,000 | | Social (0.65) | Posts mentioning the symbol | 0.32 | 15 | -| Social | Comments mentioning the symbol | 0.32 | 50 | -| Social | Unique authors mentioning it | 0.22 | 20 | -| Social | Tips on mentioning posts | 0.05 | 15 | +| Social | Matching comments and replies in matching threads | 0.32 | 50 | +| Social | Unique authors of matching posts and comments | 0.22 | 20 | +| Social | Non-self tips on matching posts and comments | 0.05 | 15 | | Social | Tip amount in AE | 0.03 | 250 | | Social | Reads of mentioning posts | 0.06 | 200 | @@ -143,9 +148,10 @@ freshness_decay = 1 / (1 + age_hours / 2) ^ 1.15 ``` At two hours idle a token keeps about half its pre-decay score; at a day, about a twentieth. Scores -are refreshed on a cron (every two hours for tokens with recent activity, every six for a stale -backfill), so a score you read may be up to two hours behind the window it describes. Tokens flagged -`unlisted` are skipped entirely. +are refreshed by activity-triggered jobs and scheduled batches: every two hours for active +tokens and every six hours for stale scores. Batch limits and processing failures can delay +updates further; inspect `trending_score_update_at` rather than assuming a maximum age. +Tokens flagged `unlisted` are skipped by these refresh jobs. Trending *tags* are a different mechanism that happens to share a word. They may not have tokens at all, and their `score` and `source` are **pushed in by external providers** through @@ -167,4 +173,4 @@ it as a ranking aid, not as ground truth. See [The Trending Score](/tokens/trend - [Where the Money Goes](/concepts/value-flow): the 1% spread, split to the fraction, on both sides of a trade. - [The Trending Score](/tokens/trending-score): what the API returns and how the app sorts by it. - [Risks](/tokens/risks): the trading risks stated plainly, with the mitigations that exist. -- [Trending tokens on superhero.com](https://superhero.com/trends/tokens): the live market, sorted by market cap. +- [Trending tokens on superhero.com](https://superhero.com/trends/tokens): the token list, with selectable sorting. diff --git a/pages/concepts/faq.mdx b/pages/concepts/faq.mdx index 83be5ea..a98d95f 100644 --- a/pages/concepts/faq.mdx +++ b/pages/concepts/faq.mdx @@ -34,7 +34,8 @@ wallet. Tokens are minted/burned against AE along the bonding curve. ### 4. Where do fees go? -A portion of each trade funds the token's DAO treasury. Holders can propose and vote to allocate +A portion of each buy's curve cost funds the token's DAO treasury. Sells make no new DAO +allocation. Holders can propose and vote to allocate funds for growth, bounties, or community rewards. *Trading · More in [Where the Money Goes](/concepts/value-flow)* @@ -114,8 +115,8 @@ sales, you can withdraw accumulated referral rewards. ### 15. How is Market Cap and pricing shown? -We display price and market cap using AE as the unit. Trending defaults to Market Cap so larger -communities surface first. Token pages include candlestick charts, recent transactions, and holders +We display price and market cap using AE as the unit. The web app's main token list starts +with Trending selected; choose Market Cap to sort by size. Token pages include candlestick charts, recent transactions, and holders to help you read the market. *Pricing & Analytics · More in [Reading a Token Page](/tokens/token-page)* @@ -143,9 +144,10 @@ hash, and what happened. ### 19. What is a sponsored name claim? -We sponsor one free .chain name claim per address. The name must be longer than 12 characters -(excluding the .chain suffix). This gives you a human‑readable identity on the æternity blockchain -at no cost. +We can sponsor one .chain name claim per address. The name must be longer than 12 characters +(excluding the .chain suffix). When the sponsor can fund it, you get a human‑readable identity on +the æternity blockchain at no cost; otherwise the app offers a self-funded claim paid from your +wallet. *Name Claims · More in [Claim Your .chain Name](/getting-started/claim-name)* @@ -177,18 +179,21 @@ factory at `GET /api/factory`. ### What is the API base URL? -`https://api.superhero.com` on mainnet. The testnet API is not publicly documented. The node +`https://api.superhero.com` on mainnet. No public Superhero testnet API endpoint is documented; +testnet API workflows require a separately deployed backend. The node and middleware are separate: `https://mdw.wordcraft.fun` and `https://mdw.wordcraft.fun/mdw` on mainnet, `https://testnet.aeternity.io` and `https://testnet.aeternity.io/mdw` on testnet. See [Conventions](/api-reference/conventions). ### Is the API authenticated? Are there rate limits? -Read endpoints need no authorization header. Writes are not API calls; they are signed -transactions you send to the node. Profile mutation is the exception: it goes through a -challenge-and-signature flow (`POST /api/profile/[address]/challenge`, then `PATCH`). +Public token, post and account reads need no authorization header. On-chain actions use +signed transactions sent to a node. Profile and address-link updates use REST challenge +and submit endpoints, such as `POST /api/address-links/bio/claim` followed by +`POST /api/address-links/bio/submit`. Private notifications use a bearer session token, and +administrative writes can require an API key. See [Authentication](/api-reference/conventions#authentication). -The API allows **10 requests per minute** per IP and route path, and rejects the eleventh with +Guarded routes allow **10 requests per minute** per IP and route path, and reject the eleventh with HTTP 429 and a body carrying `retryAfter` in seconds: ```json @@ -197,14 +202,18 @@ HTTP 429 and a body carrying `retryAfter` in seconds: Design around three properties: -- **The bucket key is IP plus route path.** Ten calls a minute to `/api/tokens` and ten to - `/api/posts` both succeed; eleven to either does not. +- **The bucket key is IP plus route path.** The guard uses Express's route pattern where + available, so changing an address parameter does not necessarily create a separate bucket. - **The window is fixed, not sliding.** The first request starts a 60-second window and the counter resets when it expires. -- **The limit applies to the entity CRUD endpoints** and to the profile rewards, profile chain-name, - notification feed and token-gated-room endpoints. Write your client to back off on any 429 and +- **The limit applies only to the routes in the + [guarded-route list](/api-reference/conventions#rate-limits).** Write your client to back off on any 429 and honour `retryAfter`. +Public token and post routes do not use this guard. See the +[guarded-route list](/api-reference/conventions#guarded-routes) for its scope; deployment +infrastructure may impose additional limits. + ### Is there a published OpenAPI schema? The API is documented with Swagger, and the document is served at `/api` when the backend runs @@ -250,8 +259,8 @@ post whose first media entry is `comment:PARENT_ID`. See [Posts](/api-reference/ ### How do I get live updates instead of polling? Open a socket.io connection to the API origin and listen for **`token-updated`** and -**`token-history`**: `token-updated` fires when a token's state changes, and `token-history` when -a new chart point exists. +**`token-history`**: `token-updated` fires when a token's state changes, and `token-history` once +per live-indexed buy, sell or create. - **Every connected client receives each event.** The `sale_address` in the payload tells you which token it is about, so you update just the views that show it. diff --git a/pages/concepts/glossary.mdx b/pages/concepts/glossary.mdx index 2328e0d..a1dd3b4 100644 --- a/pages/concepts/glossary.mdx +++ b/pages/concepts/glossary.mdx @@ -9,35 +9,35 @@ Terms are alphabetical. Where a term has a colloquial name and a contract name, | Term | Definition | | --- | --- | -| **ACI** | *Contract interface descriptor.* A JSON description of a contract's entrypoints, types and events, produced by the Sophia compiler. The SDK needs one to encode a call; the agent skill ships them under `contracts/`. It describes signatures only, never implementations. See [Calling Contracts](/contracts/calling-contracts). | +| **ACI** | *æternity Contract Interface.* A JSON description of a contract's entrypoints, types and events, produced by the Sophia compiler. The SDK uses it to encode calls and decode results; the agent skill ships ACIs under `contracts/`. It describes the interface, not the implementation. See [Calling Contracts](/contracts/calling-contracts). | | **AE** | The native coin of the æternity blockchain. Used for gas, for tipping, and as the base currency of every bonding curve. See [AE & Gas](/aeternity/ae-and-gas). | | **AddressLink** | The on-chain identity contract. It stores signed, revocable provider links from an address to an X handle, a Nostr key, a preferred `.chain` name, a bio and a website, plus a per-address nonce that makes every link message single-use. See [AddressLink](/identity/address-link). | | **AENS** | *æternity Naming System.* Human-readable `.chain` names that resolve to an address, built into the protocol rather than added as a contract. Names of 13 or more characters register instantly; shorter ones go to auction. See [AENS](/aeternity/aens). | -| **aettos** | The smallest unit of AE, 1e-18 AE, analogous to wei. Contract amounts are in aettos unless stated in AE. See [Curve Parameters & Units](/tokens/curve-parameters). | +| **aetto** | The smallest unit of AE, 1e-18 AE, analogous to wei; plural: aettos. Native AE amounts use aettos at the protocol level. Token amounts use their own decimal units. See [Curve Parameters & Units](/tokens/curve-parameters). | | **AEX-9** | The æternity fungible-token standard, analogous to ERC-20. Community tokens and the ProtocolDAO token both conform to it. See [AEX Standards](/aeternity/aex-standards) and [FungibleTokenFull (AEX-9)](/contracts/aex9). | -| **Affiliation system** | The four-level referral scheme that receives 0.5% of every buy and splits it up the invite chain at 0.300%, 0.125%, 0.050% and 0.025%. Accounting lives in `AffiliationTreasury.aes`. See [The Affiliation System](/rewards/affiliation). | +| **Affiliation system** | The four-level referral scheme funded by an extra 0.5% of each buy's curve cost. Shares of that curve cost are credited up the invite chain at 0.300%, 0.125%, 0.050% and 0.025%, before integer rounding. Accounting lives in `AffiliationTreasury.aes`. See [The Affiliation System](/rewards/affiliation). | | **Allowance** | An AEX-9 approval letting another account move a set number of your tokens. Required before selling, because the sale contract can only take your tokens if you have approved it. See [FungibleTokenFull (AEX-9)](/contracts/aex9). | | **Bonding curve** | A function mapping circulating supply to price. Superhero uses one exponential curve for every community token, so price is a deterministic function of supply with no order book. See [Bonding Curves](/tokens/bonding-curve). | -| **Buy curve / sell curve** | The two branches of the pricing function. The sell curve sits 0.5% below the buy curve at every supply level, which is what guarantees the reserve can always redeem the full supply. See [Where the Money Goes](/concepts/value-flow). | +| **Buy curve / sell curve** | The two branches of the pricing function. The sell curve sits 0.5% below the buy curve. Buys retain the immediate sell quote to fund the reserve; the full-redemption argument uses the continuous model. See [Reserve accounting and rounding](/concepts/value-flow#reserve-accounting-and-rounding). | | **Chain name** | An AENS `.chain` name resolved for your address and shown on your profile. A preferred name you link through `AddressLink` takes priority over the one the middleware resolves. See [Chain Names (AENS)](/identity/chain-names). | | **Collection** | A namespace in the community factory with its own naming rules: `allowed_name_length` and `allowed_chars`. Every community token is created inside one; Superhero's global collection is fetched from the factory API. See [Collections & Naming Rules](/tokens/collections-and-naming). | -| **Community factory** | `CommunityFactory.aes`. A single, statically deployed contract that holds the collection registry, deploys a community's five contracts in one transaction, and mints ProtocolDAO tokens on buys. See [CommunityFactory](/contracts/community-factory). | -| **Community management** | `CommunityManagement.aes`. Per-community metadata, the moderator set, the muted-user set, and the minimum token threshold for write access. See [CommunityManagement](/contracts/community-management). | +| **Community factory** | `CommunityFactory.aes`. A shared contract that holds the collection registry, creates each community's token, sale, DAO and management contracts, and mints ProtocolDAO tokens on buys. Communities use the factory's shared bonding curve. See [CommunityFactory](/contracts/community-factory). | +| **Community management** | `CommunityManagement.aes`. Per-community metadata, the moderator set, the muted-user set, and the minimum token threshold for chat-room access and proposals. See [CommunityManagement](/contracts/community-management). | | **Community token** | The AEX-9 token attached to a trend, hashtag or community. Minted on buy and burned on sell against the bonding curve. See [Community Tokens](/tokens/overview). | | **DAO** | The on-chain treasury and governance contract attached to each community token. It is both the owner and the beneficiary of that token's sale contract. See [How DAOs Work](/dao/overview). | | **DAOVote** | `DAOVote.aes`. The contract deployed per vote that records positions, locks the tokens used to vote, and can be withdrawn from after close. See [DAOVote](/contracts/dao-vote). | | **Delegated posting** | Publishing a post signed by the author but submitted and paid for by someone else, verified on-chain through `post_without_tip_sig`. See [Delegated & Gasless Posting](/social/delegated-posting). | | **Delegation** | In platform governance, assigning your voting power to another account so it votes on your behalf. Distinct from delegated posting. See [Delegation](/governance/delegation). | -| **DID** | *Decentralized identifier.* The W3C standard SuperheroID follows, linking a wallet, chain names and an X handle into one verifiable, portable identity. See [Identity and DIDs](/identity/did-standard). | +| **DID** | *Decentralized identifier.* An identifier defined by a DID method under the W3C DID Core model. SuperheroID maps onto some DID concepts but does not define its own DID method, document or resolver. See [Identity and DIDs](/identity/did-standard). | | **FATE VM** | The virtual machine that executes æternity smart contracts, optimised for functional-language execution. Sophia compiles to FATE instructions. See [Sophia & FATE](/aeternity/sophia-and-fate). | | **Indexer** | The off-chain service that subscribes to contract events and builds the queryable index behind `api.superhero.com`. It derives the feed, charts, market cap and trending scores; no contract reads any of them back. See [Architecture Overview](/concepts/architecture). | | **Invite link** | A one-time, AE-funded link that registers the claimer into your affiliation chain. The secret is in the link, so share it directly and never log or commit it. See [Invite Links](/rewards/invite-links). | | **Key-block** | A mined æternity block. Used as the time unit for governance: a DAO vote runs for two weeks measured in key-blocks, not wall clock. See [Quorum & Thresholds](/dao/quorum-and-thresholds). | -| **Market cap** | Price multiplied by circulating supply, quoted in AE. The default sort on the trending list, so larger communities surface first. See [Reading a Token Page](/tokens/token-page). | +| **Market cap** | Price multiplied by circulating supply, quoted in AE. The default sort for `GET /api/tokens` when `order_by` is omitted; the web app's main list explicitly requests trending-score sorting by default. See [Reading a Token Page](/tokens/token-page). | | **Middleware** | æternity's caching and reporting layer in front of the node, serving transaction history and other queries the node will not. Configured as `MIDDLEWARE_URL`. See [Networks & Endpoints](/aeternity/networks). | -| **Minimum token threshold** | The community token balance required for write access in a community, held in `CommunityManagement.aes` and changed only by a `ChangeMinimumTokenThreshold` DAO vote. Also the balance required to open a vote. See [Moderators & Write Thresholds](/dao/moderators). | +| **Minimum token threshold** | The community token balance required to enter a community's token-gated chat room, held in `CommunityManagement.aes` and changed only by a `ChangeMinimumTokenThreshold` DAO vote. Also the balance required to open a vote. See [Moderators & Write Thresholds](/dao/moderators). | | **Moderator** | An address in a community's moderator set, appointed and removed by `AddModerator` and `DeleteModerator` DAO votes. Moderators can mute and unmute user IDs; they cannot delete posts. See [Moderators & Write Thresholds](/dao/moderators). | -| **Muted user** | A user ID in a community's mute set. Clients hide muted content within that community; the underlying post remains in contract state and is readable by anything that ignores the list. See [Moderation](/social/moderation). | +| **Muted user** | A user ID in a community's mute set. The mute excludes the account from that community's chat eligibility; it does not hide its posts or comments. The underlying content remains in contract state. See [Moderation](/social/moderation). | | **Nostr** | The protocol behind Superhero's own chat, over the relay `wss://relay.superhero.chat`. Separate from anything on-chain. See [Chat](/social/chat). | | **Payout period** | The accounting bucket `AffiliationTreasury.aes` accrues referral rewards into before they can be withdrawn. See [The Affiliation System](/rewards/affiliation). | | **Poll** | A platform-wide governance vote against the governance registry contract, distinct from a community DAO vote. Stake-weighted; the official result is the stake-weighted tally, not the raw address count. See [Polls](/governance/polls). | @@ -46,13 +46,13 @@ Terms are alphabetical. Where a term has a colloquial name and a contract name, | **ProtocolDAO token** | A platform-wide AEX-9 token minted to the buyer on every community-token buy, intended as the foundation for future protocol governance. The governance functionality is not yet implemented. See [ProtocolDAO Token](/dao/protocol-dao). | | **Quorum** | The participation floor a DAO vote must clear to be executable: at least 10% of total token stake must vote. Separate from the 55% approval supermajority. See [Quorum & Thresholds](/dao/quorum-and-thresholds). | | **ReplaceableDAO** | The interface a community-supplied DAO must implement to be installed by a `ChangeDAO` vote. Requires `is_dao() = true` so a treasury cannot be transferred to a non-DAO address. See [Replaceable DAOs](/dao/replaceable-dao). | -| **Reserve** | The AE held by a token sale contract to redeem sellers. Grows by 0.995 of each buy's curve cost, which is exactly the sell-curve integral for that slice, so the full supply is always redeemable. See [Where the Money Goes](/concepts/value-flow). | +| **Reserve** | The AE held by a token sale contract to pay sellers. Each buy retains the quote for immediately selling its newly minted tokens, approximately 0.995 of the curve cost. See [Reserve accounting and rounding](/concepts/value-flow#reserve-accounting-and-rounding) for the continuous-model redemption argument. | | **Sale address** | The `ct_...` address of a token's bonding-curve sale contract, the contract that mints and burns tokens on the curve. The handle you use to buy, sell, look up a token, find its DAO, and join its chat room. See [AffiliationBondingCurveTokenSale](/contracts/token-sale). | | **Slippage** | The tolerance you allow between the quote you saw and the price you get. On a sell it is enforced on-chain as `minimal_return_required`; the transaction reverts rather than paying out below it. Defaults: 1% in the token trade card, 5% on the DEX, 3% in the agent CLI. See [Fees & Slippage](/tokens/fees-and-slippage). | | **Sophia** | æternity's functional smart-contract language. It is strongly typed, with restricted mutable state and no floating point. Every Superhero contract is written in it. See [Sophia & FATE](/aeternity/sophia-and-fate). | -| **Sponsored name claim** | One free `.chain` name per address, paid for by Superhero. The name must be longer than 12 characters excluding the suffix. Additional names are claimed in Superhero Wallet at your own cost. See [Claim Your .chain Name](/getting-started/claim-name). | -| **Spread** | The gap between the buy and sell curves: 1% in total, split 0.5% to the community DAO and 0.5% to the affiliation system. It is not billed as a separate fee; it is built into the two curves and collected entirely on the buy. See [Where the Money Goes](/concepts/value-flow). | -| **State channel** | An æternity layer-2 mechanism for off-chain transactions with on-chain settlement guarantees. Part of why æternity was chosen; not used by the Superhero contracts themselves. See [State Channels](/aeternity/state-channels). | +| **Sponsored name claim** | A Superhero-funded claim for an eligible `.chain` name, subject to sponsor availability and limited to one per address. The name must be longer than 12 characters excluding the suffix. Additional names can be claimed in Superhero Wallet at your own cost. See [Claim Your .chain Name](/getting-started/claim-name). | +| **Spread** | The difference between the all-in buy cost and sell return: 1% of the underlying curve value. It combines a 0.5% curve difference for the DAO with a 0.5% affiliation fee added on buys. See [Where the Money Goes](/concepts/value-flow). | +| **State channel** | An æternity layer-2 mechanism for two-party off-chain updates with on-chain settlement and dispute resolution. Superhero does not use state channels. See [State Channels](/aeternity/state-channels). | | **SuperheroID** | Superhero's on-chain identity: your wallet address plus your names and linked accounts, recorded as `AddressLink` provider links and mappable onto the W3C DID model. See [SuperheroID](/identity/superhero-id). | | **Tipping (v3)** | `Tipping.aes` version 3, the content contract. Holds every post in a map keyed by `tip_id`, supports direct and delegated posting, and emits `PostWithoutTipReceived`. See [Tipping (v3)](/contracts/tipping). | | **Token sale** | `AffiliationBondingCurveTokenSale.aes`. The contract you trade against: it holds the reserve, executes buys and sells, and routes the DAO and affiliation shares. See [AffiliationBondingCurveTokenSale](/contracts/token-sale). | diff --git a/pages/concepts/index.mdx b/pages/concepts/index.mdx index 0d63735..bfee998 100644 --- a/pages/concepts/index.mdx +++ b/pages/concepts/index.mdx @@ -1,23 +1,16 @@ --- title: "Core Concepts" -description: "Attention is the most valuable thing on the internet, and the people who create it have never owned it. Here is how Superhero changes that." +description: "Understand Superhero's architecture, on-chain social model, bonding-curve tokens and fee flows before building an integration." --- # Core Concepts -You have been early before. A song, a meme, a project, a community: you saw it before it broke -out, you told people, you helped it happen. Then the platform sold ads against the attention you -created, and you got a badge. - -**Superhero is built on the idea that being early should be worth something.** - -A post belongs to the person who wrote it, not to a database someone else controls. A trending -topic is a market you can back while it is still small, priced by -nothing but how many people arrived before you. The fees that trading generates flow into a -treasury the community votes on, instead of out to an advertiser. +Superhero combines on-chain posts, community tokens priced by bonding curves, and token-holder +governance. These pages explain the contracts and services behind those features, which data +is stored on chain, and how trading fees reach community treasuries and referrers. If you already know what a bonding curve is, skip ahead to -[Where the Money Goes](/concepts/value-flow); it answers the question everyone asks first. +[Architecture Overview](/concepts/architecture) or [Where the Money Goes](/concepts/value-flow). ## In this section @@ -41,11 +34,14 @@ by a `tip_id`. Nobody, including Superhero, can delete it afterwards. **Topics are tokens.** Any hashtag can be turned into an AEX-9 token whose price is a deterministic function of its own circulating supply. There is no order book and no counterparty: you buy from the -curve and sell back to it, and the contract holds a reserve large enough to redeem the entire supply. - -**The spread funds the community.** The gap between the buy curve and the sell curve is 1%. Half -goes to the token's own DAO treasury, half to a four-level referral chain. Token holders vote on -what the treasury does with it. +curve and sell back to it, using a reserve funded by buys. See +[Reserve accounting and rounding](/concepts/value-flow#reserve-accounting-and-rounding) for the +continuous-model redemption argument and its implementation limits. + +**The spread funds the community.** The spread is 1% of curve value, including the affiliation +fee added on buys. On each buy, half is allocated to the token's own DAO treasury and half to a +four-level referral chain, before integer rounding. Token holders vote on what the treasury does +with it. ## Related diff --git a/pages/concepts/on-chain-social.mdx b/pages/concepts/on-chain-social.mdx index 0985a74..d06bc85 100644 --- a/pages/concepts/on-chain-social.mdx +++ b/pages/concepts/on-chain-social.mdx @@ -15,7 +15,7 @@ Each post is a `PostWithoutTip` variant holding two things: | Field | Type | Contents | | --- | --- | --- | -| `tip_meta.sender` | `address` | The author. `Call.caller` for a direct post, the recovered signer for a delegated one | +| `tip_meta.sender` | `address` | The author. `Call.caller` for a direct post; for a delegated one, the `author` argument, after the contract verifies its signature | | `tip_meta.title` | `string` | The post text (the whole body, not a headline) | | `tip_meta.timestamp` | `int` | `Chain.timestamp` at the moment of posting | | `media` | `list(string)` | Media URLs or identifiers attached to the post | @@ -24,7 +24,8 @@ Posts live in a map indexed by a monotonically increasing integer `tip_id`, whic returns. This gives a deterministic, append-only ordering of every post ever published. `get_state()` returns the whole map, so anyone can reconstruct the complete post history without trusting an indexer. -The contract has exactly three entrypoints. There is no edit, and there is no delete. +The contract has three callable entrypoints (plus `init`, run once at deployment). There is no +edit, and there is no delete. ```text post_without_tip(title: string, media: list(string)) -> int @@ -49,7 +50,8 @@ threading is a client convention over an on-chain string. which is what lets a mention survive the mentioned user renaming themselves. The 280-character limit in the composer is a client default, not a contract rule. The contract -accepts any string; you pay gas proportional to its size. +accepts any string; a longer post costs more, because the transaction fee grows with its byte +size. **Superhero does not host media.** The composer has no upload. Both attachment buttons are pickers over third-party catalogues, and what they store is that provider's URL: @@ -82,13 +84,13 @@ records you as the author. The contract verifies it cryptographically: 4. Blake2b-hash that payload. 5. Verify the digest against the supplied signature and author address with `Crypto.verify_sig`. -The prefix is what stops a signature you produced for some other æternity protocol from being -replayed as a post. See [Delegated & Gasless Posting](/social/delegated-posting). +The framing separates personal-message signatures from transaction signatures. It does not +bind a post signature to a network or contract. See [Delegated & Gasless Posting](/social/delegated-posting). ## What a post costs -A post pays gas only: there is no posting fee, and a comment works the same way. Gas scales with -the size of the text you write and follows network conditions at submission time. +A post pays a network transaction fee and execution gas, with no additional posting fee. +A comment works the same way. The cost depends on transaction size, gas used and gas price. All an account needs to post is some AE in its wallet, which is why the agent skill's setup checks for a balance before an agent posts. See [AE & Gas](/aeternity/ae-and-gas) and @@ -156,8 +158,9 @@ The key convention belongs to the client that writes it. If you build a client t lists, read the existing set before assuming `ak_` addresses. **Write thresholds.** The same contract holds a `minimum_token_threshold`, the minimum balance of -the community's token required for write access in that community. It raises the cost of spamming a -community without granting anyone the power to erase what is already there. +the community's token required to enter its token-gated chat room and to open DAO votes. Feed +posting is not gated. It raises the cost of spamming the chat without granting anyone the power +to erase what is already there. Both levers are governed rather than administered. Muting requires `require_moderator()`, meaning membership of `moderator_accounts`. Everything else requires `require_owner()`, and the owner is the diff --git a/pages/concepts/value-flow.mdx b/pages/concepts/value-flow.mdx index 3771f04..e95c589 100644 --- a/pages/concepts/value-flow.mdx +++ b/pages/concepts/value-flow.mdx @@ -5,37 +5,38 @@ description: "The exact split of every AE spent on a community token buy — and # Where the Money Goes -Every AE that enters a community token trade ends up in one of four places: the bonding curve -reserve, the community's DAO treasury, the affiliation chain, or the network as gas. This page gives +AE spent on a community-token buy funds the sale reserve, the community DAO and affiliation +accounting. Network transaction fees and execution gas are paid separately. This page gives the full accounting, on both sides of a trade. ## The buy side -On every community-token **buy**: +For a community-token **buy**, let `C` be the curve cost before the affiliation fee. In the +continuous model, before integer rounding and assuming both treasury calls succeed: ```text -Buyer pays AE - ├── 99.0% → Bonding curve reserve (redeemable by sellers) - ├── 0.5% → Community DAO treasury (governed by token holders) - └── 0.5% → Affiliation system - ├── 0.300% → Level 1 referrer - ├── 0.125% → Level 2 referrer - ├── 0.050% → Level 3 referrer - └── 0.025% → Level 4 referrer - (if no referrer: burned) +Buyer pays 1.005 * C, excluding network charges + ├── 0.995 * C → Bonding curve reserve + ├── 0.005 * C → Community DAO treasury + └── 0.005 * C → Affiliation treasury + ├── 0.00300 * C → Level 1 referrer + ├── 0.00125 * C → Level 2 referrer + ├── 0.00050 * C → Level 3 referrer + └── 0.00025 * C → Level 4 referrer + (missing levels receive no ledger credit) Buyer also receives: └── ProtocolDAO tokens = 1,000 × AE value of the buy ``` -The 1% total spread is the difference between the buy curve and the sell curve. It is not -charged as a separate fee; it is built into the two curves. See +The total spread is 1% of `C`: a 0.5% curve difference plus the 0.5% affiliation fee added +on buys. Sells make no new DAO or affiliation allocation. See [Bonding Curves](/tokens/bonding-curve) for the math. ## The exact split -Write `C` for the **curve cost** of the slice you are buying: the integral of the buy curve from the -current supply to the supply after your purchase: +Write `C` for the **curve cost** of the slice you are buying. In the continuous model, this is the +integral of the buy curve from the current supply to the supply after your purchase: ```text C = integral of buy(x) dx, from supply to supply + amount @@ -54,8 +55,8 @@ function exp_helper(x : int, term : int, sum : int, i : int, scale : int) : int exp_helper(x, next_term, sum + next_term, i + 1, scale) ``` -The series matches the closed form to well below one aetto per token. Use the closed form to -reason about the shape; use `price(count)` when a number has to be exact. +Integer truncation means the closed form is not an exact transaction quote. Use it to reason +about the shape; use `price(count)` for the contract's quote. The sell curve is `sell(x) = buy(x) * 0.995`, and that 0.5% gap funds the DAO. The sale contract adds a further 0.5% affiliation fee **on top of** the curve price, so the total spread between buy and @@ -71,7 +72,8 @@ entrypoint price(count : int) : int = bonding_curve_price + affiliation_amount ``` -`price(n)` already equals `1.005 * C`; do not multiply it by 1.005 again. `buy` uses the same +`price(n)` already includes the affiliation fee, approximately `1.005 * C`; do not multiply it by +1.005 again. `buy` uses the same arithmetic and requires `Call.value >= total_price`, refunding any excess with `Chain.spend(Call.caller, overpaid_refund)`. That is why the agent CLI can attach `price * 1.03` and get the difference back. @@ -79,17 +81,18 @@ and get the difference back. The affiliation fee rate is read from the treasury at call time: `get_affiliation_fee_percentage()` returns `500` and `get_affiliation_fee_precision()` returns `10^5`, so 500 / 100,000 = 0.5%. -The buyer's gross is `1.005 * C`, and it splits exactly: +Before integer rounding, the buyer's gross is `1.005 * C`, and it splits as follows: | Destination | Amount | Share of what the buyer pays | | --- | --- | --- | | Bonding curve reserve | `0.995 * C` | 99.005% | | Community DAO treasury | `0.005 * C` | 0.4975% | -| Affiliation chain (or burned) | `0.005 * C` | 0.4975% | +| Affiliation treasury | `0.005 * C` | 0.4975% | | **Total** | `1.005 * C` | 100% | -`0.995 + 0.005 + 0.005 = 1.005`, with no remainder. The 99.0 / 0.5 / 0.5 figures above are this -split rounded to one decimal place. +`0.995 + 0.005 + 0.005 = 1.005` in this model. The percentages in this table are rounded; +the contract computes integer amounts as described below. Shares without an inviter receive +no ledger credit and stay in the affiliation treasury. The four affiliation levels are percentages **of the transaction value**, not of the fee, which is why they sum to 0.5% rather than to 100%. The transaction value handed to the treasury is `C`, the @@ -108,10 +111,10 @@ bare curve price, so level 1 receives 0.300% of `C`, not of `1.005 * C`. | 5 | `dao_contract.record_sale_transaction(...)` | `Call.value - overpaid_refund - affiliation_amount - reserve` | The DAO's cut in step 5 is a **residual**, not a percentage. `reserve` is -`calculate_sell_return(total_supply_after_mint, count)`, which is `0.995 * C`: exactly what a -seller of that same slice could immediately redeem. Subtracting it and the affiliation fee from -`1.005 * C` leaves `0.005 * C` for the DAO. The sale contract keeps precisely the sell-side -obligation and forwards the rest, which is what makes the solvency guarantee structural. +`calculate_sell_return(total_supply_after_mint, count)`, the exact integer quote for immediately +selling that same slice. It is approximately `0.995 * C`, leaving approximately `0.005 * C` for +the DAO after the affiliation fee. The sale contract retains that quote and forwards the +remainder. See [Reserve accounting and rounding](#reserve-accounting-and-rounding). Both treasury calls are made with `protected = true`, so a failure in the DAO or the affiliation treasury cannot block a buy. @@ -120,8 +123,10 @@ treasury cannot block a buy. Selling is not the buy flow in reverse. -**It is two transactions, not one.** AEX-9 has no transfer-from without prior approval, so you first -grant the sale contract an allowance over your tokens, then call sell: +**It is usually two transactions.** AEX-9 has no transfer-from without prior approval, so you first +grant the sale contract an allowance over your tokens, then call sell. With a sufficient standing +allowance `sell` alone works, but the app, bctsl-sdk and the agent CLI always send the allowance +step first: ```text 1. create_allowance(sale_account, count) on the community AEX-9 token @@ -152,10 +157,22 @@ return = integral of sell(x) dx, from supply - amount to supply | Affiliation chain | nothing | | ProtocolDAO tokens minted | none | -The 0.5% gap relative to the buy curve is not a sell fee. It was taken when those tokens were -bought. The reserve grows by `0.995 * C` per buy, which is exactly the sell-curve integral over the -same slice, so the reserve at supply `S` is always `integral of sell(x) from 0 to S`: precisely -enough to redeem the entire supply. Selling the entire supply back to the curve is always possible. +The 0.5% gap relative to the buy curve is not a sell fee. Its allocation to the DAO happens when +tokens are bought. + +### Reserve accounting and rounding + +For a history consisting of buys and sells in the ideal continuous model, each buy retains +the sell-curve integral over the newly minted slice. Those amounts add up to +`integral of sell(x) from 0 to S` at supply `S`, enough to redeem the full supply in that +model. Sells reduce the supply and reserve by the corresponding integral. A holder's direct +burn reduces supply without withdrawing AE, leaving additional reserve relative to that model. + +The implementation truncates each trade's quote separately, so the reserve can end a few aettos +per trade below the quote for selling the whole supply at once; after a history of buys only, it +is never above that quote. The shortfall is measured in aettos, but it means the very last full +exit can fail by that margin. Use `sell_return(count)` for the contract's quote and dry-run the +intended sell before submitting it. **Your tokens are burned.** Community tokens are minted on buy and burned on sell; the token contract's `Burn` event on the sell receipt carries the amount destroyed. @@ -170,7 +187,7 @@ contract's `Burn` event on the sell receipt carries the amount destroyed. 5. `Chain.spend(Call.caller, return)`, then emits `PriceChange` and `Sell`. The minimum tradable amount is enforced one level down: `calculate_price` requires -`count >= minimum_count`, where `minimum_count` is 10^12 aettos (10^-6 tokens). +`count >= minimum_count`, where `minimum_count` is 10^12 token base units (10^-6 tokens). The sale contract's trading entrypoints: @@ -180,7 +197,7 @@ The sale contract's trading entrypoints: | `sell` | `sell(count: int, minimal_return_required: int) -> int` | Stateful, **not** payable, returns the AE paid out | | `price` | `price(count: int) -> int` | The buy-side counterpart | | `buy` | `buy(count: int) -> unit` | Stateful, payable | -| `buy_with_affiliation` | `buy_with_affiliation(count: int, affiliation_rewardee: address) -> unit` | Stateful, payable | +| `buy_with_affiliation` | `buy_with_affiliation(count: int, affiliation_rewardee: address) -> unit` | Stateful, payable; factory-only (`ONLY_FACTORY_CAN_CALL`), used for the creator's initial buy | There is a `buy_with_affiliation` and no `sell_with_affiliation`: referral rewards accrue on buys only. Likewise the factory's `mint_protocol_dao_token(int, address)` is called on buys only. See @@ -261,8 +278,8 @@ Count transactions, not trades: | --- | --- | | Post or comment | 1 | | Buy a token | 1 | -| **Sell a token** | **2**: allowance, then sell | -| Create a token | 1 (deploys token, curve, sale, DAO and management contracts together) | +| **Sell a token** | **2**: allowance, then sell (1 with a sufficient existing allowance) | +| Create a token | 1 (deploys management, DAO, sale and token contracts; reuses the factory's curve and affiliation treasury) | | Open a DAO vote | 1, plus a **555 AE** payment to the DAO | | Create a governance poll | 2: deploy, then register | | Claim rewards | 1; a small gas fee applies | @@ -288,13 +305,15 @@ switch(get_direct_inviter(invitee)) update_inviters(inviter, buyer, transaction_value, remaining_affiliation_fee_percentages) ``` -No entry is credited for a missing level. The only way AE leaves the treasury is `withdraw()`, -which pays `get_accumulated_rewards(Call.caller)`, the sum of that caller's own ledger entries. +No entry is credited for a missing level. Referral rewards leave through `withdraw()`, +which pays `get_accumulated_rewards(Call.caller)`, the sum of that caller's eligible ledger entries. +Separately funded invitations also move AE through redemption and revocation. There is no owner, no admin entrypoint and no sweep, so uncredited AE stays in the contract balance permanently. (Creating a collection, by contrast, sends its 555 AE fee to the burn address `ak_11111111111111111111111111111111273Yts`.) -Two further amounts burn the same way, both consequences of `withdraw()`: +Two further categories of rewards can become permanently unwithdrawable, without being +transferred to a burn address: - **Rewards older than two payout periods.** `get_accumulated_rewards` sums only the current period and the one before it. A payout period is `Chain.timestamp / 2592000000` (30 days in diff --git a/pages/concepts/what-is-superhero.mdx b/pages/concepts/what-is-superhero.mdx index 272886b..4b35e25 100644 --- a/pages/concepts/what-is-superhero.mdx +++ b/pages/concepts/what-is-superhero.mdx @@ -29,7 +29,7 @@ one app, available on the web, as a mobile app, and as an installable PWA. | --- | --- | --- | | Publish a post | [superhero.com](https://superhero.com) feed, or the agent CLI | A `post_without_tip` call on the Tipping v3 contract; text and media URLs become contract state | | Tip a post | Post detail view | AE moves to the author's address | -| Create a community token | `superhero.com/trends/create` | The community factory deploys an AEX-9 token, a bonding curve, a token sale, a DAO and a management contract | +| Create a community token | `superhero.com/trends/create` | The factory creates a token, sale, DAO and management contract using a shared bonding curve | | Buy or sell a token | A token page's trade card | Tokens are minted or burned against AE along the bonding curve | | Open a DAO vote | `superhero.com/trends/daos` | A `DAOVote` contract is deployed; opening it costs 555 AE, paid to the DAO | | Vote on a platform poll | `superhero.com/voting` | A stake-weighted vote against the governance registry contract | @@ -43,19 +43,21 @@ contract call you sign yourself. **Tokens are priced by a formula.** There is no bid, no ask, no maker and no taker. You trade against a [bonding curve](/tokens/bonding-curve), and the price stays on that curve for the token's -whole life. There is no graduation to an AMM pool. The sale contract holds a reserve sufficient to -redeem the entire supply. +whole life. There is no graduation to an AMM pool. Buys fund the sale contract's reserve for +sellers. See [Reserve accounting and rounding](/concepts/value-flow#reserve-accounting-and-rounding) +for the continuous-model redemption argument and its implementation limits. **Everything runs on æternity.** Superhero is a set of Sophia contracts plus an indexer and a client. Community tokens are fungible AEX-9 tokens; `.chain` names are AENS entries. See [æternity Blockchain](/aeternity). -**Posts are permanent.** No one can delete a post from the Tipping contract. Moderation is a -community-scoped mute list plus client-side filtering. See [Moderation](/social/moderation) and +**Posts are permanent.** No one can delete a post from the Tipping contract. A community mute +excludes an account from its chat eligibility without hiding its posts or comments. See [Moderation](/social/moderation) and [On-Chain Social](/concepts/on-chain-social). -**Every token ships with a DAO.** Of the 1% trading spread, 0.5% goes to the token's own treasury -and 0.5% to a four-level referral chain. Token holders vote on what the treasury does. The +**Every token ships with a DAO.** Buys allocate approximately 0.5% of the curve cost to the token's +own treasury and add another 0.5% for affiliation accounting. Sells make no new allocation. +Token holders vote on what the treasury does. The ProtocolDAO token is issued on buys; its governance functionality is not yet implemented. ## Where the product lives diff --git a/pages/contracts/address-link.mdx b/pages/contracts/address-link.mdx index 78e8a31..88562d0 100644 --- a/pages/contracts/address-link.mdx +++ b/pages/contracts/address-link.mdx @@ -10,9 +10,10 @@ holding one value per provider (an X handle, a nostr public key, a preferred AEN also keeps a reverse index for resolving a value back to an address and a per-address nonce sequence for signed writes. -A link can be owned by a bare account, by an AENS name (a *principal*), or by a DID with a -controlling address. Each family has its own entrypoints, its own nonce space and its own -resolver. +Links are stored under the signer's address. The entrypoint families accept that address, +a principal (including an owned AENS name), or a `did:ae:` subject. All families share the +same links and nonce counter for that signer. The Superhero indexer reads only `link`, `unlink`, +`link_principal` and `unlink_principal` calls, so DID-entrypoint changes do not reach the API. ## State @@ -73,8 +74,11 @@ link:
::: unlink:
:: ``` -The principal variants substitute the AENS name for the address in the same layout. The -signature is 64 bytes, submitted as a 128-character hex string. A stale or reused nonce aborts +The principal variants substitute the principal for the address in the same layout; DID +variants use `did:ae:`. Sign the full text with SDK `signMessage`; +see [the framing](/identity/address-link#the-signed-message). The signature is 64 bytes; +the REST API takes 128 hex characters, while a direct SDK contract call takes the bytes. +A stale or reused nonce aborts with `INVALID_NONCE`; a signature that does not verify aborts with `INVALID_SIGNATURE`. ## Linking through the Superhero API @@ -84,10 +88,13 @@ REST surface is two calls per operation: | Step | Endpoint | What it does | | --- | --- | --- | -| 1 | `POST /address-links/{provider}/claim` | verifies you control the external account, reads `get_nonce`, and returns the exact message to sign | -| 2 | `POST /address-links/{provider}/submit` | takes `value`, `nonce` and `signature`, and relays the `link` call | -| 1 | `POST /address-links/{provider}/unclaim` | returns the unlink message and nonce | -| 2 | `POST /address-links/{provider}/unclaim/submit` | relays the `unlink` call | +| 1 | `POST /api/address-links/{flow}/claim` | validates the claim, reads the nonce, and returns the exact message to sign | +| 2 | `POST /api/address-links/{flow}/submit` | takes the signed claim and the flow's required proof, verifies it, and relays the link call | +| 1 | `POST /api/address-links/{flow}/unclaim` | returns the unlink message and nonce | +| 2 | `POST /api/address-links/{flow}/unclaim/submit` | relays the unlink call | + +The REST flow names are `x`, `nostr`, `site`, `bio` and `prefered-aens-name`. The last uses +the on-chain provider `prefaens` and the principal-based contract calls. See [Profile API](/api-reference/profile) for the request and response shapes. @@ -98,8 +105,8 @@ See [Profile API](/api-reference/profile) for the request and response shapes. | `get_links(addr)` | every link for an address, as `provider -> value` | | `get_link(addr, provider)` | one value, or `None` | | `resolve(provider, value)` | the address that owns `value` under `provider`, or `None` | -| `resolve_signer(principal)` | the account that signs for an AENS name | -| `resolve_did_controller(did)` | the controlling address of a DID | +| `resolve_signer(principal)` | the current AENS owner for a name-based principal; `None` for an address-based one | +| `resolve_did_controller(did)` | the current AENS owner for a `did:ae:` name subject; `None` for an address subject | | `get_provider_owner(provider)` | the account that owns a provider namespace | The Superhero API resolves an account's public name in the order: `prefaens` link, AENS name @@ -112,13 +119,17 @@ from the middleware, legacy username, raw address. The X handle is returned sepa | --- | --- | | `INVALID_SIGNATURE` | the signature does not verify against the message and address | | `INVALID_NONCE` | the nonce does not match `get_nonce` | -| `ALREADY_CLAIMED` | this provider is already linked to a different value for this address | -| `NOT_LINKED` | no link exists for this provider | +| `ALREADY_CLAIMED` | this provider value is already linked to a different address | +| `LINK_NOT_FOUND` | no link exists for this provider | | `NO_LINKS` | the address has no links at all | | `NOT_PROVIDER_OWNER` | the caller does not own the provider namespace | -| `PRINCIPAL_NOT_FOUND` | the AENS name does not resolve | -| `PRINCIPAL_MISMATCH` | only the name owner can link or unlink | -| `INVALID_PRINCIPAL` | the principal string is malformed | +| `PRINCIPAL_NOT_FOUND` | the `.chain` name has no active registration (never claimed, in auction, expired or revoked) | +| `PRINCIPAL_MISMATCH` | the signer does not own the `.chain` name, or a non-name principal is not the signer's address | +| `INVALID_PRINCIPAL` | the principal (after any `did:ae:` prefix) contains a colon | +| `EMPTY_PRINCIPAL` / `PRINCIPAL_TOO_LONG` | the principal is empty or longer than 200 characters | +| `INVALID_DID` | not `did:ae:` followed by a subject | +| `EMPTY_VALUE` / `VALUE_TOO_LONG` / `INVALID_VALUE` | the value is empty, longer than 200 characters, or contains a colon | +| `PROVIDER_NOT_FOUND` | no such provider is registered | ## Events @@ -131,8 +142,9 @@ datatype event = | PrincipalUnlink(address, string) ``` -Every event carries an `address` topic and a `string` in `data`. On the link events the -`data` string is `provider:value`, colon-joined. Topic hashes are in the +Every event carries an `address` topic and a `string` in `data`. `Link` and `Unlink` carry +`provider:value`, including the removed value on unlink. Principal events carry +`principal|provider:value`. Topic hashes are in the [event catalogue](/contracts/events). ## Related diff --git a/pages/contracts/aex9.mdx b/pages/contracts/aex9.mdx index b4dadf2..391f9fc 100644 --- a/pages/contracts/aex9.mdx +++ b/pages/contracts/aex9.mdx @@ -120,14 +120,15 @@ token_contract = Chain.create(name, decimals, symbol, None) : FungibleTokenFull ``` Because `Chain.create` runs inside the sale contract, the sale contract is the token's -`owner`, and that is what authorises `mint` on a buy and `burn` on a sell. +`owner`, and that is what authorises `mint` on a buy. On a sell, it first transfers your +tokens into its own balance, then burns them from that balance. `initial_owner_balance` is `None`, so a new community token starts at zero total supply: every token in existence was minted by a buy. The name and the symbol are the same string, because `CommunityFactory.create_community` passes its `name` argument to both positions. ## Allowances -Two Superhero flows require an allowance before they work: +These bonding-curve and DAO flows require an allowance before they work: | Flow | Grant the allowance to | | --- | --- | @@ -149,6 +150,9 @@ Three entrypoints manage the value: | `change_allowance(for_account, value_change)` | Adds a delta to an existing allowance. The delta may be negative. | Adjusting an existing allowance | | `reset_allowance(for_account)` | Sets it to zero. | Revoking | +Resetting leaves the allowance record in place. To grant it again afterwards, use +`change_allowance`; `create_allowance` still rejects the existing record. + The pattern: ```javascript @@ -165,9 +169,10 @@ if (existing === undefined) { } ``` -`allowance` returns `option(int)`, so a never-granted allowance decodes to `undefined`. The -`.catch(() => undefined)` covers a call that aborts on a missing entry rather than returning -`None`. +`allowance` returns `option(int)` and never aborts on a missing entry: a never-granted allowance +decodes to `undefined`. The `.catch(() => undefined)` therefore only hides unrelated failures +(network, wrong address, ACI mismatch) and would route them into `create_allowance`; drop it or +rethrow in production code. `allowance_for_caller(from_account)` is the same read from the spender's side. @@ -179,16 +184,21 @@ if (existing === undefined) { - On a sell, the sale contract pulls your tokens with `transfer_allowance` and calls `burn`, and supply goes down. -Both are owner-gated. For a community token the owner is the sale contract, so the only way to -increase supply is to pay the curve. That is what makes `total_supply()` a reliable input to a -price calculation. +Only `mint` is owner-gated. For a community token the owner is the sale contract, so new +tokens are issued through curve buys. Any holder can call `burn(value)` to destroy tokens +from their own balance without receiving AE. Direct burns also reduce the supply used by +the curve; they are different from selling tokens through the sale contract. ## The swap extension -`swap`, `swapped` and `check_swap` come from the AEX-9 swappable extension, which migrates -balances from an older token contract into a newer one: `swap()` credits the caller based on -their balance in the predecessor and records the amount in the `swapped` map. Superhero does -not use this path; for a factory-created token `swapped()` is empty. +In this implementation, `swap()` burns the caller's entire current balance, writes that +amount to `swapped[caller]`, and emits `Swap`. `check_swap(account)` reads the stored amount, +defaulting to zero. A later call overwrites that account's stored amount rather than adding +to it. + +This call neither reads a predecessor token nor credits replacement tokens. A migration +would need a separate receiving contract or process; `swap()` alone destroys the current +tokens without paying AE or issuing another token. It is also unrelated to a DEX swap. `aex9_extensions()` returns the list of extension names the contract implements. It is the standard's own discovery mechanism, so call it instead of assuming. diff --git a/pages/contracts/affiliation-treasury.mdx b/pages/contracts/affiliation-treasury.mdx index e71e697..a15fb1e 100644 --- a/pages/contracts/affiliation-treasury.mdx +++ b/pages/contracts/affiliation-treasury.mdx @@ -49,7 +49,7 @@ Or resolve it at runtime with `factory.affiliation_treasury()`. Its interface is datatype unique_invitees_state = ThresholdReached | WaitingForInvitations(Set.set(address), map(address, int)) - // invitees seen, per-invitee buy volume + // invitees at 10 AE, volume of those below it record state = { payout_periods : map(int, map(address, int)) @@ -195,8 +195,9 @@ datatype unique_invitees_state = | WaitingForInvitations(Set.set(address), map(address, int)) ``` -While an account is `WaitingForInvitations`, the contract holds the set of invitees seen so -far and how much each of them has bought. Two constants govern the transition: +While an account is `WaitingForInvitations`, the contract holds the set of invitees who have +reached 10 AE of recorded buys, and the running volume of invitees still below it (an invitee +leaves the map on reaching 10 AE). Two constants govern the transition: | Constant | Value | Meaning | | --- | --- | --- | @@ -252,7 +253,7 @@ stateful entrypoint withdraw() = ### Rewards expire -Anything credited three or more buckets ago is no longer withdrawable. Because buckets are +Anything credited two or more buckets before the current one is no longer withdrawable. Because buckets are absolute rather than relative to when you earned, the grace period is **between 30 and 60 days**: a reward credited on the first day of a bucket survives that bucket plus the whole of the next one; a reward credited on the last day of a bucket has a few hours plus 30 days. diff --git a/pages/contracts/bonding-curve.mdx b/pages/contracts/bonding-curve.mdx index 8e6ea9c..432460c 100644 --- a/pages/contracts/bonding-curve.mdx +++ b/pages/contracts/bonding-curve.mdx @@ -14,30 +14,31 @@ when you call the curve directly; `BondingCurve.aci.json` is the interface the s ## Entrypoints -Everything here is non-stateful and free to call. +Everything here is non-stateful. The SDK dry-runs these calls by default without a network fee; +broadcasting a contract-call transaction still incurs network charges. | Entrypoint | Signature | What it gives you | | --- | --- | --- | | `calculate_buy_price` | `(total_supply: int, count: int) => int` | Cost in aettos of buying `count` more tokens at a given supply | | `calculate_sell_return` | `(total_supply: int, sell_tokens: int) => int` | AE returned for selling `sell_tokens` at a given supply | -| `buy_price` | `(total_supply: int) => int` | The instantaneous buy price at that supply | -| `sell_price` | `(total_supply: int) => int` | The instantaneous sell price at that supply | +| `buy_price` | `(total_supply: int) => int` | Ceiling of the spot ratio in AE per whole token, not a quote in aettos | +| `sell_price` | `(total_supply: int) => int` | Floor of the sell spot ratio in AE per whole token, not a quote in aettos | | `buy_curve` | `(x: int) => Frac.frac` | The raw buy curve value as an exact rational | | `sell_curve` | `(x: int) => Frac.frac` | The raw sell curve value as an exact rational | | `get_k` | `() => int` | Exponent coefficient | -| `get_initial_price` | `() => int` | Curve offset constant | +| `get_initial_price` | `() => int` | Spot buy price at supply 0 (`10^11` aettos, 0.0000001 AE per token); the offset `a - initial_price` is not stored | | `get_minimum_count` | `() => int` | Smallest tradable count | | `get_sell_return_percentage` | `() => int` | The sell factor numerator | -| `get_sell_return_precision` | `() => int` | The sell factor denominator | +| `get_sell_return_precision` | `() => int` | Getter intended to expose the sell factor denominator; see the implementation note below | | `curve_type` | `() => string` | Curve identifier | | `supported_decimals` | `() => int` | Token decimals the curve is calibrated for | The `BondingCurve` interface declares the same eight computational entrypoints with unnamed arguments (`_1`, `_2`), which is why the sale contract's ACI shows them that way. -`calculate_buy_price` and `buy_price` take a **supply**, not a count. The token sale's -`price(count)` takes a count and reads the current supply for you. Mixing them up produces -prices that are wrong by many orders of magnitude. +`buy_price(total_supply)` takes a supply. `calculate_buy_price(total_supply, count)` takes +both the starting supply and the count to buy, in token base units. The token sale's +`price(count)` takes only a count and reads the current supply for you. Use `calculate_buy_price` and `calculate_sell_return` for quotes. @@ -49,7 +50,7 @@ Use `calculate_buy_price` and `calculate_sell_return` for quotes. | `k` | `1 * 10 ^ 10` | 10,000,000,000 | | `initial_price` | `1 * 10 ^ 11` | 100,000,000,000 | | `decimals` | `1 * 10 ^ 18` | 10^18 | -| `minimum_count` | `1 * 10 ^ 12` | 10^12 aettos, i.e. 10^-6 of a token | +| `minimum_count` | `1 * 10 ^ 12` | 10^12 token base units, i.e. 10^-6 of a token | | `sell_return_percentage` | `9950` | 99.50% | | `sell_return_precision` | `10000` | the denominator of that percentage | | `curve_type()` | `"TAYLOR_EXPONENTIAL_V1"` | n/a | @@ -83,6 +84,12 @@ That 0.5% is the DAO's half of the spread. The sale contract adds the other 0.5% affiliation fee on the way in, which is how the round trip reaches a 1% total spread while the curve itself only knows about 0.5%. +`get_sell_return_precision()` returns `sell_return_percentage` (`9950`), not the internal +denominator `10000` that the calculation uses. This is a getter bug in +[`BondingCurveExponential.aes`](https://github.com/bctsl/bctsl-contracts/blob/02e5dc1acb31729b7f0e4c2c72bcd9e381c9d9dc/contracts/BondingCurveExponential.aes), +and the deployed mainnet curve `ct_6E78VvU5Raz7g6oaGymF2eMNG7FjVToS6JA4AqoufaWF6sTXd` returns +`9950` from both getters. Do not derive the sell factor by dividing the two getters. + ## What the contract evaluates FATE has no floating point, so the contract replaces `e^x` with a **bounded Maclaurin (Taylor) @@ -124,12 +131,13 @@ Two things bound the series: truncates to zero makes every later term zero too. At realistic supplies this fires long before the iteration cap. -The approximation error is negligible: the on-chain result and the closed form agree to within -2e-16 AE at supply 0 and 1.4e-12 AE at supply 10,000,000, far below one aetto of a per-token -price. Quote the closed form for explanation; call `calculate_buy_price` for money. +For a count of 1,000 whole tokens, the integer calculation differs from the idealised integral +by less than one aetto at starting supplies 0 and 10,000,000. This is a check of those +examples, not a bound for arbitrary inputs. Use the closed form for explanation and +`calculate_buy_price` for a transaction quote. `calculate_price` carries the only `require` on the curve: a `count` below `minimum_count` -(10^12 aettos) aborts with `MINIMUM_TOKENS_REQUIRED`. That applies to `calculate_buy_price` and +(10^12 token base units) aborts with `MINIMUM_TOKENS_REQUIRED`. That applies to `calculate_buy_price` and `calculate_sell_return` alike, because both route through it. `buy_curve` and `sell_curve` are a separate code path. They call `exp_helper` with the full @@ -197,9 +205,13 @@ console.log({ - **Price is a pure function of supply.** There is no time component, no oracle and no liquidity provider. Two buys of the same size at the same supply cost the same. - **`minimum_count` is 10^12 base units.** With 18-decimal tokens that is 0.000001 of a token. - Quotes below it are not meaningful. -- **The curve is steep by design.** It is calibrated so the price rises noticeably from the - very first buys; only 10–20% of the nominal supply is expected to be reached. + Calls below it abort with `MINIMUM_TOKENS_REQUIRED`. +- **Price grows exponentially with supply.** Use the actual supply and trade size when + calculating a quote; this curve does not define a maximum token supply. +- **Integer quotes do not prove aggregate solvency.** Separately rounded trade quotes need not + sum to the quote for their combined amount. See + [Reserve accounting and rounding](/concepts/value-flow#reserve-accounting-and-rounding) for the + continuous-model redemption argument and its implementation limits. ## Related @@ -207,4 +219,4 @@ console.log({ - [Curve parameters](/tokens/curve-parameters): the same constants from a trader's point of view - [AffiliationBondingCurveTokenSale](/contracts/token-sale): the contract that calls this one - [Calling Contracts](/contracts/calling-contracts): how to run the snippets above -- [Sophia standard library](https://docs.aeternity.com/aesophia/v7.0.1/sophia_features/): where `Frac` is defined +- [Sophia standard library](https://github.com/aeternity/aesophia/blob/master/docs/sophia_stdlib.md): where `Frac` is defined diff --git a/pages/contracts/calling-contracts.mdx b/pages/contracts/calling-contracts.mdx index a1af62a..b59a870 100644 --- a/pages/contracts/calling-contracts.mdx +++ b/pages/contracts/calling-contracts.mdx @@ -13,7 +13,7 @@ aborts. ## Install ```bash -npm install @aeternity/aepp-sdk bignumber.js +npm install @aeternity/aepp-sdk@14.1.0 bignumber.js ``` The code below targets `@aeternity/aepp-sdk` 14. @@ -115,7 +115,7 @@ console.log('events:', result.decodedEvents.map((e) => e.name)); | `Contract.initialize` | Needs `aci` plus `address`. Pass `onNode` always, and `onAccount` only when you intend to sign. Without `onAccount` the instance can still do read calls. | | `.decodedResult` | Every call returns a result envelope. `decodedResult` is the value, already decoded against the ACI: integers come back as `BigInt`, records as plain objects, maps as `Map`. | | `{ amount }` | The AE attached to a payable call, in aettos (1 AE = 10^18 aettos). | -| `omitUnknown: true` | Drops call-option keys the SDK does not recognise instead of throwing. Set it on every write. | +| `omitUnknown: true` | Skips emitted events for which the supplied ACIs have no definition. Without it, an unknown event can make decoding throw even after a transaction succeeds. | ### Arguments and types @@ -153,11 +153,11 @@ await dao.add_vote( Two different things are called "dry run". -**A non-stateful entrypoint is already free.** `price`, `sell_return`, `buy_price`, +**The SDK dry-runs non-stateful entrypoints by default.** `price`, `sell_return`, `buy_price`, `balance`, `meta_info`, `total_supply`, `has_community` and every other read in these contracts is declared without `stateful` in the ACI. The SDK resolves them through the node's -dry-run endpoint automatically: no transaction is created, no gas is spent, no account is -needed. That is why the price quote in the example above costs nothing. +dry-run endpoint automatically without broadcasting a transaction or charging a network fee. +Execution still has a gas limit. That is why the price quote in the example above costs nothing. **A stateful entrypoint can be dry-run explicitly** by passing `callStatic: true`. The node executes the call against current state and returns the result and the events it would emit, @@ -176,8 +176,8 @@ dry run exactly as it would on chain, without costing a transaction fee. ## Gas estimation and gas limits -`result.result.gasUsed` on a dry run is the measured consumption for that call against -current state, and `result.gasPrice` is the price the call paid. Set an explicit `gasLimit` +`dry.result.gasUsed` is the measured consumption for a dry-run call against current state. +A dry-run does not pay a gas charge. Set an explicit `gasLimit` from the measurement with a margin: ```javascript @@ -199,7 +199,7 @@ Two caveats: aggressively; let the SDK use its default unless you have measured repeatedly. You can also set `gasPrice` explicitly. Leave it alone unless you are fighting for inclusion; -the SDK's default tracks the node's minimum. +SDK v14.1.0 estimates it from recent node gas prices and utilisation, with a `1e9` aetto floor. ## Decoding events @@ -259,7 +259,7 @@ Revert strings you are most likely to hit, with the contract that raises them: | `VOTE_RESULT_TIMEOUTED` | `DAO.apply_vote_subject` | The execution window after close height has passed. | | `VOTE_NOT_YET_FINAL` | `DAO.apply_vote_subject` | The vote has not closed yet. | | `COLLECTION_CREATION_DONATION_MISMATCH` | `create_collection` | The attached amount is not exactly 555 AE. | -| `collection_ALREADY_EXISTS` | `create_collection` | That collection name is taken. | +| `collection_ALREADY_EXISTS` | `create_collection` | The raw input equals an existing suffixed collection id; a repeat of a plain name is not caught | | `MINIMUM_REDEMPTION_AND_FEE_NOT_MEET` | `register_invitation_code` | `redemption_fee_cover` is below 0.001 AE. | | `INVITATION_AMOUNT_AND_FEE_NOT_MATCHING` | `register_invitation_code` | Attached AE is not exactly `(fee + amount) * number of invites`. | | `NOT_KNOWN_TOKEN_SALE` | `mint_protocol_dao_token` | Called by something the factory did not deploy. | diff --git a/pages/contracts/community-factory.mdx b/pages/contracts/community-factory.mdx index 953f982..6d99255 100644 --- a/pages/contracts/community-factory.mdx +++ b/pages/contracts/community-factory.mdx @@ -20,7 +20,7 @@ It is deployed once per network and reused for every collection and community af `CommunityFactory.aci.json` also carries the inlined interfaces of `DAO`, `DAOVote`, `CommunityManagement`, `AffiliationTreasury`, `VoteSubjects`, `Frac` and `FungibleTokenFull`. -Four values are fixed, so you never need a node to know them: +The factory exposes these identifiers and fee parameters: | Call | Returns | Note | | --- | --- | --- | @@ -30,7 +30,7 @@ Four values are fixed, so you never need a node to know them: | `fee_precision()` | `100000` | passthrough to `AffiliationTreasury.get_affiliation_fee_precision()` | `fee_percentage() / fee_precision()` is `500 / 100000`, or 0.5%. Divide the two rather than -hardcoding 0.005; both are passthroughs and a treasury redeployment could move them. +hardcoding 0.005. Both are passthroughs, so read them from the deployed factory when integrating. ## Entrypoints @@ -90,7 +90,7 @@ dash". Decoded in JavaScript, each entry is a one-key object: ```javascript const chars = await factory.allowed_name_chars(collectionId).then((r) => r.decodedResult); -// [ { CharRangeFromTo: [ 65n, 90n ] }, { CharRangeFromTo: [ 48n, 57n ] }, { SingleChar: [ 45n ] } ] +// [ { SingleChar: [ 45n ] }, { CharRangeFromTo: [ 48n, 57n ] }, { CharRangeFromTo: [ 65n, 90n ] } ] ``` `CommunityManagement.meta_info` is `map(string, string)`: free-form key/value metadata with @@ -137,8 +137,11 @@ create_collection("WORDS", ...) called by ak_alice... ``` That returned string is the id every later call must use, and it is why collection ids in the -Superhero API are typed as `${string}-${Encoded.AccountAddress}`. Creating a collection whose -name already exists aborts with `collection_ALREADY_EXISTS` (note the lowercase first letter). +Superhero API are typed as `${string}-${Encoded.AccountAddress}`. `collection_ALREADY_EXISTS` +checks the raw input against registry keys before the caller suffix is appended, so it never +stops a repeat: calling `create_collection` again with the same name from the same account burns +another 555 AE and replaces the collection's registry entry with an empty one. See +[Collections & Naming](/tokens/collections-and-naming). Any account may register a collection, with any naming rules. The collections the Superhero app lists on mainnet (`WORDS`, `CHINESE`, `ARABIC` and `RUSSIAN`) are a curated set @@ -207,9 +210,11 @@ const amount = new BigNumber(onChainPrice.toString()) The client-side estimate only picks a count; the chain always sets the price. Pass `0n` as the supply to `calculate_buy_price` because a brand-new community starts at zero supply. -Overpayment is refunded by the sale contract, so the buffer is safe. +Overpayment is refunded by the factory before the buy, so the buffer is safe. -Pass `initial_buy_count` as `0` and attach no AE to create a token with zero supply. +Pass `initial_buy_count` as `0` and attach no AE to create a token with zero supply. Any AE +attached when `initial_buy_count` is `0` stays in the factory permanently: there is no refund or +withdrawal. ## Minting ProtocolDAO tokens diff --git a/pages/contracts/community-management.mdx b/pages/contracts/community-management.mdx index a36d36f..ec66f8a 100644 --- a/pages/contracts/community-management.mdx +++ b/pages/contracts/community-management.mdx @@ -125,8 +125,9 @@ function require_moderator() = ``` Moderators are not owners: a moderator cannot add another moderator, change the -threshold, or touch the metadata. The owner is not automatically a moderator either, so the DAO -cannot mute anyone without first voting itself onto the moderator set. The initial moderator +threshold, or touch the metadata. The owner is not a moderator, and the stock DAO has no vote +subject that calls `mute_user_id`, so it can never mute anyone directly: it acts by appointing +or removing moderators. Only a replacement DAO could add a mute path. The initial moderator is the community creator, set once in `init`; the owner becomes the DAO immediately afterwards. Muting is the one action that does not need a vote: governance sets the policy and appoints diff --git a/pages/contracts/dao-vote.mdx b/pages/contracts/dao-vote.mdx index 3454a40..2f3c2c1 100644 --- a/pages/contracts/dao-vote.mdx +++ b/pages/contracts/dao-vote.mdx @@ -201,8 +201,8 @@ const inFavour = current.get(true) ?? 0n; const against = current.get(false) ?? 0n; ``` -The map is keyed by the boolean option, and an option nobody has voted for is absent. That is why -the code uses `?? 0n`. +The map is keyed by the boolean option. Both keys exist from `init` (set to `0`) and are never +removed, so `?? 0n` is only defensive. ## Passing conditions diff --git a/pages/contracts/dao.mdx b/pages/contracts/dao.mdx index 86b0339..85e938f 100644 --- a/pages/contracts/dao.mdx +++ b/pages/contracts/dao.mdx @@ -81,10 +81,10 @@ require(Option.default(0, token.balance(Call.caller)) >= minimum_token_threshold The threshold is a balance check at call time. Proposing locks no tokens; only voters lock stake, when they call `DAOVote.vote`. -`add_vote` does not check a payout amount against the treasury balance. A `VotePayout` or -`VotePayoutAmount` for more AE than the DAO holds is accepted and can pass, and then fails at -execution when `apply_vote_subject` reaches `Chain.spend`. Check the treasury balance before -proposing an amount. +`add_vote` does not check a payout amount against the treasury balance. A `VotePayoutAmount` +for more AE than the DAO holds is accepted and can pass, and then fails at execution when +`apply_vote_subject` reaches `Chain.spend`. Check the treasury balance before proposing an +amount. `VotePayout` has no amount: it pays whatever the balance is at execution. ```javascript const result = await dao.add_vote( @@ -126,8 +126,10 @@ In JavaScript each is a one-key object whose value is an array of the constructo arguments: `{ VotePayoutAmount: ['ak_...', '1000000000000000000'] }`, and for the map-valued one, `{ ChangeMetaInfo: [new Map([['description', 'new text']])] }`. -The Superhero app's create-vote form offers `VotePayout`, `ChangeDAO`, `AddModerator` and -`DeleteModerator`. All seven subjects are callable directly. +The Superhero app's create-vote form lists several subject types, but it currently submits every +proposal as `VotePayout()`, whatever type is selected: choosing `ChangeDAO` +there proposes paying the whole treasury to that address. Open the other subjects through the +SDK or a direct call; all seven are callable directly. ## Executing a vote diff --git a/pages/contracts/events.mdx b/pages/contracts/events.mdx index d1b9bb0..7d91efd 100644 --- a/pages/contracts/events.mdx +++ b/pages/contracts/events.mdx @@ -94,8 +94,8 @@ datatype event = | `CreateCommunity` | `9838227481037218045844062460739435620538960633417016110994140287779986845610` | | `CreateCollection` | `106451687811681430585235988806070705060981919041452525929915952793933471156443` | -`CreateCommunity` is the most useful event in the system for an indexer: one log entry gives -you a new community's name and all three of its contract addresses. +`CreateCommunity` gives an indexer a new community's name and its DAO, sale and management +addresses. Read `token_contract()` on the sale for the fourth, the AEX-9 token address. ### AffiliationBondingCurveTokenSale @@ -252,12 +252,13 @@ datatype event = | `PrincipalLink` | `33734067034041800501097175880685404869663974342910460138405033266635271063644` | | `PrincipalUnlink` | `65650841556643744410284701498125626234659108343589856439166449381677919258575` | -Every one carries an `address` topic and a `string` in `data`. The `Link` / `Unlink` pair -covers account links; the `Principal` pair covers links made against an AENS name. +Every one carries an `address` topic and a `string` in `data`. `Link` and `Unlink` carry +`provider:value`, including the removed value on unlink. Non-address principals additionally +emit `PrincipalLink` or `PrincipalUnlink` with `principal|provider:value`. -**The `data` string on a link event is `provider:value`, colon-joined.** Split it on the -first colon. Provider ids match `/^[a-z]{1,10}$/`, so a value may contain a colon but a -provider id may not. `prefaens` is the provider id for a preferred AENS name. +Provider ids match `/^[a-z]{1,10}$/`, and values may not contain a colon. `prefaens` is the +provider id for a preferred AENS name. For a principal event, remove the known principal and +its `|` separator before parsing the provider and value. ### Tipping v4 @@ -274,7 +275,7 @@ datatype event = PostViaBurnReceived(tip_id, address, string, TokenContract) ## Name collisions: filter by contract, always The topic hash is computed from the name alone. It carries no contract identity and no -argument types. Three names collide across the suite: +argument types. Two names collide across the suite: | Name | Emitted by | Arguments | | --- | --- | --- | @@ -282,7 +283,6 @@ argument types. Three names collide across the suite: | `Vote` | `Poll` | `(address, address, int)` | | `RevokeVote` | `DAOVote` | `(address, bool, int)` | | `RevokeVote` | `Poll` | `(address, address)` | -| `AddModerator` / `DeleteModerator` / `ChangeMinimumTokenThreshold` | `CommunityManagement` events | also `VoteSubjects.subject` constructor names | A `Vote` log from a governance poll and a `Vote` log from a community DAO have the same topic hash and different argument shapes. An indexer that matches on `topics[0]` alone and then @@ -304,8 +304,9 @@ for (const e of result.decodedEvents) { } ``` -`decodedEvents` covers events from **every** contract the call touched, so a buy gives you the -sale's `Buy` and `PriceChange` plus both `Mint` events. Match on `e.contract.address` to tell +`decodedEvents` can include events from every contract the call touched when their definitions +are available in the supplied ACIs. `omitUnknown: true` skips unknown events; it does not +decode them. Match on `e.contract.address` to tell the community token's mint from the ProtocolDAO token's: ```javascript @@ -319,7 +320,7 @@ const tokenMint = result.decodedEvents.find( For transactions you did not submit, query the middleware's contract log index: ```text -GET {middlewareUrl}/v3/contracts/logs?contract_id={ct_...}&tx_hash={th_...}&limit=100 +GET {middlewareUrl}/v3/contracts/{ct_...}/logs?event=Mint&limit=100 ``` | Network | Middleware base URL | @@ -327,46 +328,50 @@ GET {middlewareUrl}/v3/contracts/logs?contract_id={ct_...}&tx_hash={th_...}&limi | Mainnet | `https://mainnet.aeternity.io/mdw` | | Testnet | `https://testnet.aeternity.io/mdw` | -Drop `tx_hash` to get a contract's full log history, paged. Each entry carries `topics` as an -array of big-integer strings and `data` as the string payload, so matching is a string compare -against the hashes above: +Omit `event` for the contract's full log history. Middleware logs use `args` for the indexed +arguments and `event_hash` for the constructor hash; they do not expose the node's `topics` +array. With the default argument formatting, indexed arguments are decimal strings and the +constructor hash is not included in `args`: ```javascript -const MINT_TOPIC = '97248968993606906149864095761415446114204891017168990930824289305879066770211'; - const res = await fetch( - `https://mainnet.aeternity.io/mdw/v3/contracts/logs?contract_id=${saleAddress}&limit=100`, + `https://mainnet.aeternity.io/mdw/v3/contracts/${tokenAddress}/logs?event=Mint&limit=100`, ); +if (!res.ok) throw new Error(`Middleware returned ${res.status}`); const { data } = await res.json(); -const mints = data.filter((log) => log.topics?.[0] === MINT_TOPIC); -for (const log of mints) { - console.log('account topic:', log.topics[1], 'value:', log.topics[2]); +for (const log of data) { + console.log('account topic:', log.args[0], 'value:', log.args[1]); + console.log('transaction:', log.call_tx_hash); } ``` -A log entry also carries `event_hash` and, when the middleware can resolve the contract's -ACI, a decoded `event_name` and an `args` array: +A log entry also carries the transaction hash, payload and an event name when the middleware +recognises the event through its built-in definitions or configured custom events: ```javascript const eventHash = log.event_hash; -const eventName = log.event_name; // may be absent -const addressTopic = log.args?.[0]; // decoded topic arguments +const eventName = log.event_name; // may be null +const addressTopic = log.args[0]; // numeric topic string by default const payload = log.data; ``` `event_hash` is the same 32-byte Blake2b-256 digest as `topics[0]`, encoded as padded base32hex (RFC 4648's extended-hex alphabet, not standard base32). Match on `event_hash` when you want a stable identifier, and on `event_name` only as a convenience, since it is present only -when the middleware has the contract's ACI. +when the middleware recognises the event. `aexn-args=true` and `custom-args=true` enable +additional formatting for supported events. Non-UTF-8 payloads are returned as base64. + +To select the logs of a known transaction, pass `scope=transaction:th_...` to the log query, or +read its raw logs from the node's `GET /v3/transactions/{hash}/info` response. Two operational notes: -- **Paginate.** The response carries a `next` field with a relative path. Follow it until it - is absent; do not assume one page is the whole history. +- **Paginate.** The response carries a `next` field with a path relative to the middleware base + URL (append it after `/mdw`). Follow it until it is absent; do not assume one page is the whole history. - **Logs lag the transaction.** A transaction hash is available the moment it is mined, but - the middleware may not have indexed its *logs* yet, so a `tx_hash`-filtered query can return - an empty list for a transaction that emitted events. Retry, or reconcile in a later + the middleware may not have indexed its *logs* yet, so its logs can be missing from the + indexed history. Retry, or reconcile in a later catch-up pass. ## Live subscriptions @@ -402,7 +407,7 @@ and `token-history`. See [WebSocket API](/api-reference/websocket). ## Related - [Calling Contracts](/contracts/calling-contracts): `decodedEvents` in context, plus reverts and gas -- [AffiliationBondingCurveTokenSale](/contracts/token-sale): where the four events of a buy come from +- [AffiliationBondingCurveTokenSale](/contracts/token-sale): the core buy events and additional treasury logs - [Node and middleware API](/api-reference/node-and-middleware): the middleware endpoints in full - [WebSocket API](/api-reference/websocket): the Superhero API's own real-time channels - [æternity contract events specification](https://github.com/aeternity/protocol/blob/master/contracts/events.md): the topic and data encoding rules diff --git a/pages/contracts/governance-contracts.mdx b/pages/contracts/governance-contracts.mdx index 6a28e6e..27ea990 100644 --- a/pages/contracts/governance-contracts.mdx +++ b/pages/contracts/governance-contracts.mdx @@ -236,7 +236,7 @@ await poll.revoke_vote(); // retract ``` There is no stake, no allowance and no lock. A vote is a single map entry keyed by your -address, and `revoke_vote` deletes it. Voting on a poll costs only gas. +address, and `revoke_vote` deletes it. Voting on a poll costs a transaction fee and execution gas. `vote(option)` requires that the poll is open (`POLL_ALREADY_CLOSED`) and that the option exists (`VOTE_OPTION_NOT_KNOWN`). It overwrites any earlier vote by the same address, so diff --git a/pages/contracts/index.mdx b/pages/contracts/index.mdx index 7b79531..eecc1db 100644 --- a/pages/contracts/index.mdx +++ b/pages/contracts/index.mdx @@ -28,9 +28,10 @@ events each one emits, and how to call all of it from JavaScript. | [`Registry.aes` / `Poll.aes`](/contracts/governance-contracts) | æternity governance polls | | [`AddressLink`](/contracts/address-link) | Identity: provider-keyed links from an address to an X handle, AENS name or nostr key | -`DAO`, `DAOVote`, `CommunityManagement`, `AffiliationTreasury`, `VoteSubjects`, `Set`, `Frac` -and `FungibleTokenFull` have no ACI file of their own: the compiler inlines them into -`CommunityFactory.aci.json`. Load the factory ACI when you need any of those interfaces. +`DAO`, `DAOVote`, `CommunityManagement` and `AffiliationTreasury` have their own ACI files in +`bctsl-contracts/generated/`, and `FungibleTokenFull` in `aeternity-fungible-token/generated/`; +all are also inlined in `CommunityFactory.aci.json`. `VoteSubjects`, `Set` and `Frac` exist only +inlined, so load the factory ACI when you need one of those. ## How the pieces fit together diff --git a/pages/contracts/security.mdx b/pages/contracts/security.mdx index f9ee9ec..c4ac42d 100644 --- a/pages/contracts/security.mdx +++ b/pages/contracts/security.mdx @@ -14,8 +14,13 @@ the gates around governance. The contracts have not undergone a third-party secu Sophia is a strongly typed functional language with **no arbitrary mutable global state**. Each contract has exactly one `state` value, replaced wholesale rather than mutated in place. Every FATE instruction is typed, and a type mismatch aborts the call and reverts every change. -Together these remove the class of failure that dominates EVM incident reports: partially -updated state surviving a failed call, and reentrancy against a half-written storage slot. +These rules help catch type and state-update errors. They do not establish that a contract is +secure or remove the need to review external calls, authorisation checks and state-update order. + +FATE also rejects remote calls into a contract already executing on the call stack. This is +enforced by the VM's +[`check_reentrant_remote`](https://github.com/aeternity/aeternity/blob/d3efeb60/apps/aefate/src/aefa_engine_state.erl) +check, rather than following from the type system or the use of a single `state` value. ## Cryptographic integrity @@ -25,8 +30,8 @@ updated state surviving a failed call, and reentrancy against a half-written sto `Crypto.verify_sig`. The message is framed with the æternity signed-message prefix, the 28-byte constant `#1a61657465726e697479205369676e6564204d6573736167653a0a20`, which decodes to a length byte, `aeternity Signed Message:` with a newline, and a second length byte. That -framing prevents a signature produced in another æternity protocol context from being replayed -as a post. The post signature carries no nonce; relayers track which signed posts they have +framing separates personal-message signatures from transaction signatures. It does not bind +the signature to a network or contract address. The post signature carries no nonce; relayers track which signed posts they have already submitted. See [Tipping v3](/contracts/tipping). ### Identity linking @@ -42,13 +47,14 @@ are verifiable directly against the naming system. See [AddressLink](/contracts/ ## Economic security -- **Bonding curve solvency.** The sell curve sits strictly below the buy curve at every supply - level, so the AE reserve held in the sale contract always covers buying back the entire - circulating supply. There is no bank-run state. The gap is the 0.5% sell factor - (`sell_return_percentage = 9950`) plus the 0.5% affiliation fee added at the sale layer. -- **Fixed spread allocation.** The 1% spread splits 0.5% to the community DAO and 0.5% to the - affiliation system, with the split fixed in the contracts. On a sale, the contract retains - exactly what it would owe if the same count were sold straight back, and only the remainder +- **Bonding curve reserve.** Each buy retains the quote for immediately selling its newly + minted tokens. These amounts cover full redemption in the ideal continuous model, but + integer rounding requires separate analysis. See + [Reserve accounting and rounding](/concepts/value-flow#reserve-accounting-and-rounding). +- **Fixed spread allocation.** The spread is 1% of curve value: approximately 0.5% of that + value is allocated to the community DAO and 0.5% to affiliation on buys, before integer + rounding. On a buy, the contract retains the + immediate sell quote for that count, and only the remainder after the affiliation fee reaches the DAO. - **Collection creation is burned, not collected.** `create_collection` requires exactly 555 AE and spends it to `ak_11111111111111111111111111111111273Yts`, the burn address. @@ -109,13 +115,14 @@ are verifiable directly against the naming system. See [AddressLink](/contracts/ - **Minting is gated to known sales.** `mint_protocol_dao_token` requires `Set.member(Call.caller, state.known_token_sales)` and aborts with `NOT_KNOWN_TOKEN_SALE`. Only sale contracts the factory itself deployed can mint protocol tokens. Community token - supply is likewise owner-minted: the owner is the sale contract, so supply tracks the curve. + issuance is likewise owner-gated: the owner is the sale contract. Holders can separately + burn their own tokens without receiving AE. ## Related - [Deployed Addresses](/contracts/addresses): what is deployed, per network - [DAO](/contracts/dao): the vote execution gates described above -- [BondingCurveExponential](/contracts/bonding-curve): the solvency property in detail +- [BondingCurveExponential](/contracts/bonding-curve): integer pricing and rounding - [Token risks](/tokens/risks): the same picture for someone deciding how much to put in - [Wallet security](/wallets/security): key handling, the risk most users actually face - [Registry and Poll](/contracts/governance-contracts): the æternity governance contracts and the off-chain tally diff --git a/pages/contracts/tipping.mdx b/pages/contracts/tipping.mdx index ddafdf0..9e87015 100644 --- a/pages/contracts/tipping.mdx +++ b/pages/contracts/tipping.mdx @@ -143,8 +143,9 @@ are opaque references that the frontend renders as links or embeds. ## Delegated posting `post_without_tip_sig` lets any account submit a post on behalf of an author who signed it off -chain. This is how gasless posting works: the user signs a message in their wallet, a relayer -pays the fee, and the on-chain record still attributes the post to the signer. +chain. This is how gasless posting works: the author signs the post digest off chain (a +standard wallet `signMessage` cannot produce this signature), a relayer pays the fee, and the +on-chain record still attributes the post to the signer. The entire verification: @@ -205,18 +206,28 @@ framing: 5. ok = Crypto.verify_sig(digest, author, sig) ``` -Steps 3 and 4 are exactly what the SDK's `signMessage` does to whatever you hand it, so from a -key the whole author side is two calls: +SDK v14's `account.signMessage` accepts text. This contract expects the raw 32-byte inner +digest as the message body, so construct the framing explicitly and sign its hash: ```javascript -import { signMessage, hash } from '@aeternity/aepp-sdk'; +import { MemoryAccount, hash } from '@aeternity/aepp-sdk'; +const account = new MemoryAccount(process.env.AE_PRIVATE_KEY); // sk_... secret const message = title + media.join(''); -const signature = signMessage(hash(message), secretKey); +const inner = hash(Buffer.from(message, 'utf8')); +const payload = Buffer.concat([ + Buffer.from([0x1a]), + Buffer.from('aeternity Signed Message:\n', 'utf8'), + Buffer.from([0x20]), + inner, +]); +const signature = await account.unsafeSign(hash(payload)); ``` Note what is being signed: the **32-byte inner digest**, not the text. Handing a wallet's -`signMessage` the raw post text produces a different digest and the call reverts. +`signMessage` the raw post text, or a hex string of the digest, produces a different digest +and the call reverts. `unsafeSign` signs exactly the bytes supplied; use it here only with +the contract-specific digest above. ## Notes @@ -229,6 +240,7 @@ takes an explicit `nonce` on every signed write. - [Posting](/social/posting): what posting looks like from the app, and what the API adds on top - [Delegated posting](/social/delegated-posting): the relayer flow end to end - [Tipping](/social/tipping): the spend-with-payload mechanism +- [SDK v14.1.0 account implementation](https://github.com/aeternity/aepp-sdk-js/blob/v14.1.0/src/account/Memory.ts): `signMessage` and `unsafeSign` - [Events](/contracts/events): the topic hash for `PostWithoutTipReceived` and how to subscribe - [Calling Contracts](/contracts/calling-contracts): SDK setup, gas, and reading revert reasons - [aeternity/tipping-contract](https://github.com/aeternity/tipping-contract): the contract family's source diff --git a/pages/contracts/token-sale.mdx b/pages/contracts/token-sale.mdx index 3ed7a80..e33692e 100644 --- a/pages/contracts/token-sale.mdx +++ b/pages/contracts/token-sale.mdx @@ -80,8 +80,9 @@ record state = , dao_contract : ReplaceableDAO } ``` -`get_state()` is the way to get the DAO address from the sale, because the factory has no getter for -it. +`beneficiary()` returns the DAO (decoded as `ak_`; swap the prefix to `ct_`), and so does `owner()` +unless a replacement DAO has moved ownership; `get_state().dao_contract` gives it as `ct_`. The +factory has no getter for it. ## Events @@ -102,7 +103,7 @@ entrypoints capture it before the mint or burn and emit that value at the end. `PriceChange` carries unit prices sampled before and after the trade. `calculate_unit_price()` is `price(10 ^ 18)`, the cost of one whole token *including* the affiliation fee. -A single `buy` emits four events across three contracts: +An ordinary `buy` includes these four core events across the sale and the two token contracts: | Event | Emitted by | Carries | | --- | --- | --- | @@ -111,6 +112,11 @@ A single `buy` emits four events across three contracts: | `PriceChange` | the sale | previous unit price, next unit price | | `Buy` | the sale | total price paid, affiliation amount, pre-buy total supply | +When the protected affiliation-treasury call succeeds, the receipt also includes its +`RecordSaleTransaction` event and a `RewardAdded` event for each credited referral level. +These treasury events are absent if that protected call fails. A replacement DAO can emit +additional events from its own income handler, so this table is not a fixed receipt length. + Distinguish the two `Mint` events by the emitting contract address, not by order. On the sale contract itself `PriceChange` is emitted **before** `Buy` and before `Sell`. @@ -172,9 +178,11 @@ In the order the contract pays them, for a buy of `count` tokens: | Reserve | stays in this contract | `calculate_sell_return(new_supply, count)` | | Spread | `DAO.record_sale_transaction` | whatever is left | -The reserve line is the solvency mechanism: the contract retains exactly what it would owe if -that same `count` were sold straight back, and only the remainder reaches the DAO. It is -computed against the supply **after** the mint. +The reserve line funds sellers: the contract retains the integer quote for immediately selling +that same `count`, and only the remainder after the affiliation fee reaches the DAO. It is +computed against the supply **after** the mint. See +[Reserve accounting and rounding](/concepts/value-flow#reserve-accounting-and-rounding) for the +continuous-model redemption argument and its implementation limits. Both outbound contract calls are made with `protected = true`, so a DAO or treasury that aborts cannot block a buy. The AE stays in the sale contract. @@ -267,9 +275,10 @@ state.token_contract.transfer_allowance(Call.caller, Contract.address, count) Passing `0` as `minimal_return_required` disables slippage protection. Quote first and set a floor on every live trade. -There is no revert for "the reserve is empty". The sell curve sits strictly below the buy -curve at every supply level, so the reserve always covers a full buy-back of the circulating -supply. +`sell` pays the quoted return with `Chain.spend`, which requires enough AE in the sale contract. +Buys retain the immediate sell quote to fund that reserve. The continuous-model argument for +full redemption needs separate integer-rounding analysis; see +[Reserve accounting and rounding](/concepts/value-flow#reserve-accounting-and-rounding). ## Ownership and beneficiary diff --git a/pages/dao/index.mdx b/pages/dao/index.mdx index 5c40625..bd64ba2 100644 --- a/pages/dao/index.mdx +++ b/pages/dao/index.mdx @@ -19,7 +19,7 @@ The two systems use separate contracts, separate voting power and separate parts | Contracts | `DAO.aes`, `DAOVote.aes` | `Registry.aes`, `Poll.aes` | | Scope | One community token's treasury | The æternity ecosystem as a whole | | Voting power | That community's AEX-9 token balance | AE balance, plus delegated AE | -| Tokens locked while voting | Yes. An AEX-9 allowance locks your stake | No | +| Tokens locked while voting | Yes. The vote contract receives your stake through an AEX-9 allowance | No | | Ballot shape | Binary: in favour or against | Any list of at least two options | | Outcome | Executes an on-chain action | Signalling; no automatic execution | | Where in the app | `/trends/daos` and `/trends/dao/:saleAddress` | `/voting` | @@ -44,7 +44,7 @@ A community's contracts are deployed together, in one transaction, by ## The lifecycle -1. Trading fees accumulate in the DAO treasury: 0.5% of every buy. +1. Each buy allocates approximately 0.5% of its curve value to the DAO treasury, before integer rounding. 2. A holder at or above the community threshold opens a vote, paying **555 AE** to the DAO. 3. The vote stays open for **two weeks**, measured in key-blocks. 4. Holders vote for or against by locking tokens in the vote contract. diff --git a/pages/dao/moderators.mdx b/pages/dao/moderators.mdx index 76669de..2c38f35 100644 --- a/pages/dao/moderators.mdx +++ b/pages/dao/moderators.mdx @@ -1,12 +1,13 @@ --- title: "Moderators & Write Thresholds" -description: "How a community controls who can post in it — the CommunityManagement contract, moderator powers, and the minimum token threshold." +description: "How a community controls who can open proposals and join its chat room — the CommunityManagement contract, moderator powers, and the minimum token threshold." --- # Moderators & Write Thresholds A community's governance layer and its moderation layer are the same thing. Moderators are -appointed and removed by DAO vote; the token balance you need to post is changed by DAO vote. +appointed and removed by DAO vote; the token balance you need to join the community's chat room and to open proposals is changed by +DAO vote. Both live in one contract, `CommunityManagement.aes`, deployed alongside the DAO when the community is created. @@ -69,9 +70,9 @@ transaction. See [Replaceable DAOs](/dao/replaceable-dao). ## The minimum token threshold `minimum_token_threshold` is the amount of the community's own token an account needs to -write in the community. It has a second job: it is also the bar for **opening a DAO -proposal**. Raising the threshold makes a community both harder to post in and harder to -propose in; lowering it does the reverse. +join and post in the community's token-gated chat room. It has a second job: it is also the bar +for **opening a DAO proposal**. Raising the threshold makes the chat room harder to enter and +proposals harder to open; lowering it does the reverse. Posting to the public feed is not gated. Read it directly: @@ -83,8 +84,8 @@ The value is in the token's smallest unit. Divide by `10^decimals` (read `decima token's `meta_info()`) before comparing it to a balance shown in a wallet. Every community starts at `10^18`, one whole token, until a `ChangeMinimumTokenThreshold` vote moves it. -The contract stores the threshold and hands it out. The app and the backend enforce it for -posting (see [Moderation](/social/moderation)), and `DAO.add_vote` enforces it for +The contract stores the threshold and hands it out. The backend enforces it for chat-room +membership (see [Moderation](/social/moderation)), and `DAO.add_vote` enforces it for proposals, requiring the proposer's balance to clear it. ### Choosing one diff --git a/pages/dao/overview.mdx b/pages/dao/overview.mdx index 5b99145..d29b1ad 100644 --- a/pages/dao/overview.mdx +++ b/pages/dao/overview.mdx @@ -11,8 +11,8 @@ follow a real proposal on-chain. ## The lifecycle -1. Trading fees accumulate in the DAO treasury: **0.5% of every buy** on the community's - bonding curve. +1. Each buy allocates approximately **0.5% of its curve value** to the DAO treasury, + before integer rounding. 2. Any holder at or above the community threshold opens a vote through `DAO.add_vote(metadata)`, paying **555 AE** to the DAO. 3. The vote stays open for **two weeks**, measured in key-blocks. @@ -35,7 +35,8 @@ CommunityFactory.create_community(collection_name, name, initial_buy_count, The `DAO` is created as both the **owner** and the **beneficiary** of the token sale. The same call deploys `CommunityManagement` with an initial moderator and an initial minimum token -threshold, plus the sale contract, the bonding curve and the AEX-9 token. +threshold, plus the sale contract and the AEX-9 token. The sale references the factory's +shared bonding curve and affiliation treasury. The DAO's state: diff --git a/pages/dao/proposals.mdx b/pages/dao/proposals.mdx index b329f65..7023770 100644 --- a/pages/dao/proposals.mdx +++ b/pages/dao/proposals.mdx @@ -20,7 +20,7 @@ In ACI order, which is also the variant tag order used on the wire: | 1 | `VotePayoutAmount` | `address`, `int` | Disburse a **specified amount** to that account | | 2 | `ChangeDAO` | `address` | Transfer the treasury, the token sale's ownership and beneficiary rights, and ownership of community management to another DAO | | 3 | `ChangeMetaInfo` | `map(string, string)` | Replace the community's metadata map in community management | -| 4 | `ChangeMinimumTokenThreshold` | `int` | Change the minimum token threshold for write access and for opening proposals | +| 4 | `ChangeMinimumTokenThreshold` | `int` | Change the minimum token threshold for chat-room access and for opening proposals | | 5 | `AddModerator` | `address` | Appoint a moderator | | 6 | `DeleteModerator` | `address` | Remove a moderator | @@ -91,9 +91,13 @@ Two guards protect the migration: - **The target must already reference the same `CommunityManagement`.** Deploy the replacement DAO pointing at the existing community management contract before the vote is applied; otherwise the whole transaction reverts and nothing moves. +- **The target must be a `payable contract`.** The treasury moves with `Chain.spend`, which + aborts when the target is not payable, even for a zero balance. -`set_beneficiary` on the sale also runs its own `verify_dao` probe against the new address, so -a target whose `record_sale_transaction` is not payable fails there. +`set_beneficiary` on the sale also probes the new address with a zero-value +`record_sale_transaction` call. That catches a missing entrypoint or a wrong signature, but not a +handler that is not `payable`: such a DAO passes migration, and each later buy's DAO share then +stays in the sale contract. `is_dao()` is a shape check, not a trust check. Any contract can return `true` from it. Read [Replaceable DAOs](/dao/replaceable-dao) before voting on a `ChangeDAO` proposal. @@ -155,8 +159,10 @@ shows the decoded subject and its payload. ### From the app Open the community's DAO at `/trends/dao/:saleAddress`, fill in the create-vote form, and -confirm the 555 AE payment in your wallet. `VotePayoutAmount` and `ChangeMetaInfo` proposals -are opened through the SDK or a direct contract call. The vote's detail page decodes and +confirm the 555 AE payment in your wallet. The form currently submits every proposal as +`VotePayout` to the contract address you enter, whatever type you select, so it can only propose +paying the whole treasury to a `ct_` address. Open every other subject, and any payout to an +`ak_` account, through the SDK or a direct contract call. The vote's detail page decodes and displays the subject that was signed. ## Related diff --git a/pages/dao/protocol-dao.mdx b/pages/dao/protocol-dao.mdx index 6a7588b..be3f001 100644 --- a/pages/dao/protocol-dao.mdx +++ b/pages/dao/protocol-dao.mdx @@ -44,9 +44,11 @@ stateful entrypoint mint_protocol_dao_token(buy_value : int, receiver : address) state.protocol_dao_token.mint(receiver, buy_value * protocol_dao_token_multiplier) ``` -`known_token_sales` is populated by `create_community` and nothing else. There is no owner -mint and no other issuance path, so ProtocolDAO supply is exactly 1,000 times the AE ever -spent buying community tokens through the factory. +`known_token_sales` is populated by `create_community` and nothing else. The factory mints +only through these buy paths, so cumulative issuance is 1,000 times the AE actually paid +for those purchases after refunds. Outstanding supply can be lower: holders can burn their +own ProtocolDAO tokens, including through the token's `swap()` entrypoint. See +[Mint and burn](/contracts/aex9#mint-and-burn). The token contract is an ordinary `FungibleTokenFull` with 18 decimals, so the whole AEX-9 surface applies: `balance`, `total_supply`, `transfer`, `create_allowance` and the rest. Its diff --git a/pages/dao/replaceable-dao.mdx b/pages/dao/replaceable-dao.mdx index 1d79cb0..a219dd4 100644 --- a/pages/dao/replaceable-dao.mdx +++ b/pages/dao/replaceable-dao.mdx @@ -5,19 +5,19 @@ description: "The ReplaceableDAO interface a custom DAO must implement, and how # Replaceable DAOs -Sophia contracts are immutable once deployed, and Superhero's contracts have no proxy, no -admin key and no migration hook. A community that wants different governance rules cannot -patch `DAO.aes`. What it can do is deploy a **different DAO contract** and vote to hand over +Sophia contract code is immutable once deployed. A community that wants different governance +rules cannot patch its deployed `DAO.aes`. It can deploy a **different DAO contract** and vote to hand over control. `ReplaceableDAO.aes` defines the interface that makes that possible, and `ChangeDAO` is the vote that performs it. What survives a migration: the AEX-9 token keeps its address, its supply and its holders; the -bonding curve keeps its reserve and its price; the community keeps its name and its posts. +sale contract keeps its reserve and its pricing curve; the community keeps its name and its posts. Only the contract that owns the sale and holds the treasury is replaced. ## The interface -A contract that implements all three entrypoints can be the target of a `ChangeDAO` vote: +A `payable contract` that implements all three entrypoints can be the target of a `ChangeDAO` vote +(a non-payable target makes the treasury transfer abort): | Entrypoint | Signature | Purpose | | --- | --- | --- | @@ -50,14 +50,19 @@ contract can implement `is_dao() = true`. ## Build a replacement DAO -1. **Write the contract in Sophia.** Implement `is_dao`, `get_community_management` and - `record_sale_transaction` with exactly the signatures above. Sophia type-checks the - interface, so a mismatched arity or a missing `payable` fails at the call site. +1. **Write the contract in Sophia.** Declare it `payable contract`: `ChangeDAO` moves the old + treasury with `Chain.spend`, which aborts when the target is not payable, even for a zero + balance. Implement `is_dao`, `get_community_management` and `record_sale_transaction` with + the signatures above, including a `payable` income handler. The sale's zero-value probe + checks that the handler can be called, but not that it accepts a payment: a DAO with a + non-payable handler passes migration, and each later buy's DAO share then stays in the sale + contract. Check that behavior separately before migration. 2. **Decide what it does with authority.** The replacement becomes the owner and beneficiary of the existing `AffiliationBondingCurveTokenSale`, and the owner of the existing `CommunityManagement`. If it does not expose equivalents of `add_vote` and `apply_vote_subject`, the community loses the ability to appoint moderators or change its - write threshold, because those actions can only be reached by the sale's owner. + write threshold, because `CommunityManagement` accepts those calls only from its own owner, + which the migration sets to the replacement DAO. 3. **Point it at the existing `CommunityManagement`.** `apply_vote_subject` asserts `get_community_management() == new_dao.get_community_management()` and aborts the whole migration with `NEW_DAO_HAS_TO_REFERENCE_SAME_COMMUNITY_MANAGEMENT` if they differ. The @@ -97,7 +102,7 @@ spent and the proposal has to be reopened. | `CommunityManagement` ownership | Yes | `community_management.set_owner(new_dao_address)` | | The moderator roster, mute list, threshold and metadata | Untouched | They live in `CommunityManagement`, which is not redeployed | | The AEX-9 token, its supply and its holders | Untouched | Not owned by the DAO | -| The bonding curve and its reserve | Untouched | Held by the sale contract, which is not replaced | +| The bonding curve and the reserve | Untouched | The reserve is the sale contract's AE balance; the curve is the factory's shared `BondingCurveExponential`. Neither is replaced | | The vote history | **Not transferred** | `DAO.votes` stays on the old contract, which keeps answering `votes()` | Because `CommunityManagement.set_owner` is called in the same transaction, the diff --git a/pages/dao/treasury.mdx b/pages/dao/treasury.mdx index 37dd714..69cda45 100644 --- a/pages/dao/treasury.mdx +++ b/pages/dao/treasury.mdx @@ -6,19 +6,21 @@ description: "Where a community DAO's AE comes from, how to read the balance on- # The DAO Treasury A community DAO holds plain AE. There is no separate vault contract, no wrapped balance and -no staking position. The treasury is the AE balance of the `DAO` contract, and the only way -it leaves is a payout vote that passes and is applied in time. +no staking position. The treasury is the AE balance of the `DAO` contract. Funds can leave +through an approved payout or move to a replacement DAO through an approved `ChangeDAO` vote. ## Where the money comes from | Source | Amount | Path into the DAO | | --- | --- | --- | -| Buys on the bonding curve | 0.5% of the curve value of every buy | `record_sale_transaction(buyer, buy_price)` | +| Buys on the bonding curve | Approximately 0.5% of the curve value of every buy | `record_sale_transaction(buyer, buy_price)` | | Opening a proposal | 555 AE per vote opened | `add_vote(metadata)`, which is payable | | A `ChangeDAO` migration into this DAO | The whole balance of the old DAO | `Chain.spend` from the old DAO | +| Direct donations | Any amount | AE spent to the payable DAO contract, or attached to `record_sale_transaction` | -Nothing else pays the treasury. Sells do not, because the 1% spread is charged on the buy -side; tips and posts do not, because they settle through `Tipping_v3`, not the token sale. +Sells do not automatically fund the treasury, because the spread is collected on the buy +side. Posts go through `Tipping_v3`, and tips are direct AE spend transactions to authors; +neither funds the DAO. The DAO's share is not computed as a percentage. The sale sets the redemption reserve aside first and forwards what is left: @@ -29,9 +31,10 @@ state.dao_contract.record_sale_transaction( value = Call.value - overpaid_refund - affiliation_amount - reserve, protected = true, ...) ``` -`total_supply()` has already been incremented by the mint, so `reserve` is exactly `0.995 ×` -the curve price and the DAO receives the residual `0.5%`. Setting the payout obligation aside -before the treasury is paid is what keeps the reserve solvent. +`total_supply()` has already been incremented by the mint, so `reserve` is the integer quote for +immediately selling that same count, approximately `0.995 ×` the curve price. The DAO receives +the residual, approximately `0.5%`. This funds sellers in the continuous model; integer rounding +needs separate analysis. See [Reserve accounting and rounding](/concepts/value-flow#reserve-accounting-and-rounding). The call is `protected = true`, so a DAO call that aborts does not block the trade; the AE stays in the sale contract. See [Value flow](/concepts/value-flow) and diff --git a/pages/dao/voting.mdx b/pages/dao/voting.mdx index cabbabb..474221a 100644 --- a/pages/dao/voting.mdx +++ b/pages/dao/voting.mdx @@ -91,13 +91,14 @@ The relevant AEX-9 entrypoints: | `allowance(allowance_accounts)` | Read the current allowance; returns `option(int)` | | `create_allowance(for_account, value)` | Create an allowance where none exists | | `change_allowance(for_account, value_change)` | Adjust an existing allowance by a delta | -| `reset_allowance(for_account)` | Remove the allowance entirely | +| `reset_allowance(for_account)` | Set an existing allowance to zero, retaining its record | | `allowance_for_caller(from_account)` | Read the allowance granted to you by another account | `allowance` takes a record (`allowance_accounts` is `from_account` plus `for_account`) and returns `None` when no allowance exists. Calling `create_allowance` when one already exists fails; calling `change_allowance` when none exists fails too, so handle the two cases -separately. +separately. After a reset, the record still exists with value zero; use `change_allowance` +to grant it again. ### Code @@ -216,7 +217,7 @@ contract state. See [Contract events](/contracts/events). the bonding curve; revoking is the only early exit. - **Voting power is plain token weight.** A single holder above 55% of participating stake decides any vote they show up for. The 10% quorum limits capture by tiny minorities only. -- **The allowance persists** until you reset it. It is scoped to one vote contract. +- **Transfers consume the allowance.** Any unused approval is scoped to that vote contract and remains until used, reduced or reset. - **Nothing reminds you to withdraw.** Closed votes do not return tokens automatically. ## Related diff --git a/pages/defi/bridge.mdx b/pages/defi/bridge.mdx index 8c17f54..00028c6 100644 --- a/pages/defi/bridge.mdx +++ b/pages/defi/bridge.mdx @@ -26,12 +26,12 @@ by contrast, is backed by AE held in one contract on one chain. æternity operates its own Ethereum bridge, documented on the [æternity docs hub](https://docs.aeternity.com/aeternity-user-tools-and-services/aerc-bridge). -To get AE from ETH without bridging at all, use one of the swap aggregators listed under +To get AE without bridging at all, buy it on an exchange; see [Buying AE](/defi/buy-ae). ## Related -- [Buying AE](/defi/buy-ae): exchanges and ETH-to-AE swap aggregators. +- [Buying AE](/defi/buy-ae): earning AE, or buying it on Gate.io. - [Swapping](/defi/swap): trade aeETH you already hold. - [Wrapped AE](/defi/wrapped-ae): the DEX's wrapper for native AE. - [DeFi & DEX overview](/defi): the full route map and contract addresses. diff --git a/pages/defi/buy-ae.mdx b/pages/defi/buy-ae.mdx index 2661072..0d260d0 100644 --- a/pages/defi/buy-ae.mdx +++ b/pages/defi/buy-ae.mdx @@ -1,6 +1,6 @@ --- title: "Buying AE" -description: "Earn AE inside Superhero, or buy it from the exchanges and swap aggregators the Get AE page links to." +description: "Earn AE inside Superhero, or buy it on Gate.io, the exchange the Get AE page links to." --- # Buying AE @@ -9,7 +9,7 @@ AE is the native coin of the æternity blockchain. You need it to pay transactio community tokens on the bonding curve, swap on the DEX, and fund invite links. The Get AE page at `https://superhero.com/get-ae` collects every route: ways to earn AE inside -Superhero, and exchanges and swap aggregators where you can buy it. The older `/buy-ae` path +Superhero, and Gate.io for buying it. The older `/buy-ae` path redirects there. ## Earn AE diff --git a/pages/defi/explore.mdx b/pages/defi/explore.mdx index ea58394..f135fc1 100644 --- a/pages/defi/explore.mdx +++ b/pages/defi/explore.mdx @@ -45,7 +45,7 @@ GET /api/dex/tokens `listed` filters to listed or unlisted tokens; omit it to return both, which is what the web UI shows. Tokens start unlisted, and the flag is set by the Superhero operator through the -API-key-protected `POST /api/dex/tokens/
/listed`. +API-key-protected `PATCH /api/dex/tokens/{address}/listed` (see [DEX API](/api-reference/dex)). Endpoints for a single token: diff --git a/pages/defi/index.mdx b/pages/defi/index.mdx index 1bb3dd6..42abf5a 100644 --- a/pages/defi/index.mdx +++ b/pages/defi/index.mdx @@ -23,11 +23,12 @@ prices for the same token are independent, and nothing arbitrages them automatic | Counterparty | The curve contract's reserve | Other liquidity providers | | Contracts | `AffiliationBondingCurveTokenSale`, `BondingCurveExponential` | `AedexV2Router`, `AedexV2Factory`, `AedexV2Pair` | | Fee | 1% spread, split 0.5% DAO and 0.5% affiliation | 0.3% per swap, to liquidity providers | -| Can it run out of liquidity | No: the reserve always covers the full supply | Yes: a thin pool gives poor prices or no route | +| Liquidity model | Buys fund a reserve for sellers; full redemption follows in the continuous model, subject to integer-rounding analysis | A thin pool gives poor prices or no route | | Main risk | Price falls back down the curve | Price impact, no route, and impermanent loss if you provide liquidity | -The curve can always buy back its entire supply. A liquidity pool makes no such promise: if the -liquidity providers leave, there is no price to sell at. +The curve's reserve is funded by buys. Its continuous-model redemption argument needs a separate +check for integer rounding; see [Reserve accounting and rounding](/concepts/value-flow#reserve-accounting-and-rounding). +In a liquidity pool, providers can withdraw the reserves used for swaps. ## Routes diff --git a/pages/defi/pools.mdx b/pages/defi/pools.mdx index 36b9058..651b36f 100644 --- a/pages/defi/pools.mdx +++ b/pages/defi/pools.mdx @@ -24,19 +24,35 @@ your positions on the right. **Match the ratio.** For an existing pool the app compares your two amounts against the current reserve ratio. If they differ by more than **1%** it blocks with a ratio-mismatch message and -offers the optimal counter-amount for each side. Take the suggestion: a constant-product pool -only accepts proportional deposits, and the surplus on one side buys you nothing. +offers the optimal counter-amount for each side. Take the suggestion: the router selects deposit +amounts using the reserve ratio. + +For an existing pool whose balances match its cached reserves before your deposit, the LP mint +and the share represented by those new tokens are: ```text -lpMinted = totalSupply × min( amountA / reserveA , amountB / reserveB ) -yourShare = lpMinted / totalSupply × 100 +lpMinted = min( + floor(amountA × supplyBeforeMint / reserveA), + floor(amountB × supplyBeforeMint / reserveB) +) +newTokensShare = lpMinted / (supplyBeforeMint + lpMinted) × 100 ``` -The `min` is why an off-ratio deposit wastes the larger side: the smaller ratio sets the mint. +Here `amountA` and `amountB` are the router-selected amounts in each token's base units, and the +reserves are from before the deposit. `supplyBeforeMint` includes locked liquidity and any LP +tokens minted to the protocol-fee recipient before your mint. If you deposit amounts equal to +both existing reserves, you mint as many LP tokens as that supply and the new tokens represent +**50%** of the resulting pool. If you already hold LP tokens, use your final LP balance divided +by the final total supply to calculate your total position's share. A new pool uses the different +first-mint calculation below. + +The `min` sets the LP mint, but the router does not transfer unused AEX-9 tokens from your wallet. +Excess attached native AE is refunded in the same transaction. The transaction can still fail +if the selected amounts fall below your minimums. Minimum amounts are your desired amounts minus your slippage tolerance, clamped to at least one -aetto. The deadline is `Date.now()` plus your configured minutes, in milliseconds. Every router -entrypoint checks `require(deadline >= Chain.timestamp, "AedexV2Router: EXPIRED")`, and Sophia's +base unit of each asset. The deadline is `Date.now()` plus your configured minutes, in milliseconds. +Every router entrypoint checks `require(deadline >= Chain.timestamp, "AedexV2Router: EXPIRED")`, and Sophia's `Chain.timestamp` is unix time in milliseconds. ### Router entrypoints @@ -48,7 +64,7 @@ entrypoint checks `require(deadline >= Chain.timestamp, "AedexV2Router: EXPIRED" `add_liquidity_ae` is `payable`. The attached AE is the upper bound on the AE side: the router wraps what it needs with `wae.deposit_to(pair, value = amount_ae)` and refunds the rest with -`Chain.spend` in the same transaction, so over-attaching AE is safe. +`Chain.spend` in the same transaction. Both forms move your tokens with `transfer_allowance(Call.caller, pair, amount)`, which is why each AEX-9 side needs a router allowance first. The 1% ratio check is client-side only; on chain, @@ -214,7 +230,8 @@ reaches you as native AE in the same transaction. Both forms abort with `AedexV2Router: INSUFFICIENT_A_AMOUNT` or `INSUFFICIENT_B_AMOUNT` if the burn returns less than your minimums, and with `AedexV2Router: EXPIRED` past the deadline. -Slippage above 100% or below 0 is rejected client-side on both add and remove. +The DEX slippage setting is limited to 0–50%; the add and remove code also rejects negative values +and values of 100% or more. ## Impermanent loss diff --git a/pages/defi/swap.mdx b/pages/defi/swap.mdx index 33d9486..5639316 100644 --- a/pages/defi/swap.mdx +++ b/pages/defi/swap.mdx @@ -121,7 +121,8 @@ function get_amount_out(amount_in, reserve_in, reserve_out) = ``` 997 of every 1000 input units buy output; the remaining 3 stay in the pool. `get_amount_in` -inverts the same ratio and adds one aetto of rounding headroom. +inverts the same ratio and adds one base unit of the input asset (one aetto when the input is +AE or WAE) of rounding headroom. The pair enforces it inside `swap`, independently of the router's arithmetic: @@ -190,8 +191,9 @@ The AE-side entrypoints do the wrapping for you. `swap_exact_ae_for_tokens` and `swap_ae_for_exact_tokens` require the first element of `path` to be the WAE address and call `wae.deposit_to(first_pair, value = ...)`; `swap_exact_tokens_for_ae` and `swap_tokens_for_exact_ae` require the last element to be WAE, swap into the router itself, then -`wae.withdraw(amount)` and `Chain.spend(to, amount)`. Both exact-out AE-input forms refund the -unspent AE to you in the same transaction. +`wae.withdraw(amount)` and `Chain.spend(to, amount)`. `swap_ae_for_exact_tokens` refunds AE +attached above the computed input in the same transaction; `swap_exact_ae_for_tokens` spends the +whole attached value. Router and factory addresses for both networks are in the [deployment table](/defi). diff --git a/pages/defi/wrapped-ae.mdx b/pages/defi/wrapped-ae.mdx index 3990f49..9f7f276 100644 --- a/pages/defi/wrapped-ae.mdx +++ b/pages/defi/wrapped-ae.mdx @@ -7,7 +7,8 @@ description: "Why native AE cannot be pooled directly, and how to wrap and unwra WAE is an AEX-9 token contract that holds AE and issues an equal balance of WAE against it. It exists because the DEX cannot work with native AE directly. Wrapping and unwrapping is always -1:1 with no price impact and no swap fee. You pay only the æternity transaction fee. +1:1 with no price impact and no swap fee. You still pay the network transaction fee and +contract-execution gas. Wrap and unwrap at `https://superhero.com/defi/wrap`. diff --git a/pages/getting-started/claim-name.mdx b/pages/getting-started/claim-name.mdx index 19ac466..6fedbec 100644 --- a/pages/getting-started/claim-name.mdx +++ b/pages/getting-started/claim-name.mdx @@ -1,20 +1,21 @@ --- title: "Claim Your .chain Name" -description: "Turn your ak_ address into a human-readable on-chain username, free for names over 12 characters." +description: "Claim a human-readable on-chain username: long names, sponsorship eligibility and the self-funded path." --- # Claim Your .chain Name A `.chain` name is an æternity Naming System (AENS) record that points at your account, so people -see `yourname.chain` instead of `ak_2a1j2Mk4…`. Superhero sponsors one free claim per address, and -the name's length decides whether yours is free. +see `yourname.chain` instead of `ak_2a1j2Mk4…`. Superhero can sponsor one claim per address. +The name must meet the length requirement, and the sponsor must be available and able to fund it. ## The two rules - **The name must be longer than 12 characters**, excluding the `.chain` suffix. Names of 12 characters or fewer go to auction instead of registering instantly. This is an AENS protocol rule. -- **One sponsored claim per address.** Further names are claimed directly in Superhero Wallet: the - browser extension, the mobile app, or the web wallet at `wallet.superhero.com`. +- **One sponsored claim per address.** A valid name is not automatically free. The app checks + whether the sponsor can fund it; when it reports that it cannot, the app offers a self-funded + claim. The standalone Superhero Wallet also supports claims, including short-name auctions. The claim field shows a live counter against 13 characters as you type. @@ -28,12 +29,14 @@ most 63 characters. The app validates this before you can submit. 1. Open your profile, edit it, and choose to claim a `.chain` name. 2. Type the name you want. The field checks availability as you type and shows whether the name is sponsored (**Free**) or has a price. -3. A name of 13 or more characters shows **Free**. A shorter one shows an approximate AE price with - the note *"Paid from your wallet"*, which marks the self-funded path, not the sponsored one. -4. Press **Claim**. Your wallet asks you to sign a message. This proves you control the address - without spending anything. -5. The app reports *"Claim submitted. Waiting for sponsorship and transfer…"* and tracks the - claim's progress. +3. A valid long name shows **Free** when the sponsor can fund it. Otherwise it shows an + approximate AE price and *"Paid from your wallet"*. Names of 12 characters or fewer are + rejected here; the app does not quote or bid on short names. +4. Press **Claim**. For a sponsored claim, sign a challenge message proving control of your + address; you do not pay the claim's transaction fees or name fee. For a self-funded claim, + approve the on-chain transactions and their costs in your wallet. +5. For a sponsored claim, the app reports *"Claim submitted. Waiting for sponsorship and + transfer…"* and tracks the claim's progress. A self-funded claim runs from your own wallet. ### What happens behind that message @@ -43,8 +46,8 @@ Superhero's backend executes the sponsored claim on your behalf and reports each | --- | --- | | `wallet` | You sign the challenge message in your wallet | | `queued` | The signed claim is accepted and queued | -| `preclaim` | The commitment transaction is submitted; AENS requires this to prevent front-running | -| `claim` | The name is claimed in a later block | +| `preclaim` | The sponsor submits a commitment to conceal the name before claiming it | +| `claim` | The name is claimed at a later key-block height | | `update` | The name's pointer is set | | `transfer` | The name is transferred to **your** address | @@ -53,10 +56,11 @@ not Superhero's. ### When a name is not free -For a name short enough to pay for, the figure shown is the **preclaim transaction fee plus the -claim's execution cost**, which includes the protocol's minimum name fee for a name of that length. -Short names are expensive by design. That is how AENS allocates scarce names, and why the free tier -starts at 13 characters. +If the sponsor cannot fund a valid long name, the app can offer a self-funded claim. The figure +shown estimates the preclaim transaction fee plus the claim transaction fee and the protocol's +minimum name fee. The flow also updates the name's pointer, which requires another transaction +fee. Keep additional AE for that step. This path still requires more than 12 characters; use +Superhero Wallet or the SDK for short-name auctions. ### Errors you may see @@ -83,8 +87,9 @@ node scripts/superhero-name.mjs register myagentname123 then runs: 1. **Preclaim**, and wait for it to be mined. -2. **Wait for a different block.** AENS requires the claim to land in a later block than its - commitment; the script polls the chain height every 30 seconds until it advances. +2. **Wait for the next key block.** AENS requires the claim at a later key-block height than its + commitment (a later micro block is not enough); the script polls the chain height every 30 + seconds until it advances. 3. **Claim**, and wait for it to be mined. 4. **Update the pointer** to your wallet address, setting the `account_pubkey` pointer. @@ -101,7 +106,7 @@ The rest of the command surface: | `list` | Your own names | Names are lowercased and get `.chain` appended automatically if you leave it off. Registration -costs gas plus the name fee, so run `available` first. +costs transaction fees plus the name fee, so run `available` first. The script targets **mainnet**. See [Using Testnet](/getting-started/testnet). @@ -113,7 +118,7 @@ rejects it, the sponsored-claim backend requires at least 13 characters (and res To bid on a short name, use Superhero Wallet's own claim screen, another æternity wallet, or `@aeternity/aepp-sdk` directly. [AENS on æternity](/aeternity/aens) covers the auction (including -the Ceres rule that every bid extends the auction by up to 120 key blocks) and +the Ceres rule that every bid extends the auction by up to 240 key blocks) and `getMinimumNameFee(name)` as the way to compute a starting bid. ## Superhero Wallet's name manager diff --git a/pages/getting-started/create-account.mdx b/pages/getting-started/create-account.mdx index 5c8aafa..c194aa6 100644 --- a/pages/getting-started/create-account.mdx +++ b/pages/getting-started/create-account.mdx @@ -36,37 +36,44 @@ you the same addresses in every one of them. ## Create in the Superhero app -Press **Connect**. The dialog offers a passkey (the built-in wallet), Superhero Wallet, and an AI -agent setup. +Press **Connect**. The dialog offers a **Passkey** card (the built-in wallet), **Download the +mobile app**, **Superhero Wallet** and **Onboard your AI Agent**. ### With a passkey -Choose **Use a passkey**. One ceremony does everything: Face ID, Touch ID, a fingerprint or your +Tap the **Passkey** card. One ceremony does everything: Face ID, Touch ID, a fingerprint or your device PIN, and a wallet exists. -There is no seed-phrase screen because the phrase is **derived** from the passkey's own output at a -fixed salt, so it can be re-derived on any device the passkey reaches. The app then takes you -straight to the mandatory **recovery code** screen. +The phrase is **derived** from the passkey's own output at a fixed salt, so it can be re-derived on +any device the passkey reaches. The app then offers an optional **12-word recovery phrase backup**, +hidden until you press **Reveal**, with copy and download options. The download is an unencrypted +text file containing your address and phrase, so writing the words down is safer; keep any copy +offline. These words restore the wallet independently of the passkey. This path does not enroll +a recovery code. -This is a real backup **only if your passkey syncs** (iCloud Keychain, Google Password Manager). A -device-bound credential such as Windows Hello dies with its device, and the app has no phrase -reveal or export screen. +If you skip the phrase backup, recovery depends on keeping the passkey. Confirm that it syncs +(iCloud Keychain, Google Password Manager) before relying on it across devices. A device-bound +credential such as Windows Hello cannot follow you to another device. -If the option is greyed out, this device or browser cannot create a platform passkey; use a -recovery phrase instead. If tapping it does nothing at all, see +If this device or browser cannot create a platform passkey, the card reads **Create a wallet** +and goes straight to the recovery-phrase flow. If tapping it does nothing at all, see [Troubleshooting](/wallets/troubleshooting). ### With a recovery phrase -Choose **Use a recovery phrase**. Twelve words you write down and keep yourself; works on any -device, with or without biometrics. +Twelve words you write down and keep yourself; works on any device, with or without biometrics. +On a device that can create passkeys, tap the **Passkey** card and **cancel** the system passkey +prompt; the next screen offers **Use a recovery phrase** (**Create with a phrase**). Where +passkeys are unavailable, the card reads **Create a wallet** and opens this flow directly. 1. **The phrase is shown.** Write it down by hand. Do not screenshot it. -2. **The phrase is verified.** You re-enter the words. Nothing is stored until this passes. +2. **Confirm your backup.** The app asks you to re-enter two words. You can skip this step, but + the app does not offer the check again later, so do it now, before you fund the account. 3. **You set a passphrase.** It encrypts the wallet on this device. The app scores it locally and requires a genuinely unguessable one, so a numeric PIN is rejected. Take the **generated five-word passphrase** unless you have a reason not to. The passphrase cannot be changed later; - changing it means recreating the wallet from the phrase. + changing it means recreating the wallet from the phrase, which only the installed app can + import. 4. **The wallet is created** and your first address is derived. 5. **A device passkey is offered.** Optional. With it you stop typing the passphrase for every signature. @@ -80,12 +87,16 @@ Offered **only in the installed app** (Add to Home Screen / installed PWA). In a the answer to "I already have a wallet" is **Connect**, which hands signing to your extension or wallet app and never asks for your secret. -Imported phrases are checked against the BIP39 wordlist **and checksum** before anything is stored, -so a mistyped word is rejected rather than silently creating a different, empty wallet. +Imported phrases are checked against the BIP39 wordlist **and checksum** before anything is stored. +A misspelled word is always rejected, but a wrong word that is itself on the list (or two swapped +words) passes about 1 time in 16 for a 12-word phrase and creates a different, empty wallet. Check +that the address on the final screen matches your old one before funding it. ### Restore a passkey wallet on a new device -Choose **Restore a wallet you created with a passkey**. The ceremony derives the wallet your passkey +Tap the **Passkey** card and **cancel** the prompt to create a new passkey: approving it creates a +new, empty wallet, which you would have to erase before restoring. On the screen that follows, +choose **Restore a wallet you created with a passkey**. The ceremony derives the wallet your passkey implies and **shows you the address before saving anything**, together with a check of whether that address has on-chain history. If it reports no activity, stop: you probably picked the wrong passkey. Details in [Backup & Recovery](/wallets/backup-and-recovery). @@ -93,9 +104,10 @@ passkey. Details in [Backup & Recovery](/wallets/backup-and-recovery). ### Coming back later If this device already has a wallet, Connect shows either *"Your wallet is ready"* or *"Finish -setting up your wallet"*. The second appears when the recovery code was never enrolled, for -example after a reload mid-flow. Finish it: on a passkey wallet that code is the only factor that -survives a passkey rekey. +setting up your wallet"*. On a phrase-created or imported wallet, the second can appear when the +recovery code was never enrolled, for example after a reload mid-flow. Finish that enrollment for +a same-device fallback. A passkey-created wallet is complete without a recovery code; keep its +phrase backup in case the passkey is lost or rekeyed. ## Create in Superhero Wallet @@ -143,8 +155,12 @@ Use a dedicated account funded with a capped amount. See ## If you clear browser storage An account created in the Superhero app lives encrypted in this browser's IndexedDB for the -superhero.com origin. **Clearing site data deletes it.** So does Safari's tracking prevention after -roughly seven days without interaction. Once it is gone: +superhero.com origin. **Deleting the storage containing that vault removes it.** In a Safari tab, +ITP can also remove script-writable storage after seven days of Safari use without interaction +with the site. First-party Home Screen web-app storage is exempt from that ITP rule. On iOS, a +Home Screen web app also keeps its storage separate from Safari: a wallet created in a Safari tab +does not appear in the installed app until you import its phrase there (or restore a +passkey-created wallet with its passkey). Once the vault is gone: - your **passphrase** opens nothing, - your **recovery code** opens nothing, diff --git a/pages/getting-started/first-post.mdx b/pages/getting-started/first-post.mdx index 65061dd..244414f 100644 --- a/pages/getting-started/first-post.mdx +++ b/pages/getting-started/first-post.mdx @@ -7,7 +7,7 @@ description: "Publish a post that lives permanently on chain — what you sign, A post on Superhero is a contract call recorded in a block, attributed to your address, and readable by anyone forever. You need [an account](/getting-started/create-account) with a little AE in it. A -post costs gas and nothing else. +post costs a network transaction fee and execution gas, with no additional posting fee. ## Post it @@ -57,8 +57,8 @@ you are about to sign. ### Cost -Gas only. There is no posting fee and no tip attached. Gas is charged on -top of the transaction fee, which is why a good signing prompt shows both. +You pay a network transaction fee and execution gas. There is no additional posting fee and +no tip attached. A signing prompt can show the transaction fee separately from the gas limit. ## Comments are posts too diff --git a/pages/getting-started/first-trade.mdx b/pages/getting-started/first-trade.mdx index a4490e3..673c303 100644 --- a/pages/getting-started/first-trade.mdx +++ b/pages/getting-started/first-trade.mdx @@ -7,16 +7,17 @@ description: "Buy a community token from the token page, read the quote correctl Community tokens on Superhero do not trade on an order book. Each one has a **bonding curve**: a contract that mints new tokens when you buy and burns them when you sell, with the price determined -by supply rather than by a counterparty. There is always liquidity and never a bid-ask queue. +by supply rather than by a counterparty. Trades use the contract's reserve instead of a bid-ask queue. -Start at **[superhero.com/trends/tokens](https://superhero.com/trends/tokens)**. It is sorted by -market cap by default, so established communities surface first. +Start at **[superhero.com/trends/tokens](https://superhero.com/trends/tokens)**. The trending +screen defaults to the **Trending** sort; choose **Market Cap** if you want that ordering. ## Buy 1. Open a token from the trending list. You land on `/trends/tokens/`. -2. Choose the **Trade** tab. The token page's tabs are Feed, Trade, Info, Transactions and Holders; - the last three appear once the token exists on chain. +2. On a phone, choose the **Trade** tab (tabs: Feed, Trade, Info, Transactions and Holders; for a + name with no token yet, Trade, Transactions and Holders are shown locked). On a wider screen + the trade card is in the right-hand column. 3. Press **Connect** if you have not already. Trading needs a connected account. 4. Make sure **Buy** is selected, and enter an amount. The two fields are linked: type AE and it shows the tokens you would receive, or type tokens and it shows the AE required. @@ -40,8 +41,9 @@ pre-approve. ### It is an estimate, not a fill price The quote is computed against the curve's state at the moment you type. Between your click and -your transaction landing in a block, other people's buys and sells move that state. On a rising -curve, the tokens you receive for a given amount of AE can be slightly fewer than quoted. +your transaction landing in a block, other people's buys and sells move that state. The buy +submits a fixed token count: if the price rises, that count costs more AE within your attached +buffer, or the call reverts if the attached amount is insufficient. **The quote does not tick.** It is recomputed only when you change the amount or flip between Buy and Sell, not on an interval, and not when the token's supply changes underneath you. Retype the @@ -55,7 +57,7 @@ not the displayed number, as your actual protection. | Default | **1%** | | Allowed range | 0 to 50% | | Stored | Per browser, in local storage under `tokenTrade:slippage` | -| Passed to | Every buy and sell call, as the contract's tolerance parameter | +| Applied as | Extra AE attached to a buy, or a minimum AE return passed to a sell | Too low and trades fail when the price moves. Too high and you accept a worse execution silently. Change it deliberately, not to force a failing trade through. @@ -68,27 +70,30 @@ The **Max** button withholds a reserve, because a trade for every last aetto can max = balance − balance × (slippage + 1) / 100 − 0.001 AE ``` -At the default 1% slippage that is roughly a 2% slippage allowance plus a flat 0.001 AE gas -reserve. This is the usual cause of "insufficient balance" on a balance that looks sufficient. +At the default 1% slippage the formula holds back 2% of the balance plus a flat 0.001 AE. +This can cause an "insufficient balance" message even when the displayed balance looks sufficient. ### The spread is structural -Every curve trade carries a **1% spread** between the buy price and the sell price. The contract -splits it: +The buy and sell sides differ by **1% of the curve value** before integer rounding. On buys, +approximately half is allocated to the DAO and half to affiliation. With `B` the curve value +in AE, the continuous-model allocation is: ```text -On a buy, the AE you spend is allocated: - ├── 99.0% → the bonding curve reserve (what sellers redeem against) - ├── 0.5% → the community's DAO treasury - └── 0.5% → the affiliation system +Buyer pays 1.005 × B AE + ├── 0.995 × B → the bonding curve reserve (what sellers redeem against) + ├── 0.005 × B → the community's DAO treasury + └── 0.005 × B → the affiliation system ├── 0.300% → level 1 referrer ├── 0.125% → level 2 referrer ├── 0.050% → level 3 referrer └── 0.025% → level 4 referrer ``` -Unaffiliated affiliation fees are burned rather than accumulated. Buying and immediately selling -the same amount loses about 1% before any price movement. +The referral percentages above are of `B`. Uncredited affiliation shares remain in the +treasury; they are not transferred to a burn address. With no intervening trades, buying and +immediately selling the same count returns about `0.995 / 1.005`, or `0.99005`, of the payment +before network charges and integer rounding. Sells make no new DAO or affiliation allocation. ### Protocol DAO tokens @@ -102,10 +107,12 @@ Superhero's built-in wallet names the call rather than showing raw bytes: - **Buy tokens**: *"Spends the AE attached to this call to buy tokens from this sale contract."* - **Sell tokens**: *"Sells your tokens back to this sale contract for AE."* -- **Lets another account spend your tokens up to this amount**: the allowance step of a sell. +- **Approve token spending** (*Lets another account spend your tokens up to this amount*): the + allowance step of your first sell of a token. Later sells show **Change token spending + approval**, with the amount as a change rather than a total. Check two things on that screen every time: the **contract address** matches the token you meant, -and the **AE amount** is what you typed. Token amounts are shown in raw base units, not scaled by +and the **AE amount** matches the payment and buffer you reviewed. Token amounts are shown in raw base units, not scaled by the token's decimals, so count digits rather than eyeballing magnitude. ## Verify the result @@ -131,8 +138,9 @@ a = 10^15 k = 10^10 initial_price = 10^11 decimals = 10^18 minimum_count = 10^12 sell_return_percentage = 9950 sell_return_precision = 10000 ``` -Two tokens at the same supply cost exactly the same; a token's price says how much has been bought, -nothing about how it was configured. `minimum_count = 10^12` aettos (10^-6 of a token) is the +Equal counts of two tokens at the same supply have the same curve quote. The quote depends +on current supply, which buys, sells and direct holder burns can change. +`minimum_count = 10^12` token base units (10^-6 of a token) is the smallest tradable amount; below it the call aborts with `MINIMUM_TOKENS_REQUIRED`. See [Curve Parameters](/tokens/curve-parameters). @@ -140,7 +148,7 @@ smallest tradable amount; below it the call aborts with `MINIMUM_TOKENS_REQUIRED - Price is a function of supply, not of demand from a counterparty. An early buyer's gain comes from later buyers pushing along the curve. -- The 1% spread is a floor on round-trip cost. +- An immediate round trip loses about 1% before network charges and integer rounding. - A community token is not equity and carries no claim on anything. Read [Token Risks](/tokens/risks). - Double-check addresses and amounts before signing. Start with an amount you would shrug at losing. diff --git a/pages/getting-started/fund-wallet.mdx b/pages/getting-started/fund-wallet.mdx index 7470e3d..5af8a96 100644 --- a/pages/getting-started/fund-wallet.mdx +++ b/pages/getting-started/fund-wallet.mdx @@ -15,10 +15,10 @@ redirects to `/get-ae`. | Action | Cost | | --- | --- | -| Publishing a post | Gas only. | -| Buying or selling a community token | The trade amount, plus fee and gas, plus a **1% curve spread** (0.5% to the community DAO, 0.5% to affiliation). | -| Claiming a `.chain` name | Gas plus a **name price**, which for short names dwarfs the fee. Superhero sponsors one free claim per address; see [Claim Your .chain Name](/getting-started/claim-name). | -| Voting in a DAO | Gas, plus an allowance transaction the first time. | +| Publishing a post | Network transaction fee and execution gas. | +| Buying or selling a community token | Network transaction fees and execution gas. A buy pays the curve cost plus a 0.5% affiliation fee; a sell receives the sell quote. The buy/sell spread is 1% of the underlying curve value before integer rounding. | +| Claiming a `.chain` name | Transaction fees and the protocol name fee. The sponsor pays for an eligible sponsored claim; you pay on the self-funded path. See [Claim Your .chain Name](/getting-started/claim-name). | +| Voting in a DAO | Network transaction fees and execution gas for the allowance, when needed, and vote calls. The voted tokens stay in the vote contract until you revoke (while the vote is open) or withdraw (after it closes). | Two things worth knowing: @@ -35,10 +35,13 @@ Two things worth knowing: fails on arithmetic rather than on price. **A working floor: 0.01 AE.** That is the balance the agent skill confirms before doing anything on -chain, and it leaves room for everyday posting, voting and claiming. +chain, and it leaves room for everyday posting and voting. A self-funded name claim also pays the +protocol name fee: 1.7711 AE for a 13-character name, falling below 0.01 AE only from 24 +characters (see [the starting-bid table](/aeternity/aens#the-starting-bid-table)). An eligible +sponsored claim costs you nothing. -Add whatever you intend to trade, plus the Max button's reserve. Funding with **0.1 AE or more** -covers a first session without further thought. +Add whatever you intend to trade, plus the Max button's reserve and any name fee. Funding with +**0.1 AE or more** covers a first session of posting, voting and small trades. ## Earn it diff --git a/pages/getting-started/index.mdx b/pages/getting-started/index.mdx index a610db4..c64fca5 100644 --- a/pages/getting-started/index.mdx +++ b/pages/getting-started/index.mdx @@ -18,7 +18,7 @@ a fraction of an AE in fees. | 2 | [Fund Your Wallet](/getting-started/fund-wallet): buy or earn AE, and how much you need | 10 min | | 3 | [Your First Post](/getting-started/first-post): publish to the chain and verify it in an explorer | 2 min | | 4 | [Your First Trade](/getting-started/first-trade): read the quote, set slippage, buy, confirm | 5 min | -| 5 | [Claim Your .chain Name](/getting-started/claim-name): free for names over 12 characters | 3 min | +| 5 | [Claim Your .chain Name](/getting-started/claim-name): sponsored for names over 12 characters, when available | 3 min | ## Reference @@ -27,8 +27,8 @@ a fraction of an AE in fees. ## Before you start -**Do the backup step.** It is the only irreversible part of the path. Your backup is the only way -back into an account. [Backup & Recovery](/wallets/backup-and-recovery) lists exactly what to keep. +**Back up your account before funding it.** Losing the recovery material can permanently +prevent access to your funds. [Backup & Recovery](/wallets/backup-and-recovery) lists what to keep. **Start small.** Every transaction is final. Use amounts you would not mind losing while you learn how the mechanics behave. diff --git a/pages/getting-started/navigating-the-app.mdx b/pages/getting-started/navigating-the-app.mdx index 06f27d7..9f0bbaf 100644 --- a/pages/getting-started/navigating-the-app.mdx +++ b/pages/getting-started/navigating-the-app.mdx @@ -86,7 +86,7 @@ All four render the same Governance view; the path selects the tab. | --- | --- | --- | | `/wallet` | The Superhero Wallet product page: features, downloads and a wallet FAQ | No | | `/tx-queue/:id` | Callback landing page for deep-link signing results | Part of a signing flow | -| `/get-ae` | Ways to get AE: earn, exchanges and swap providers | No | +| `/get-ae` | Ways to get AE: earn it, or buy it on Gate.io | No | | `/meet/:room?` | Video conference room | No | | `/landing` | The marketing landing page | No | | `/whitepaper` | The full technical whitepaper | No | diff --git a/pages/getting-started/quickstart.mdx b/pages/getting-started/quickstart.mdx index 9ea51cf..edd5624 100644 --- a/pages/getting-started/quickstart.mdx +++ b/pages/getting-started/quickstart.mdx @@ -11,12 +11,13 @@ Setting up an AI agent instead? Skip to [Agent quickstart](#agent-quickstart). ## 1. Get an account -Open **[superhero.com](https://superhero.com)** and press **Connect**. You are offered three ways -in: a passkey, Superhero Wallet, or an AI agent setup. +Open **[superhero.com](https://superhero.com)** and press **Connect**. The dialog offers a +**Passkey** card, **Download the mobile app**, **Superhero Wallet** and **Onboard your AI Agent**. -- **Fastest:** choose **Use a passkey**. Face ID, Touch ID, a fingerprint or your device PIN, and an - æternity account exists. Make sure the passkey syncs to iCloud Keychain or Google Password Manager, - because on this path the passkey *is* your backup. +- **Fastest:** tap the **Passkey** card. Face ID, Touch ID, a fingerprint or your device PIN, and an + æternity account exists. On the next screen press **Reveal** and write down the 12-word recovery + phrase: it restores the wallet even without the passkey. If you also rely on the passkey across + devices, make sure it syncs to iCloud Keychain or Google Password Manager. - **On a desktop, if you prefer a standard wallet:** install the [Superhero Wallet extension](/wallets/superhero-wallet-extension), create a wallet there, write down the seed phrase, then come back and press Connect. @@ -37,7 +38,7 @@ You need AE for network fees and for anything you buy. The app's page for this i Withdraw to your own `ak_...` address on æternity mainnet, and **send a small test amount first**. -How much: a post needs only gas. A trade needs the amount plus fee plus gas, and +How much: a post needs a transaction fee and gas. A trade also needs the purchase amount, and the Max button withholds about 2% plus 0.001 AE as a reserve. Fund with headroom. → [Fund Your Wallet](/getting-started/fund-wallet) @@ -53,9 +54,9 @@ up. ## 4. Make a trade -1. Open **[superhero.com/trends/tokens](https://superhero.com/trends/tokens)**. It sorts by market - cap, so established communities are at the top. -2. Open a token and choose the **Trade** tab. +1. Open **[superhero.com/trends/tokens](https://superhero.com/trends/tokens)**. It sorts by trending + score by default; choose **Market Cap** to put established communities on top. +2. Open a token and use its trade card (the **Trade** tab on a phone). 3. Enter a **small** amount, check the slippage setting (1% by default), and buy. 4. Approve in your wallet. 5. Verify it on the token's **Transactions** and **Holders** tabs. @@ -69,7 +70,7 @@ the sell. | Next | Where | | --- | --- | -| Get a readable username | [Claim Your .chain Name](/getting-started/claim-name): free over 12 characters | +| Get a readable username | [Claim Your .chain Name](/getting-started/claim-name): sponsored over 12 characters, when available | | Join a community's DAO and vote | [Community DAOs](/dao/overview) | | Find your way around | [Navigating the App](/getting-started/navigating-the-app) | | Understand what you just did | [What is Superhero](/concepts/what-is-superhero) | diff --git a/pages/getting-started/testnet.mdx b/pages/getting-started/testnet.mdx index f9dac79..b002958 100644 --- a/pages/getting-started/testnet.mdx +++ b/pages/getting-started/testnet.mdx @@ -5,8 +5,10 @@ description: "Endpoints, contract addresses and a faucet for running Superhero a # Using Testnet -æternity's public testnet (`ae_uat`) is where you experiment without spending real AE. Superhero has -a complete second deployment there, with its own backend, its own contracts, its own explorer. +æternity's public testnet (`ae_uat`) is where you experiment without spending real AE. +Use testnet contract addresses, nodes and middleware. No public Superhero testnet API or +Socket.IO endpoint is documented here. To test the full application, deploy and configure +a backend for testnet; selecting `ae_uat` alone does not provide one. ## Network selection is a build-time decision @@ -15,7 +17,9 @@ environment variable. It accepts `ae_mainnet` (the default) or `ae_uat`; anythin to mainnet. There is no in-app network switcher. The running app offers exactly one network, and a wallet on -the other one produces a mismatch you resolve in the wallet. To use testnet, build for it: +the other one produces a mismatch you resolve in the wallet. In a checkout of the +[`superhero-com/superhero` application](https://github.com/superhero-com/superhero), build for testnet +with the following commands. These variables configure the application, not this documentation site: ```bash VITE_NETWORK=ae_uat npm run dev @@ -39,8 +43,8 @@ names, inspect AEX-9 balances and sign for a locally built app. | Setting | Mainnet (`ae_mainnet`) | Testnet (`ae_uat`) | | --- | --- | --- | -| Backend / API | `https://api.superhero.com` | Not publicly documented | -| WebSocket | `https://api.superhero.com` | Not publicly documented | +| Backend / API | `https://api.superhero.com` | No public endpoint documented | +| WebSocket | `https://api.superhero.com` | No public endpoint documented | | Node | `https://mdw.wordcraft.fun` | `https://testnet.aeternity.io` | | Middleware | `https://mdw.wordcraft.fun/mdw` | `https://testnet.aeternity.io/mdw` | | Explorer | `https://aescan.io` | `https://testnet.aescan.io` | @@ -110,14 +114,14 @@ Superhero Wallet (extension, mobile app, or `wallet.superhero.com`) ships both n build. Switch under **Settings → Network**; custom networks can be added there too, with per-protocol URLs. -Its æternity testnet defaults: +Its æternity testnet endpoints and Superhero API requirement: | Setting | Value | | --- | --- | | Node | `https://testnet.aeternity.io` | | Middleware | `https://testnet.aeternity.io/mdw` | | Explorer | `https://testnet.aescan.io` | -| Superhero API | Not publicly documented | +| Superhero API | Configure your own testnet backend | | Tipping backend | `https://superhero-backend-testnet.prd.service.aepps.com` | | Multisig backend | `https://ga-multisig-backend-testnet.prd.service.aepps.com` | @@ -139,8 +143,10 @@ AE_NODE_URL=https://testnet.aeternity.io node scripts/superhero-governance.mjs . ``` The other scripts set their node and API URLs as constants at the top of the file. To run them -against testnet, change those constants. The Superhero API base needs changing too: the testnet API -is a different host rather than a path on the mainnet one, and it is not publicly documented. +against testnet, change those constants. Scripts that use the Superhero API also need a backend +deployed for testnet; configure its base URL rather than using the mainnet API. +Also replace network-specific contract constants, including the Tipping, factory and governance +addresses; changing the node URL alone does not select testnet contracts. | Script | Constants to change | | --- | --- | diff --git a/pages/governance/create-a-poll.mdx b/pages/governance/create-a-poll.mdx index c279689..5a0b237 100644 --- a/pages/governance/create-a-poll.mdx +++ b/pages/governance/create-a-poll.mdx @@ -193,7 +193,7 @@ official result. ## Transactions -Each transaction pays gas at the network's current gas price. +Each transaction pays a transaction fee plus execution gas; see [AE & Gas](/aeternity/ae-and-gas). | Action | Transactions | | --- | --- | diff --git a/pages/governance/voting.mdx b/pages/governance/voting.mdx index b70a61c..693c43f 100644 --- a/pages/governance/voting.mdx +++ b/pages/governance/voting.mdx @@ -5,7 +5,7 @@ description: "Cast, change and revoke a vote on an æternity governance poll, an # Voting on Polls -Voting on a governance poll is one transaction that pays gas only. Nothing is locked, +Voting on a governance poll is one transaction that pays a transaction fee and execution gas. Nothing is locked, nothing is transferred, and you can change your mind as often as you like until the poll closes. @@ -119,10 +119,10 @@ The snapshot only exists once the poll has closed: An open poll's percentages are a live reading, so two people loading the same open poll an hour apart can legitimately see different numbers. -**There is no minimum balance to vote.** An account with nothing in it can cast a vote that -records normally, emits a `Vote` event and appears in `votes()`. It contributes zero stake, -but it is counted in the backend's `voteCount`, the address count the app shows as "Total -Votes". See [Polls](/governance/polls). +**There is no minimum voting stake**, but the normal app flow requires enough AE to pay the +transaction fee and gas. The contract does not impose a minimum balance for the vote itself. +A recorded vote with zero voting weight contributes no stake but still counts in the backend's +`voteCount`, the address count the app shows as "Total Votes". See [Polls](/governance/polls). Nothing about a governance poll executes on-chain. Acting on a result is a separate, off-chain process. See [Community DAOs](/dao) for the system where a passing vote moves money. diff --git a/pages/identity/address-link.mdx b/pages/identity/address-link.mdx index 653fa6e..c9c92ef 100644 --- a/pages/identity/address-link.mdx +++ b/pages/identity/address-link.mdx @@ -20,7 +20,7 @@ state = { providers : map(string, address) A link is a `(subject, provider, value)` triple. `links` is the forward index (every provider value an address has claimed), and `reverse` is the inverse, so a provider value resolves back -to its owner. `nonce_seq` is a monotonic counter per subject: every signed message carries the +to its owner. `nonce_seq` is a monotonic counter per signer address, shared by all entrypoint families: every signed message carries the current nonce, and the nonce advances on write, so a signature cannot be replayed. ### Providers @@ -59,7 +59,8 @@ contract. ## Entrypoints -Three parallel namespaces exist, differing only in what identifies the subject. +The entrypoint families accept different forms of subject, but all store links and nonces +under the signer's address. They do not create separate link or nonce namespaces. ### Address-keyed @@ -72,7 +73,7 @@ Three parallel namespaces exist, differing only in what identifies the subject. | `get_link` | `(addr: address, provider: string) => option(string)` | | `resolve` | `(provider: string, value: string) => option(address)` | -### AENS-name-keyed ("principal") +### Principal-based | Entrypoint | Signature | | --- | --- | @@ -83,10 +84,10 @@ Three parallel namespaces exist, differing only in what identifies the subject. | `get_link_principal` | `(principal: string, signer: address, provider: string) => option(string)` | | `resolve_signer` | `(principal: string) => option(address)` | -The principal is an AENS name. The contract verifies ownership itself via `AENSv2.lookup` +For preferred-name links the principal is an AENS name. The contract verifies ownership via `AENSv2.lookup` before accepting the link: a name that is not registered aborts with `PRINCIPAL_NOT_FOUND`, and -a name the signer does not own aborts with `PRINCIPAL_MISMATCH`. The preferred-AENS-name link -uses this namespace. +a name the signer does not own aborts with `PRINCIPAL_MISMATCH`. The preferred-AENS-name flow +uses these entrypoints. ### DID-keyed @@ -99,8 +100,13 @@ uses this namespace. | `get_link_did` | `(did: string, controller: address, provider: string) => option(string)` | | `resolve_did_controller` | `(did: string) => option(address)` | -The `did` is an opaque string; the contract attaches no syntax or meaning to it. The Superhero -providers use the address-keyed and principal-keyed namespaces, and the API indexes those two. +The DID entrypoints require `did:ae:`, where the subject is the signer's `ak_` address +or a `.chain` name the signer currently owns. They use the same address-keyed links and nonce +as the other entrypoints, but the Superhero indexer processes only `link`, `unlink`, +`link_principal` and `unlink_principal`, so a change made through `link_did` or `unlink_did` +is on chain without appearing in the API's `links`. `resolve_did_controller` looks up the current owner of a name-based +subject; it returns `None` for an address-based subject. These entrypoints alone do not +provide a DID Core method specification or DID documents. ### Events @@ -108,8 +114,9 @@ providers use the address-keyed and principal-keyed namespaces, and the API inde `PrincipalLink(address, string)`, `PrincipalUnlink(address, string)`. The first argument is the subject address as an integer, and the payload string is -`provider:value` for a link and `provider:` for an unlink. The indexer decodes the integer back -to an `ak_…` address and splits the payload on its first colon. +`provider:value` for both `Link` and `Unlink`, with the removed value included on unlink. +`PrincipalLink` and `PrincipalUnlink` prepend `principal|` to that payload. The indexer decodes +the address topic back to an `ak_…` address. ## The signed message @@ -126,14 +133,19 @@ For a principal link the subject slot holds the AENS name instead of the address link:hero.chain:prefaens:hero.chain:0 ``` -The digest is the standard æternity personal-message construction: a 28-byte prefix -(`0x1a`, `aeternity Signed Message:` plus a newline, then the body length `0x20`) concatenated -with the Blake2b-256 hash of the message, the whole 60 bytes hashed again. That is exactly what -`signMessage` in `@aeternity/aepp-sdk` produces, so pass the claim's `message` string to -`signMessage` and never hash it by hand. The signature goes on the wire as **128 lowercase hex -characters**, no `0x`, no base64. +The digest uses standard æternity personal-message framing: -The same construction is used by [delegated posting](/social/delegated-posting). +```text +body = UTF-8(message) +digest = Blake2b-256(0x1a || UTF-8("aeternity Signed Message:\n") + || varuint(byte_length(body)) || body) +``` + +The body is the full message, and its byte length uses the SDK's variable-length integer +encoding. Pass the claim's `message` directly to SDK `signMessage`; do not pre-hash it. +The REST API expects **128 hex characters**, without `0x`, `sg_` or base64. +[Delegated posting](/social/delegated-posting) uses a different construction: its body is +always a 32-byte inner hash, producing a fixed 60-byte payload before the final hash. ### Error codes @@ -141,14 +153,21 @@ The same construction is used by [delegated posting](/social/delegated-posting). | --- | --- | | `INVALID_SIGNATURE` | The Ed25519 check failed against the subject | | `INVALID_NONCE` | The nonce moved between claim and submit; restart from claim | -| `ALREADY_CLAIMED` | This provider is already linked to a different value for this subject | -| `NOT_LINKED` / `NO_LINKS` | Nothing to unlink | +| `ALREADY_CLAIMED` | This provider value is already linked to a different address | +| `LINK_NOT_FOUND` / `NO_LINKS` | No link for this provider, or no links for the address | | `NOT_PROVIDER_OWNER` | The submitting wallet does not own the provider namespace | -| `PRINCIPAL_NOT_FOUND` | The AENS name is not registered | -| `PRINCIPAL_MISMATCH` | The AENS name is not owned by the signer | -| `INVALID_PRINCIPAL` | Not a well-formed AENS name | - -The backend maps each abort to a readable `400` message. +| `PRINCIPAL_NOT_FOUND` | The `.chain` name has no active registration (never claimed, in auction, expired or revoked) | +| `PRINCIPAL_MISMATCH` | The signer does not own the `.chain` name, or a non-name principal is not the signer's address | +| `INVALID_PRINCIPAL` | The principal (after any `did:ae:` prefix) contains a colon | +| `EMPTY_PRINCIPAL` / `PRINCIPAL_TOO_LONG` | The principal is empty or longer than 200 characters | +| `INVALID_DID` | Not `did:ae:` followed by a subject | +| `EMPTY_VALUE` / `VALUE_TOO_LONG` / `INVALID_VALUE` | The value is empty, longer than 200 characters, or contains a colon | +| `PROVIDER_NOT_FOUND` | No such provider is registered | + +The backend maps recognised aborts to readable `400` messages. The mapping names `NOT_LINKED` +rather than the contract's `LINK_NOT_FOUND`, so that +abort is propagated without the documented friendly mapping. Do not assume every contract +failure returns `400`. ## Configuration @@ -161,8 +180,13 @@ The backend's address-link module is environment-driven: | `ADDRESS_LINK_VERIFICATION_TTL_SECONDS` | Claim-token lifetime, default 300 | | `ADDRESS_LINK_NOSTR_EVENT_MAX_AGE_SECONDS` | Nostr proof-event freshness window, default 300 | -With either of the first two unset, every address-link read and write returns -`503 Service Unavailable` and nothing is indexed. +The indexer requires `ADDRESS_LINK_CONTRACT_ADDRESS`; without it, address-link indexing is +disabled. It does not require the provider secret. Reads of stored links through account and +profile endpoints also do not require that secret. + +The contract service requires **both** the address and secret, including for nonce reads used by +claims and for link/unlink submissions. Missing either produces `503 Service Unavailable` from +that service. Existing indexed records remain separate from these contract-dependent operations. ## How a link reaches the API @@ -191,7 +215,7 @@ deprecated): | `profile.bio` | `links.bio`, falling back to the legacy profile field | | `profile.site` | `links.site` | | `profile.prefered_aens_name` | `links.prefaens` | -| `profile.chain_name` | The middleware's AENS name for the address, refreshed hourly | +| `profile.chain_name` | Cached middleware-resolved name, falling back to the legacy cached name; see [freshness limits](/identity/names#how-the-chain-name-stays-fresh) | | `profile.fullname`, `avatarurl`, `username`, `chain_expires_at` | Legacy profile fields, read-only | | `public_name` | `prefered_aens_name`, else `chain_name`, else `username`, else the address | | `followers_count`, `following_count` | The social-graph counts, when that feature is enabled | @@ -203,7 +227,7 @@ deprecated): flow end to end. - [Profiles & Accounts](/identity/profiles): where the linked values surface on screen. - [Chat](/social/chat): the `nostr` provider, and the room pipeline that consumes it. -- [Delegated & Gasless Posting](/social/delegated-posting): the same signed-message - construction in the posting contract. +- [Delegated & Gasless Posting](/social/delegated-posting): the posting contract's signature, + which uses the same personal-message prefix over a 32-byte hash of the post, without a nonce. - [Sophia standard library](https://github.com/aeternity/aesophia/blob/master/docs/sophia_stdlib.md): the reference for `Crypto.verify_sig` and the Blake2b primitives. diff --git a/pages/identity/chain-names.mdx b/pages/identity/chain-names.mdx index 32013c8..168b614 100644 --- a/pages/identity/chain-names.mdx +++ b/pages/identity/chain-names.mdx @@ -1,6 +1,6 @@ --- title: "Chain Names (AENS)" -description: "Register, point, extend and link a .chain name, including the one sponsored free claim." +description: "Register, point, extend and link a .chain name, including the sponsored claim." --- # Chain Names (AENS) @@ -29,20 +29,22 @@ Use a wallet that supports `NameClaimTx` bidding if you want a short name. ## Registration is preclaim, then claim -AENS registration is two transactions, to stop front-running: +The app and CLI use a two-transaction registration flow to protect against front-running: 1. **Preclaim.** Publish a commitment: the hash of the name plus a random salt. Nobody watching the mempool learns which name you want. 2. **Claim.** Reveal the name and the salt. The protocol checks the commitment. -The two transactions must land in **different blocks**. After the claim, **update** the name's +The claim must land at a **later key-block height** than the preclaim. After the claim, **update** the name's pointers so it resolves to your address. A name with no `account_pubkey` pointer resolves to -nothing. +nothing. Since Ceres the protocol also allows a direct claim with salt zero, without a +preclaim; see [AENS](/aeternity/aens). ## The sponsored claim in the app -Superhero sponsors **one free `.chain` claim per address**, for names longer than 12 characters -before the suffix, so every user can have a human-readable identity at no cost. Claim additional +Superhero can sponsor **one `.chain` claim per address**, for names longer than 12 characters +before the suffix. When the sponsor can fund it, the claim costs you nothing; otherwise the app +offers a self-funded claim paid from your wallet. Claim additional names from Superhero Wallet: the browser extension, the mobile app, or `wallet.superhero.com`. The backend pays for and submits the sponsored transactions: @@ -53,7 +55,7 @@ The backend pays for and submits the sponsored transactions: | 2 | `POST /api/profile/chain-name/challenge` | Get a `nonce`, an `expires_at` and a `message` bound to your address. | | 3 | (in your wallet) | Sign `message` with your wallet to prove you control the address. | | 4 | `POST /api/profile/chain-name/claim` | Submit `address`, `name`, `challenge_nonce`, `challenge_expires_at` and `signature_hex`. | -| 5 | `GET /api/profile/{address}/chain-name-claim` | Poll the status. Returns `status` plus `preclaim_tx_hash`, `claim_tx_hash`, `update_tx_hash`, `transfer_tx_hash` and the expiry. | +| 5 | `GET /api/profile/{address}/chain-name-claim` | Poll the status. Returns `status` plus `preclaim_tx_hash`, `claim_tx_hash`, `update_tx_hash`, `transfer_tx_hash`, `error` and `retry_count`. It carries no expiry. | The four transaction hashes are the four stages the app narrates: reserving the name on chain, submitting the sponsored claim, updating the name pointers, and transferring the name to your @@ -98,32 +100,40 @@ node scripts/superhero-name.mjs list # names owned by your own w ## Expiry and extension An AENS name has a finite time-to-live measured in key-blocks, exposed as an expiry height. The -`extend` command issues an extend-TTL transaction; the app surfaces the expiry through the claim -status response's `expires_at`. +`extend` command issues an extend-TTL transaction. The claim-status response carries no expiry; +read `expire_height` or `approximate_expire_time` from the middleware's `GET /v3/names/{name}`. The ceiling is protocol configuration: an `expire_by` may be at most **180,000 key generations** into the future, roughly 375 days. Auction durations and starting bids are protocol parameters too; the [AENS protocol specification](https://github.com/aeternity/protocol/blob/master/AENS.md) is the -reference. +reference, except that since Ceres the node extends an auction by up to 240 key blocks after a +bid, not the 120 the specification gives. -If a name expires, it stops resolving and becomes available again. On Superhero: +If a name expires, it stops resolving and passes through the revoked state before becoming +available again. On Superhero: -- The cached `chain_name` is refreshed from the middleware on an hourly sweep, and on any stale - read of `GET /api/accounts/{address}`, so a lapsed name disappears from profiles within about - an hour. +- The cached `chain_name` is refreshed by an hourly sweep of eligible stale accounts, capped + at 100 per run. The reviewed backend uses a 23-hour sweep staleness window and a 24-hour + read staleness window for `GET /api/accounts/{address}`. Failed lookups preserve the old value, + and profile reads can fall back to a legacy cached name. A lapsed name therefore has no + guaranteed removal deadline; see [Names](/identity/names#how-the-chain-name-stays-fresh). - A `prefaens` address link naming it does **not** self-clear. The link is contract state and stays until you unlink it. Because `prefered_aens_name` sits at the top of the [name resolution ladder](/identity/names), a lapsed linked name keeps being displayed as your - public name until you unlink it. + public name. The preferred-name unlink flow also checks current AENS ownership, so expiry + or transfer can prevent unlinking that old name through this flow. Linking another name you + own replaces the preferred-name value. Until that happens, the name's next owner cannot link + it: `link_principal` aborts with `ALREADY_CLAIMED`, because the contract still maps the name + to the previous holder. `chain_expires_at` in the profile aggregate is a legacy field and is not refreshed; resolve the name through AENS to check whether it is live. ## Linking a name to your SuperheroID -Owning an AENS name and using it as your Superhero identity are two steps. After the name -resolves to your address, link it as your preferred name through the SuperheroID editor, which +Owning an AENS name and using it as your Superhero identity are two steps. Once you own the +name (its pointer does not matter for linking), link it as your preferred name through the SuperheroID editor, which runs a signed address-link claim at `/api/address-links/prefered-aens-name/claim` and then `/submit`. diff --git a/pages/identity/did-standard.mdx b/pages/identity/did-standard.mdx index 843a77a..1e989ef 100644 --- a/pages/identity/did-standard.mdx +++ b/pages/identity/did-standard.mdx @@ -22,27 +22,29 @@ Core concepts like this: | Verifiable data registry | `AddressLink` state plus AENS | | Update and deactivate | `link` and `unlink`, per provider | -Superhero does not define a DID method, DID syntax, DID document or resolver. If you need a DID -for interoperability with an external system, derive a `did:key` from the account's Ed25519 key -or publish a `did:web` document yourself. `AddressLink` also exposes a DID-keyed namespace -(`link_did`, `resolve_did_controller` and friends) in which the `did` is an opaque string; see -[AddressLink](/identity/address-link). +`AddressLink` also accepts `did:ae:` through `link_did`, `resolve_did_controller` +and related entrypoints. The subject must be the signer's address or a `.chain` name the signer +owns. These calls share the signer's ordinary links and nonce, although the Superhero API does +not index changes made through them. They do not supply DID documents or by themselves +establish DID Core compliance. See [AddressLink](/identity/address-link). ## Verifying a SuperheroID 1. **Prove control of the address.** Ask for a signed message and verify it against the `ak_…` public key using the æternity signed-message construction. 2. **Check a `.chain` name.** Resolve it through AENS on any node or middleware and compare its - `account_pubkey` pointer to the address. For a `prefaens` link the contract already performed - the same check with `AENSv2.lookup`. + `account_pubkey` pointer to the address. Check ownership separately: `prefaens` linking + verifies the AENS owner with `AENSv2.lookup`, not the account pointer. Owners can point + their names at a different account. 3. **Read the links.** `AddressLink.get_links(addr)` returns the provider-to-value map as a dry-run call, and `resolve(provider, value)` walks it backwards. Both are free reads against consensus state. 4. **X handle.** The chain records the address's consent to a handle string; the OAuth check was performed by Superhero's backend. See [Verifying Your X Account](/identity/x-verification). -5. **Authorship of content.** A post's author is the address that signed the transaction, - recorded by the `Tipping` contract, independent of the identity layer. +5. **Authorship of content.** For direct posts, the `Tipping` contract records the caller as + author. For delegated posts, it verifies the author's message signature while a separate + relayer signs and pays for the transaction. See [Delegated posting](/social/delegated-posting). ## Related diff --git a/pages/identity/index.mdx b/pages/identity/index.mdx index 05490be..aae0093 100644 --- a/pages/identity/index.mdx +++ b/pages/identity/index.mdx @@ -7,8 +7,8 @@ description: "SuperheroID: an æternity address with signed, revocable links to Your identity on Superhero is your æternity address plus whatever you choose to attach to it. Attachments are provider links in the `AddressLink` contract, each authorised by your own -signature over a nonce-bearing message. There is no account to be locked out of, and only you -can remove a link. +signature over a nonce-bearing message. Every link change, including creating one, is submitted +as a transaction by the owner of that provider namespace. See [AddressLink](/identity/address-link). ## The shape of an identity @@ -16,7 +16,7 @@ can remove a link. | --- | --- | --- | | Address | `ak_…` public key derived from your seed | The æternity chain; you hold the key | | Preferred AENS name | A `.chain` name you own and linked | `AddressLink`, provider `prefaens`, ownership checked on chain | -| Chain name | An AENS name resolved for your address | The Superhero API, refreshed hourly from the middleware | +| Chain name | An AENS name resolved for your address | The Superhero API, cached and periodically refreshed from the middleware | | X handle | An X handle you linked after OAuth | `AddressLink`, provider `x` | | Nostr key | The npub your chat identity uses | `AddressLink`, provider `nostr` | | Bio and website | Free-text links | `AddressLink`, providers `bio` and `site` | @@ -33,7 +33,7 @@ in how much evidence backs them. See [Names](/identity/names). events, providers and the signed message format. - [Names](/identity/names): the name types, and how a public name is resolved. - [Chain Names (AENS)](/identity/chain-names): registering, pointing, extending and losing a - `.chain` name, including the sponsored free claim. + `.chain` name, including the sponsored claim. - [Verifying Your X Account](/identity/x-verification): the OAuth plus claim-sign-submit flow, in enough detail to reimplement. - [Profiles & Accounts](/identity/profiles): what an account page shows, which fields are diff --git a/pages/identity/names.mdx b/pages/identity/names.mdx index f8dc795..4f68225 100644 --- a/pages/identity/names.mdx +++ b/pages/identity/names.mdx @@ -14,8 +14,8 @@ looking at before you cache it. | Type | Where it lives | How it gets there | Verified? | | --- | --- | --- | --- | -| Preferred AENS name | `AddressLink`, provider `prefaens` | `link_principal`, which calls `AENSv2.lookup` inside the contract | **Yes**: ownership is checked on chain | -| Chain name | `chain_name` on the account | Resolved from the middleware, refreshed on an hourly sweep and on a stale read | Yes, by resolution rather than by claim | +| Preferred AENS name | `AddressLink`, provider `prefaens` | `link_principal`, which calls `AENSv2.lookup` inside the contract | Ownership is checked on chain when linking | +| Chain name | `chain_name` on the account | Resolved from the middleware, cached and periodically refreshed | By resolution at the last successful refresh | | X handle | `AddressLink`, provider `x` | `link` after an OAuth check the backend performs | Off chain only; see [X verification](/identity/x-verification) | | Legacy username | `profile.username` | Read-only legacy field | No | @@ -30,31 +30,38 @@ username (the legacy profile field) address (the ak_… itself) ``` -A linked preferred name overrides the middleware-resolved one on purpose: an address can own -several AENS names, and the middleware returns the first. Linking one says which. +A linked preferred name overrides the middleware-resolved one on purpose: several AENS names +can point at an address, and the backend shows the active one whose pointer was set most +recently. Linking one says which. The resolved value is `public_name` on `GET /api/profile/{address}` and `GET /api/accounts/{address}`. There is no per-account preference that changes the order. ### How the chain name stays fresh -`chain_name` is cached with a `chain_name_updated_at` timestamp. An hourly sweep refreshes it, -and `GET /api/accounts/{address}` also refreshes on read when the cached value is older -than the staleness window, writing the new value back asynchronously. An expired or transferred -AENS name therefore drops out of the profile within about an hour. +`chain_name` is cached with a `chain_name_updated_at` timestamp. In the reviewed backend, +an hourly sweep selects at most 100 eligible accounts whose last attempt was more than +23 hours ago or has never been recorded; it does not refresh every name each hour. +`GET /api/accounts/{address}` also attempts a refresh when the last successful resolution is +more than 24 hours old or has never been recorded, writing a successful result back +asynchronously. Failed middleware lookups preserve the previous value. + +Stored preferred-name links in `links.prefaens` take precedence over `chain_name` and are not +removed by this middleware refresh. Their ownership is checked when linking, without continuous +revalidation on profile reads. Legacy cached names can also remain as fallbacks. An expired or +transferred name therefore has no guaranteed removal deadline from the displayed profile. `chain_expires_at` in the profile aggregate is a legacy field and is not refreshed. To check whether a name is live, resolve it through AENS. ## Reverse resolution -`AddressLink` provides two reverse lookups, both free dry-run reads backed by the contract's -`reverse` map: +`AddressLink` provides two different lookups, both available as free dry-run reads: | Call | Answers | | --- | --- | | `resolve(provider, value)` | Which address holds this provider value, for example which address linked the X handle `superherocom` | -| `resolve_signer(principal)` | Which address linked this AENS name as a principal | +| `resolve_signer(principal)` | The current AENS owner of a name-based principal, whether or not it has an AddressLink link; address-based principals return `None` | ## What the app displays @@ -104,8 +111,10 @@ submit with the verification token. The handle is stored lowercased. **Change which name shows.** Link a different `.chain` name, or unlink `prefaens` to fall back to the middleware-resolved name. -**Remove a name.** `unclaim` then `unclaim/submit` on the matching provider path. Only your -own signature is required, with no OAuth or AENS check. +**Remove a name.** Use `unclaim` then `unclaim/submit` on the matching provider path. Your +signature and a transaction from the provider owner are required. Removing `prefaens` +also checks that you still own the linked AENS name; an expired or transferred name can +therefore prevent this unlink flow. ## Related diff --git a/pages/identity/profiles.mdx b/pages/identity/profiles.mdx index 3d2d161..9505fb1 100644 --- a/pages/identity/profiles.mdx +++ b/pages/identity/profiles.mdx @@ -38,9 +38,11 @@ and a `links` object keyed by the `AddressLink` provider ids: `x`, `nostr`, `bio records. If `chain_name_updated_at` is older than the staleness window, or has never been set, the -endpoint re-reads the name from the middleware, returns the fresh value, and writes it back -asynchronously. An hourly sweep covers accounts nobody is viewing, so a lapsed or transferred -`.chain` name disappears from a profile within about an hour. +endpoint attempts to re-read the name from the middleware and writes a successful result back +asynchronously. An hourly sweep also refreshes eligible accounts in batches. Stored preferred +names in `links.prefaens` take precedence independently of this cache, so an expired or +transferred `.chain` name has no guaranteed removal deadline from a profile. See +[Names](/identity/names#how-the-chain-name-stays-fresh). ## The tabs diff --git a/pages/identity/superhero-id.mdx b/pages/identity/superhero-id.mdx index 2d87ba6..3732a71 100644 --- a/pages/identity/superhero-id.mdx +++ b/pages/identity/superhero-id.mdx @@ -7,7 +7,8 @@ description: "Link your wallet, .chain name, X handle and Nostr key into one sel SuperheroID is Superhero's identity layer: an æternity address with a set of independently signed, independently revocable links attached to it. The links live in the `AddressLink` -contract. You authorise every link with your wallet signature, and only you can remove one. +contract. You authorise link changes with your wallet signature; the provider owner submits +the transaction. ## What it links @@ -20,8 +21,8 @@ contract. You authorise every link with your wallet signature, and only you can | Website | `site` | `link` | Ownership of the address only | Every link also needs your æternity signature over the claim message; the proof column is what -the provider checks on top of that. Each link is removed by its own `unlink`, which needs -nothing but your signature. +the provider checks on top of that. Removing a link requires an `unlink` call authorised by +your signature and submitted by the provider owner. The transaction itself is submitted and paid for by Superhero's provider wallet, which is the only account permitted to write the `x`, `nostr`, `bio`, `site` and `prefaens` namespaces. See @@ -37,7 +38,7 @@ only account permitted to write the `x`, `nostr`, `bio`, `site` and `prefaens` n | AENS name registration, pointers, expiry | æternity AENS; the `prefaens` link references it but does not own it | | Posts, comments, tip totals | `Tipping` v3 plus the API index | | Avatar, fullname, legacy username, follow counts, leaderboard stats | Superhero API | -| Chain name shown on a profile | Resolved hourly from the middleware, not from a contract link | +| Chain name shown on a profile | Cached middleware resolution, with a legacy-cache fallback; see [freshness limits](/identity/names#how-the-chain-name-stays-fresh) | ## Reading an identity @@ -51,7 +52,7 @@ query flag is deprecated. ```text prefered_aens_name (links.prefaens — the AENS name you explicitly linked) -chain_name (from the middleware, refreshed hourly) +chain_name (cached middleware name, with a legacy-cache fallback) username (the legacy profile field) address (the ak_… itself) ``` @@ -66,8 +67,9 @@ In order of how much can be checked independently: 1. **Preferred `.chain` name.** `link_principal` calls `AENSv2.lookup` inside the contract and aborts with `PRINCIPAL_MISMATCH` if the signer does not own the name. You can independently - resolve the name through AENS on any node and compare its `account_pubkey` pointer. Both - checks are protocol state. + check the current name owner through AENS on any node. An `account_pubkey` pointer is + a separate setting and can point to an account other than the owner. Ownership is checked + at link time; later transfer or expiry does not automatically clear the stored link. 2. **Nostr key.** The backend verifies a Schnorr signature from the npub over the exact claim message before submitting, but only the æternity signature is recorded on chain. A reader of the chain sees the address's consent to an npub string. @@ -75,8 +77,8 @@ In order of how much can be checked independently: provider owner submitted it. The OAuth evidence lives only inside the backend. See [Verifying Your X Account](/identity/x-verification). 4. **Bio and website.** Nothing to verify beyond ownership of the address. -5. **Posts.** Independent of the identity layer. A post's `sender` is whichever address signed - the transaction, recorded by the `Tipping` contract. +5. **Posts.** Independent of the identity layer. `Tipping` records the caller on direct posts + and the verified author on delegated posts; a relayer can sign the transaction for the latter. The verified badge on a profile means an `x` link exists for that account. diff --git a/pages/identity/x-verification.mdx b/pages/identity/x-verification.mdx index 087b1e7..f64de94 100644 --- a/pages/identity/x-verification.mdx +++ b/pages/identity/x-verification.mdx @@ -88,11 +88,8 @@ Content-Type: application/json ``` The backend exchanges the code for an access token itself, so the token never touches the -browser. A second body shape is accepted for callers that already hold a token: - -```text -{ "address": "ak_…", "x_access_token": "…" } -``` +browser. This is the only accepted body: any other property, such as `x_access_token`, is a +`400`. The response is a claim: @@ -103,7 +100,8 @@ The response is a claim: | `value` | The X username the backend resolved, trimmed and lowercased | | `verification_token` | A base64url HMAC token binding address, provider, value and expiry | -The username is taken from the X profile as `username || name`, then `.trim().toLowerCase()`. +The username is the X profile's `username` (the handle), never its display name, then +`.trim().toLowerCase()`. A profile the backend cannot extract a username from is a `400`. ### The verification token @@ -155,12 +153,13 @@ invalidates the profile query so the verified badge appears once the backend has | Signature is not 128 hex characters | 400 before the call is built | | Contract rejects the signature | 400, from `INVALID_SIGNATURE` | | The nonce moved since the claim | 400, from `INVALID_NONCE`; restart from claim | -| The handle is already linked to a different value for this address | 400, from `ALREADY_CLAIMED` | +| The handle is already linked to another address | 400, from `ALREADY_CLAIMED` | ## Unlinking -Unlinking is symmetrical and also signed, but requires no X proof: possession of the æternity -key is sufficient to remove your own link, so there is no verification token. +Unlinking is symmetrical and also signed, but requires no X proof and no verification token: +you sign the unlink message, and the backend, as the `x` provider owner, submits it. The contract +rejects an unlink from any other caller. ```text POST /api/address-links/x/unclaim → { "message": "unlink:ak_…:x:1", "nonce": 1 } @@ -168,9 +167,14 @@ POST /api/address-links/x/unclaim → { "message": "unlink:ak_…:x:1", POST /api/address-links/x/unclaim/submit → { "txHash": "…" } ``` -The same claim-sign-submit shape is used for `bio`, `site`, `prefered-aens-name` and `nostr`, -with only the path segment changing. To build a new provider, copy this pattern; the -per-provider work is a verifier that turns your proof into a `value` plus a verification token. +Bio, site, preferred-name and Nostr links also use claim, signature and submit steps, with +provider-specific request bodies and proofs. Nostr claim returns no verification token; +submission additionally requires a signed `nostr_event`. Preferred-name messages use the +owned `.chain` name as principal, and preferred-name unlink submission also requires the +linked name in `value`. See [Profile API](/api-reference/profile#address-links) for each flow. + +You can replace your own existing X link with another available handle. `ALREADY_CLAIMED` +rejects a handle linked to another address. ## Contract-side verification @@ -179,15 +183,17 @@ over the personal-message digest of the `message` string. That check, plus the n provider-owner rule, is the whole of it. ```text -digest = Blake2b-256( prefix(28 bytes) || Blake2b-256(message) ) +body = UTF-8(message) +digest = Blake2b-256(0x1a || UTF-8("aeternity Signed Message:\n") + || varuint(byte_length(body)) || body) ok = Crypto.verify_sig(digest, addr, sig) ``` -The prefix string `aeternity Signed Message:` plus the newline is 26 bytes. The SDK's personal -message encoding writes a length byte before the prefix and a length byte before the body, so -the header is 1 + 26 + 1 = 28 bytes. The body is the 32-byte Blake2b digest of the message, -giving 28 + 32 = 60 bytes hashed a second time. The framing makes an address-link signature -unusable as a raw transaction signature. +The prefix string plus its newline is 26 bytes. It is preceded by its length (`0x1a`), then +followed by the variable-length encoding of the message's UTF-8 byte length and the full +message bytes. The message is not pre-hashed. SDK `signMessage(message)` applies this framing; +it differs from Tipping v3's fixed 60-byte construction. The framing separates personal-message +signatures from transaction signatures. `Crypto.verify_sig(msg, pubkey, sig)` is the Sophia standard-library entrypoint for Ed25519 verification. On compiler version 8 and later it accepts a message of any length; earlier diff --git a/pages/index.mdx b/pages/index.mdx index 13181e4..cd62688 100644 --- a/pages/index.mdx +++ b/pages/index.mdx @@ -1,41 +1,31 @@ --- -title: "Superhero Dev" -description: "Superhero is the on-chain attention market where you can discover, trade, and govern the trends you believe in — before everyone else." +title: "Superhero Developer Documentation" +description: "Build on Superhero with its REST API, Sophia smart contracts, wallet integrations and AI agent tools." --- -# Superhero Dev +# Superhero Developer Documentation -**Superhero is the on-chain attention market where you can discover, trade, and govern the -trends you believe in, before everyone else.** +Build applications and integrations for [Superhero](https://superhero.com), a social application +and community-token market on the æternity blockchain. -A decentralized attention market for social trends: where creators own their content, -communities become tradable markets, and attention is priced in real time. +Use the REST API to read indexed data, call Sophia contracts to publish posts and trade tokens, +or use the agent tools to run these workflows from the command line. ![The Superhero app: a social feed with trending community tokens, live prices and hashtags](/superhero-app.webp) -## What that means in practice - -| | | -| --- | --- | -| **Own your content & identity** | On-chain posts and Superhero Onchain ID give creators full ownership. Your content is immutable, your identity is yours. | -| **Tradable trend markets** | Communities and hashtags become tradable via [bonding curve tokens](/tokens/bonding-curve). Attention and conviction show up directly in the price. | -| **Attention Market** | Trends = Hashtags = Communities = Tokens. Real-time market data on attention and sentiment for any trend or community. | -| **Rewards & referrals** | The platform rewards participation through an [affiliation system](/rewards/affiliation) and the [ProtocolDAO token](/dao/protocol-dao). You earn by taking part and by referring others. | -| **On-chain posts & tipping** | Immutable content anchored to verifiable events. [Tip creators](/social/tipping) directly, and every interaction stays public on chain. | -| **On-chain identity** | Wallet + chain names + X handle, all linked together. Your [identity](/identity) lives on-chain, not on a corporate server. | - -## Pick your track +## Start building | I want to… | Start here | | --- | --- | +| Read indexed posts, tokens and account data | [API Reference](/api-reference) | +| Call a deployed smart contract | [Calling Contracts](/contracts/calling-contracts) | +| Find network endpoints and contract addresses | [Networks & Endpoints](/aeternity/networks) and [Deployed Addresses](/contracts/addresses) | +| Run posting and trading tools from an agent | [Agent Quickstart](/agents/quickstart) | +| Understand æternity accounts, units and contracts | [æternity](/aeternity) | | Use Superhero as a person | [Getting Started](/getting-started) | | Install and secure a wallet | [Wallets](/wallets) | | Understand the token economics | [Tokens & Bonding Curves](/tokens) | | Launch a community token | [Create a token](/tokens/create-from-dashboard) | -| Give an AI agent a wallet and let it post and trade | [AI Agents](/agents) | -| Call the REST API | [API Reference](/api-reference) | -| Read or call the smart contracts | [Smart Contracts](/contracts) | -| Understand the chain underneath | [æternity](/aeternity) | ## Start from the mechanism @@ -44,7 +34,7 @@ read these. | Mechanism | What it decides | | --- | --- | -| [Bonding curves](/tokens/bonding-curve) | What a community token costs, and why there is always a price and always liquidity | +| [Bonding curves](/tokens/bonding-curve) | How supply determines a community token's price and redemption value | | [Where the money goes](/concepts/value-flow) | Every fraction of every AE you spend, buy and sell side | | [Community DAOs](/dao) | Who controls a community's treasury and how a proposal passes | | [On-chain social](/concepts/on-chain-social) | What it means for a post to live in a smart contract | diff --git a/pages/resources/links.mdx b/pages/resources/links.mdx index 50e5899..942c99f 100644 --- a/pages/resources/links.mdx +++ b/pages/resources/links.mdx @@ -76,7 +76,7 @@ The GitHub organisation is `superhero-com`. | Web app | `https://github.com/superhero-com/superhero` | | Bug tracker and feedback | `https://github.com/superhero-com/superhero/issues` | | Indexer and API | `https://github.com/superhero-com/superhero-api` | -| BCL Sophia contracts | `https://github.com/superhero-com/bcl-contracts` | +| BCL Sophia contracts | `https://github.com/bctsl/bctsl-contracts` | | Superhero Wallet | `https://github.com/superhero-com/superhero-wallet` | | AI agent skill | `https://github.com/superhero-com/superhero-agent-skill` | @@ -93,7 +93,7 @@ You do not need these to use Superhero, but you do need them to build against it | Service | Mainnet | Testnet | | --- | --- | --- | -| API and WebSocket | `https://api.superhero.com` | Not publicly documented | +| API and WebSocket | `https://api.superhero.com` | No public endpoint documented | | æternity node | `https://mdw.wordcraft.fun` | `https://testnet.aeternity.io` | | Middleware | `https://mdw.wordcraft.fun/mdw` | `https://testnet.aeternity.io/mdw` | | Explorer | `https://aescan.io` | `https://testnet.aescan.io` | diff --git a/pages/rewards/affiliation.mdx b/pages/rewards/affiliation.mdx index 24f5a21..326dc56 100644 --- a/pages/rewards/affiliation.mdx +++ b/pages/rewards/affiliation.mdx @@ -5,10 +5,11 @@ description: "Four levels of referral rewards paid from every community-token bu # The Affiliation System -Every community-token buy on Superhero carries a 1% spread between the buy and sell price. -Half of it funds the community DAO; the other half funds a four-level referral system. -**0.5% of every buy is collected up front and credited to up to four levels of inviters above -the buyer.** Rewards accumulate in 30-day periods, and `withdraw()` pays the current and +The documented buy/sell spread is 1% of curve value before integer rounding. Buys allocate +approximately 0.5% of the curve cost to the community DAO and add another 0.5% for the +four-level referral system. Sells make no new allocation. +**The affiliation fee is 0.5% of the buy's curve cost**, credited to up to four levels of +inviters above the buyer. Rewards accumulate in 30-day periods, and `withdraw()` pays the current and previous period. The percentages, the payout period length and the qualification thresholds are constants in @@ -16,9 +17,11 @@ the contract; they cannot change without redeploying it. ## The split -When an invitee buys tokens, 0.5% of the transaction value is distributed up the chain: +When an invitee buys tokens, the treasury receives the curve cost as `transaction_value`. +The following percentages use that cost, before the affiliation fee, and are rounded down +to whole aettos when credited: -| Level | Relationship to the buyer | Share of the transaction | +| Level | Relationship to the buyer | Share of the curve cost | | --- | --- | --- | | 1 | The buyer's direct inviter | 0.300% | | 2 | That person's inviter | 0.125% | @@ -196,8 +199,8 @@ of the next one; a reward credited on the last day of a period has 30 days left. shown in the app is the last two buckets, not a lifetime total. - If you are accruing rewards but have not yet reached the 4 × 10 AE gate, the clock is - running: rewards earned more than two periods before you qualify are no longer claimable by - the time you can call `withdraw()`. + running: rewards earned two or more periods before the period in which you qualify are no + longer claimable by the time you can call `withdraw()`. - Once qualified, withdraw at least once every 30 days. `withdraw()` requires only the threshold: @@ -253,7 +256,7 @@ At registration the contract spends `redemption_fee_cover` to each one-time invi `revoke_invitation_code` returns the `invitation_amount` of an unredeemed code to the inviter; it rejects `ALREADY_REDEEMED` if the code has been claimed and `CALLER_NOT_INVITER` if anyone other than the registering address calls it. On success the code is deleted from state, so -the same one-time address cannot be re-registered. +the same one-time address can be registered again. ## Contract surface @@ -296,7 +299,10 @@ the same one-time address cannot be re-registered. The token sale calls `record_sale_transaction` with `protected = true`, so a failure inside the treasury does not abort the buy. The entrypoint accepts calls from any account with AE -attached. +attached, so recorded volume is not proof of a buy: attaching 0.5% of a claimed +`transaction_value` records it. About 0.05 AE records 10 AE of volume for any address, which can +fill the 4 × 10 AE gate without real buys. `register_invitation` also does not reject your own +address as the inviter. `get_invitation_code` returns field 0 as the inviter, field 1 as the amount in aettos, and field 2 as the already-claimed flag. diff --git a/pages/rewards/index.mdx b/pages/rewards/index.mdx index cccc3e1..da8d618 100644 --- a/pages/rewards/index.mdx +++ b/pages/rewards/index.mdx @@ -14,7 +14,7 @@ invited, four levels deep. They share a page in the app (`/trends/invite`). | | Superhero Rewards Program | Trading Affiliate Program | | --- | --- | --- | | What you do | Link your X account, post about Superhero | Create funded invite links, get people trading | -| Who pays | Superhero's backend, from a scan of your X posts | The bonding curve: 0.5% of every buy in your downline | +| Who pays | Superhero's backend, from a scan of your X posts | Each buy allocates 0.5% of its curve value across up to four referral levels, before integer rounding | | Where the money comes from | A program budget | Protocol fees, split on-chain | | Payout | Sent automatically to your connected wallet | You call `withdraw()` on the AffiliationTreasury contract | | Gate | X account with at least 100 followers | 4 direct invitees who have each spent at least 10 AE | @@ -25,18 +25,19 @@ invited, four levels deep. They share a page in the app (`/trends/invite`). The **Superhero Rewards Program** is an off-chain growth campaign, run at Superhero's discretion. -The **Trading Affiliate Program** is protocol mechanics. Every community-token buy carries a -1% spread; half goes to the community DAO and half to affiliation. That affiliation half is +The **Trading Affiliate Program** is protocol mechanics. The round-trip spread is 1% of +curve value; on buys, approximately half is allocated to the community DAO and half to +affiliation before integer rounding. That affiliation half is split across up to four levels of inviters above the buyer. Rewards accumulate in 30-day periods, and `withdraw()` pays the current and previous period, so withdraw monthly. ## The affiliation split at a glance ```text -Buyer pays AE for a community token - ├── 99.0% → bonding curve reserve (redeemable by sellers) - ├── 0.5% → community DAO treasury - └── 0.5% → affiliation system +Buyer pays 1.005 × B AE, where B is the curve value in AE + ├── 0.995 × B → bonding curve reserve (redeemable by sellers) + ├── 0.005 × B → community DAO treasury + └── 0.005 × B → affiliation system ├── 0.300% → level 1 (direct inviter) ├── 0.125% → level 2 ├── 0.050% → level 3 @@ -44,8 +45,9 @@ Buyer pays AE for a community token (a level with no inviter is not credited) ``` -The 0.5% is added on top of the curve price rather than carved out of it, so a buy whose -curve price is 1,000 AE costs the buyer 1,005 AE. +This diagram uses the continuous model before integer rounding; referral percentages are +of `B`, and uncredited shares remain in the treasury. The affiliation fee is added on top of +the curve price, so a buy whose curve price is 1,000 AE costs the buyer 1,005 AE. ## In this section diff --git a/pages/rewards/leaderboards.mdx b/pages/rewards/leaderboards.mdx index 44190ef..290a2d0 100644 --- a/pages/rewards/leaderboards.mdx +++ b/pages/rewards/leaderboards.mdx @@ -42,9 +42,9 @@ all and to 0 if both are ``` -The 7d and 30d boards measure portfolio *growth*, which a deposit inflates and a withdrawal -deflates. The All board measures return on invested capital. A wallet can rank very -differently on each. +The 7d and 30d boards measure change in the backend's computed token-portfolio value; +buys can increase that value and sells can decrease it. The All board measures return on +invested capital. A wallet can rank very differently on each. For the All window, the window-based figures (the sparkline, the maximum drawdown, and the buy and sell counts) cover **the last 365 days**. Only PnL and ROI are all-time. @@ -60,8 +60,8 @@ buy and sell counts) cover **the last 365 days**. Only PnL and ROI are all-time. Custom ranges are entered as `dd/mm/yyyy hh:mm` in local time and converted to ISO-8601 before the request. Both ends are required; a start after the end is rejected in the client, -and an unparseable date disables the query. When a custom range is applied, `window` and -`points` are omitted. +and an unparseable date disables the query. The API rejects periods longer than 14 days. +When a custom range is applied, the app omits `window` and `points`. ## What each row shows @@ -76,7 +76,7 @@ and an unparseable date disables the query. When a custom range is applied, `win | `created_tokens_count` | Tokens this account created | | `owned_trends_count` | Owned trends | | `portfolio_value_usd_sparkline` | The inline sparkline, an array of point pairs | -| `volume_usd` | Present in the response; not rendered on the card | +| `volume_usd` | Present for custom ranges; not rendered on the card | Rank is computed client-side from the page offset (`(page − 1) × 15 + index + 1`), so it is the rank within the currently selected metric and window. @@ -96,15 +96,18 @@ below one US dollar. Pass `minAumUsd=0` to include them. Custom ranges bypass the snapshot and compute live. The candidate pool is then the top addresses by USD volume of buy and sell transactions **inside that range** rather than -all-time, sized by `maxCandidates`, default 100, maximum 500. +all-time. `maxCandidates` defaults to 100 and its requested value is clamped to 500, then +raised to at least the page offset plus limit. Deep pages can therefore enlarge the pool +beyond 500 candidates. ## Which trades count -Bonding-curve trades only: `buy`, `sell` and `create_community` calls on community token -sales. [DEX swaps](/defi/swap), liquidity provision and plain AE transfers are not counted, -either for the volume ranking that decides who is a candidate or for the `buy_count` and -`sell_count` on each card. Portfolio value is whatever the account's holdings are worth, so -AUM and the sparkline can move for reasons the buy and sell counts never show. +The candidate and activity queries use indexed bonding-curve transactions, excluding +[DEX swaps](/defi/swap), liquidity provision and plain AE transfers. Snapshot candidate volume +includes `create_community` rows; custom-range candidate volume uses only `buy` and `sell`. +In both modes, `buy_count` counts only `buy` rows and `sell_count` only `sell` rows, so a +creator's initial purchase is not included in that buy counter. AUM and the sparkline come +from the backend's token-PnL calculations and can move independently of those counts. `tradingOnly=true` narrows it further, for custom ranges only: it switches the selected-period PnL and ROI to realised token-trading PnL and cost basis, excluding portfolio @@ -124,16 +127,16 @@ Base URL is Superhero's API: `https://api.superhero.com` on mainnet. | `sortDir` | `ASC` or `DESC`. Defaults to `DESC`, except `sortBy=mdd` which defaults to `ASC`. | | `window` | `7d`, `30d`, `all`. Default `7d`. | | `points` | Number of sparkline points. **Ignored for `window` requests**: the snapshot fixes it at 8 for 7d, 12 for 30d and 24 for all. For a custom range it is clamped to 2–12, default 8. | -| `startDate`, `endDate` | ISO-8601, both required together, end after start. Switches to the live path; mutually exclusive with `window`. | +| `startDate`, `endDate` | ISO-8601, both required together, end after start, at most 14 days apart. Selects the live path even if `window` is also supplied. | | `minAumUsd` | Integer, 0 or more. **Defaults to 1**, which excludes near-zero portfolios. | | `tradingOnly` | Boolean. Custom ranges only: bases PnL and ROI on realised trading PnL rather than portfolio value change. | | `page` | 1-based. Default 1. | | `limit` | Page size, 1–50. Server default 18; the UI sends 15. | -| `maxCandidates` | Ignored for `window` requests. For a custom range it sizes the live candidate pool, default 100, maximum 500. | +| `maxCandidates` | Ignored for snapshot windows. For a custom range, defaults to 100; clamped to 500, then raised to at least the page offset plus limit. | -The response is the standard paginated envelope: an `items` array of the fields above, plus a +The response has an `items` array of the fields above, plus a `meta` object carrying `page`, `limit`, `totalItems`, `totalPages`, `window`, `sortBy`, -`sortDir` and a `timeFilter` block with the resolved `value`, `unit`, `start` and `end`. +`sortDir` and, for custom ranges only, `timeFilter: { start, end }` with ISO timestamps. ```bash curl "https://api.superhero.com/api/accounts/leaderboard?sortBy=pnl&sortDir=DESC&window=7d&points=7&page=1&limit=15" diff --git a/pages/social/chat.mdx b/pages/social/chat.mdx index 2e46240..9d350ae 100644 --- a/pages/social/chat.mdx +++ b/pages/social/chat.mdx @@ -1,6 +1,6 @@ --- title: "Chat" -description: "Realtime messaging over Nostr: direct messages, community rooms, token-gated membership and the relay." +description: "Real-time messaging over Nostr: direct messages, community rooms, token-gated membership and the relay." --- # Chat @@ -118,16 +118,24 @@ The API runs a reactive pipeline off the middleware's live transaction stream: the tokens moved outside the curve. 2. A balance change, a `CommunityManagement` state change (threshold, moderator set, muted set or privacy flag), or a Nostr link change each trigger a recheck. -3. Eligibility is recomputed for the affected `(sale_address, member_address)` pairs as - `balance >= min_token_threshold AND NOT muted`, raw against raw with no decimal shifting. -4. On a real flip, the bot publishes the NIP-29 kind 9000 (add) or 9001 (remove) event to the - relay, moving `relay_state` through `pending_add` to `added`. +3. Ordinary-member eligibility is recomputed for the affected `(sale_address, member_address)` + pairs as `balance > 0 AND balance >= min_token_threshold AND NOT muted`, raw against raw with + no decimal shifting. A zero threshold still requires a positive holding. Moderators bypass + the positive-balance check, but the eligibility predicate still checks the threshold and mute. +4. A changed eligibility state updates the desired relay membership. The publishing pipeline + sends NIP-29 kind 9000 (add) or 9001 (remove) events subject to the identity, mute and admin + checks below; an acknowledged add advances `relay_state` from `pending_add` to `added`. `POST /api/rooms/{saleAddress}/recheck` forces one pass through the same path for a single address; it is a repair tool, not the normal mechanism. A reconciliation service and a startup backfill cover drift. When no relay is configured, the API still indexes balances and serves the read endpoints but publishes nothing. +Eligibility and relay membership are separate: provisioning relay membership requires a linked +Nostr key. Existing admin relay states and configured-admin removal guards can preserve relay +membership when the eligibility predicate becomes false; a mute still blocks new member-add +events. + A room row carries: | Field | Meaning | diff --git a/pages/social/comments.mdx b/pages/social/comments.mdx index 89c529f..918a8b0 100644 --- a/pages/social/comments.mdx +++ b/pages/social/comments.mdx @@ -115,7 +115,7 @@ node scripts/superhero-comment.mjs get 50 2 # limit, page wallet. `comment_post_id` is the bare integer. Add `_v3` before you use it as an API id or as a parent for a further reply. -A comment pays gas only, the same as a post. +A comment pays a network transaction fee and execution gas, the same as a post. ## Limits diff --git a/pages/social/delegated-posting.mdx b/pages/social/delegated-posting.mdx index 8818b58..95534f0 100644 --- a/pages/social/delegated-posting.mdx +++ b/pages/social/delegated-posting.mdx @@ -7,8 +7,8 @@ description: "Let a relayer pay the gas while the author keeps attribution: the `post_without_tip_sig` lets any account submit a post on behalf of an author. The submitter pays the gas; the on-chain record attributes the post to the signer. This is the mechanism -behind gasless onboarding: a user signs a message in a wallet that holds no AE, and a relayer -turns it into a transaction. +behind gasless onboarding: a user signs the post digest with a key that holds no AE, and a +relayer turns it into a transaction. ## The entrypoint @@ -101,10 +101,10 @@ Sign `postDigest(title, media)` with the author's Ed25519 key and hand the relay lowercase hex string with no prefix (the convention the address-links API uses) is a good wire format. -If you are signing from a connected wallet rather than a raw key, the wallet's `signMessage` -applies the prefix framing itself over the message you give it. Pass the 32-byte inner Blake2b -digest as that message to reproduce steps 2 to 4 exactly; passing the raw text would frame the -text rather than its digest. +Do not assume a connected wallet's `signMessage` can sign this binary message body. SDK v14's +method accepts text; signing the post text or a hex-encoded digest changes the bytes. Use a +wallet API that explicitly supports this construction, or the raw-key example in +[Tipping v3](/contracts/tipping#the-full-construction). ## Run a relayer @@ -151,14 +151,15 @@ when the relayer submitted it, not when the author signed it. Use `post_without_tip_sig` when the author cannot pay: new-user onboarding before the wallet is funded, or a custodial surface that holds no user key but can forward a signature. For -everything else prefer `post_without_tip`: it is simpler, and the author pays only gas. +everything else prefer `post_without_tip`: it is simpler, and the author pays the network +transaction fee and execution gas. ## Related - [Posting](/social/posting): the direct path, the data model, and the shared conventions. - [The Tipping contract](/contracts/tipping): the contract reference for both entrypoints. -- [AddressLink](/identity/address-link): the same signed-message construction, with a - contract-held nonce. +- [AddressLink](/identity/address-link): the same personal-message prefix, with the full message + text as the body and a contract-held nonce. - [Contract security](/contracts/security): the protocol's wider security model. - [Sophia standard library](https://github.com/aeternity/aesophia/blob/master/docs/sophia_stdlib.md): the reference for `Crypto.verify_sig`. diff --git a/pages/social/feed.mdx b/pages/social/feed.mdx index 669278b..bdf2676 100644 --- a/pages/social/feed.mdx +++ b/pages/social/feed.mdx @@ -90,8 +90,10 @@ does not outrank a younger dead one. Eight of the ten are reader-scalable. Each accepts `low`, `med` or `high`, which multiply that weight by **0.6, 1.0 and 1.5** respectively. `med` is the default and the client omits it, so a request carries only the signals you changed. In the app these are the **Customize** controls -next to the sort selector. Because the multipliers scale the weights, `high` on every signal -leaves the order unchanged; scaling only matters relative to other signals. +next to the sort selector. Setting every adjustable signal to `high` can change the ranking: +freshness, the freshness-gated velocity amplifier, tie rotation and the staleness penalty are not +scaled with those signals. Custom requests also bypass the backend's daily ranking shuffle. +The app still applies its separate session-seeded shuffle to returned page items. ### Where each input comes from diff --git a/pages/social/hashtags-and-topics.mdx b/pages/social/hashtags-and-topics.mdx index 992880f..2069b8b 100644 --- a/pages/social/hashtags-and-topics.mdx +++ b/pages/social/hashtags-and-topics.mdx @@ -162,8 +162,9 @@ Once the token exists, every `#tag` matching its name or symbol in any post, inc written before the token existed, resolves to its page. Nothing rewrites the old posts; resolution starts succeeding. -From there the token layer takes over: price is set by the bonding curve, 1% of every trade -splits between the community DAO and the affiliation system, and holders govern the treasury. +From there the token layer takes over: price is set by the bonding curve, buys fund the community +DAO and the affiliation system, and holders govern the treasury. Each allocation is approximately +0.5% of the buy's curve value; the affiliation fee is added to the buyer's payment. See [Tokens overview](/tokens/overview) and [Trending score](/tokens/trending-score). ## The whole chain diff --git a/pages/social/index.mdx b/pages/social/index.mdx index 0568744..1c53e65 100644 --- a/pages/social/index.mdx +++ b/pages/social/index.mdx @@ -6,7 +6,7 @@ description: "Posting, commenting, tipping, hashtags, chat, notifications and mo # Social Posts and comments are written to the `Tipping` v3 contract, so they are permanent and -attributable. Chat is off chain by design and runs over Nostr relays for realtime messaging, so check +attributable. Chat is off chain by design and runs over Nostr relays for real-time messaging, so check which layer you are using before you publish anything. ## On chain or not diff --git a/pages/social/moderation.mdx b/pages/social/moderation.mdx index 87ca4c1..6031da1 100644 --- a/pages/social/moderation.mdx +++ b/pages/social/moderation.mdx @@ -140,11 +140,13 @@ pipeline enforces it: 1. The API reads `CommunityManagement.get_state()` and mirrors `muted_user_ids` into the room's muted list, alongside `moderators`, `min_token_threshold`, `is_private` and the owner address. The relay's admin and role lists are derived from the same read. -2. Eligibility for the room is `balance >= min_token_threshold AND NOT muted`, where the muted - check compares the member's æternity address against that list. -3. A muted member is removed from the relay group with a kind-9001 event, and the sync refuses - to publish a kind-9000 add for any member currently muted, so a mute is not undone by a - later re-sync. +2. Ordinary-member eligibility is `balance > 0 AND balance >= min_token_threshold AND NOT muted`, + using raw base units. A zero threshold still requires a positive holding. Moderators bypass + the positive-balance check, but the predicate still checks the threshold and mute. +3. An ineligible ordinary member is removed from the relay group with a kind-9001 event, and + the sync refuses to publish a kind-9000 add for a muted member. Relay publication also + requires a linked Nostr key. Existing admin relay states and configured-admin removal + guards are separate from the eligibility predicate; do not assume a mute removes every admin. Mute a holder and they become ineligible for that community's chat room regardless of balance, until the mute is lifted. @@ -164,7 +166,7 @@ silences your own alerts and changes nothing for anyone else. See | Gate | Where | Rule | | --- | --- | --- | | Opening a DAO vote | `DAO.add_vote` | `token.balance(Call.caller) >= minimum_token_threshold`, else `ADD_VOTE_TOKEN_HOLDER_MISSMATCH` | -| Entering the community chat room | The rooms eligibility check | raw balance `>=` raw threshold, and not muted | +| Entering the community chat room | The rooms eligibility check | Ordinary members need a positive raw balance meeting the raw threshold, and must not be muted; relay publication also needs a linked Nostr key | It starts at one whole token (`10 ^ 18`) and moves only by a `ChangeMinimumTokenThreshold` vote. The same value surfaces in the chat rooms API as `min_token_threshold`, alongside the diff --git a/pages/social/notifications.mdx b/pages/social/notifications.mdx index f156f6e..05a083a 100644 --- a/pages/social/notifications.mdx +++ b/pages/social/notifications.mdx @@ -6,7 +6,7 @@ description: "The notification feed, browser push, preferences and devices — e # Notifications Superhero has two independent notification systems. The **bell** is a server-side feed -(someone replied, someone sent you AE, a room let you in) delivered over REST plus a socket and +(someone replied, tipped you or followed you) delivered over REST plus a socket and optionally as an OS notification. The **transaction banner** is a purely local progress indicator for whatever you are signing right now. They share no code and no delivery path. @@ -64,28 +64,38 @@ throwing. ### Types, channels, and where a click lands -The catalog has six types, and each declares which channels it goes out on. `database` is the -channel that writes a bell row, so the web bell carries comments and invitation claims; the -other four types reach mobile push only. +The [API's notification catalog](https://github.com/superhero-com/superhero-api/blob/72a57261a054c4f3506b4b856900f64200bdb534/src/notifications/notification-catalog.ts) +has ten types, each with declared delivery channels. `database` writes a bell row; +`web-push` delivers browser push when configured and subscribed; `expo` delivers mobile push. +Preferences and each type's dispatch checks still apply. | Type | Channels | Trigger | | --- | --- | --- | | `post-comment` | expo, **database**, web-push | Someone comments on a post you authored | | `invitation-claimed` | expo, **database**, web-push | Someone redeems an invitation you created | -| `incoming-transfer` | expo only | Any incoming `SpendTx` above `NOTIF_MIN_AMOUNT_AETTOS` | +| `new-follow` | expo, **database**, web-push | Someone follows you | +| `token-price-alert` | expo, **database**, web-push | A token reaches a price alert you set | +| `tip-received` | **database**, web-push | Someone tips you or one of your posts | +| `post-mention` | expo, **database**, web-push | Someone tags your account in a post | +| `incoming-transfer` | expo only | A non-self incoming `SpendTx` at or above `NOTIF_MIN_AMOUNT_AETTOS`, with a registered device | | `announcement` | expo only | Authored by the Superhero team | | `room-membership` | expo only | You are added to or removed from a token-gated room | | `room-messages` | expo only | New messages in a room you belong to | -`incoming-transfer` is kept off the web feed because it fires for every transfer on chain to -the recipient. The client's routing table maps all six, because the same payload also feeds the -mobile app: +`incoming-transfer` is kept off the web feed; a recognised tip has its own `tip-received` +notification. The [reviewed web client's routing](https://github.com/superhero-com/superhero/blob/ef9526e1e2ca7d9ba5005b549c988109dc7ecd12/src/features/notifications/notificationNavigation.ts) +handles these destinations. Backend support alone does not establish support in every client +version; older web versions lacked the price-alert destination. | Type | Destination | Actor field | | --- | --- | --- | | `post-comment` | `/post/` plus `data.commentId`, falling back to `data.parentPostId` | `data.commenter` | | `incoming-transfer` | `/wallet` | `data.sender` | | `invitation-claimed` | `/wallet` | `data.claimer` | +| `new-follow` | `/users/` plus `data.follower` | `data.follower` | +| `token-price-alert` | `/trends/tokens/` plus `data.saleAddress` | None | +| `tip-received` | `/post/` plus `data.postId` for a post tip; `/wallet` otherwise | `data.sender` | +| `post-mention` | `/post/` plus `data.postId` | `data.author` | | `room-membership` | `/trends/tokens/` plus `data.saleAddress` | None | | `room-messages` | `/trends/tokens/` plus `data.saleAddress` | None | | `announcement` | None; the row renders as non-navigable | None | @@ -97,7 +107,7 @@ ids) rather than a URL, because the mobile app has different routes. ### What suppresses a notification -Every send passes three gates before a channel sees it; `post-comment` shows all three: +Comment notifications pass three gates before delivery; other types have their own checks: 1. **Self-action.** You are never notified about your own reply. 2. **Preference.** The recipient's opt-out is checked before the rate cap, so an opted-out @@ -163,10 +173,10 @@ payload wins over the mapping after an origin check. ### The preference keys -A preference key is a catalog `type`, and the six keys are exactly the types in the table -above: `incoming-transfer`, `announcement`, `invitation-claimed`, `post-comment`, -`room-membership`, `room-messages`. The catalog is ordered, and the mobile preferences screen -renders its rows in that order. +A preference key is a catalog `type`. The API accepts all ten types in the table above and +returns them in catalog order from `GET /api/notifications/{address}/preferences`, including +each type's `id`, `title`, `short_description` and `enabled` state. Use that returned catalog for API +integrations; it does not establish which controls a particular client screen exposes. The write is a partial upsert behind a signed challenge: @@ -183,8 +193,9 @@ rejected against the catalog. The model is opt-out: a type with no stored row is `/notifications/devices` registers an **Expo push token**, for the native apps; the web-push endpoints register a **VAPID browser subscription**. An expo-only type reaches a registered -device, and nothing if the account has none. Both registration paths are behind their own -signed challenge, and deregistration binds the signature to both the address and the token. +device, and nothing if the account has none. Expo registration uses a signed device challenge; +browser subscription uses the notification-feed bearer session. Device deregistration binds +its signature to both the address and the Expo token. The per-room mute control lives with chat: it writes `muted` and a tri-state account-wide `mute_all` through `POST /api/rooms/{saleAddress}/mute` behind its own signed challenge. The @@ -208,12 +219,13 @@ Step 4 of 4 — transferring the name to your wallet Others cover token creation, swaps, wrapping and unwrapping AE, liquidity changes, and signing a profile update. None of these are recorded in the notification feed. -## No tip notification +## No tip notification? -There is no tip type in the catalog. `incoming-transfer` does fire for a tip, since a tip is a -plain `SpendTx`, but it is expo-only and never reaches the bell. An incoming tip produces a -mobile push if you have a registered device, and nothing in the web app. See -[Tipping](/social/tipping). +`tip-received` writes a web bell item and can send browser push when a recognised tip is +indexed live and passes the preference, amount and rate-cap checks. Self-tips do not notify. +A post tip opens the tipped post; a profile tip opens the wallet. The same +`SpendTx` can produce the Expo-only `incoming-transfer` notification for a registered mobile +device, so `tip-received` itself does not send Expo push. See [Tipping](/social/tipping). ## Related diff --git a/pages/social/posting.mdx b/pages/social/posting.mdx index 78ce922..a8c710b 100644 --- a/pages/social/posting.mdx +++ b/pages/social/posting.mdx @@ -208,8 +208,8 @@ The ACI ships with the agent skill at `contracts/Tipping_v3.aci.json`. ## Cost -A post is a single stateful contract call with no payable amount, so you pay gas only. Gas -follows the network's gas price and the size of the stored text. +A post is a single stateful contract call with no payable amount. You pay the transaction +fee and execution gas. The cost depends on the transaction size, gas used and gas price. ## Permanence diff --git a/pages/social/tipping.mdx b/pages/social/tipping.mdx index e9c8e42..7c64b48 100644 --- a/pages/social/tipping.mdx +++ b/pages/social/tipping.mdx @@ -7,7 +7,8 @@ description: "Send AE directly to a creator against a specific post — the payl A tip on Superhero is a plain AE transfer with a payload that names the post: a spend transaction from your account straight to the author's. The indexer reads the payload to -attribute it. There is no fee, no escrow and no intermediary. +attribute it. There is no platform tipping fee or escrow; the sender still pays the network +transaction fee. ## The transaction @@ -31,8 +32,9 @@ There is nothing to claim, no vesting, and no minimum enforced by the protocol. The `Tipping` v3 contract is not involved: it stores posts, has no `payable` entrypoint and holds no balance. (A companion `Tipping_v3_Getter` contract adds one read helper, -`get_tip_by_id(c : Tipping, tip_id : int) : option(Tipping.tip)`, for fetching a single post -without pulling the whole state.) +`get_tip_by_id(c : Tipping, tip_id : int) : option(Tipping.tip)`, which returns a single post. +It calls `get_state()` internally, so the VM still loads every post and its gas grows with the +post count; it only shrinks the response.) Practical consequences: @@ -48,7 +50,10 @@ Practical consequences: 2. The payload is decoded from its `ba_…` form to a string. It must start with `TIP_PROFILE` or `TIP_POST`, otherwise the transaction is skipped. 3. For a `TIP_POST:` payload, everything after the colon is taken as a post id and looked up - directly by `id`. A miss leaves the tip unattached to a post. + directly by `id`. A miss leaves the tip unattached to a post. The recipient is **not** + checked: any spend with that payload counts toward the post's tip totals and popular + ranking, whoever receives the AE. Only a `tip-received` notification requires that the post's + author was paid. 4. Self-tips are dropped, not stored. For a post tip that means `sender == post.sender_address` (tipping your own post), and for a profile tip `sender == receiver`. 5. The row is keyed on `tx_hash`, so reprocessing the same transaction is idempotent. @@ -100,7 +105,7 @@ sorts by value rather than lexically. `type` holds the **whole decoded payload** not on the bare word `TIP_POST`. Tip signals also feed the popular feed: `tipsAmountAE`, `tipsCount` and `uniqueTippers` are -three of the eight weighting inputs a reader can scale, all computed with self-tips excluded. +three of the eight weighting inputs a reader can scale, all computed with tips from the post's own author excluded. See [The Feed](/social/feed). ## Tipping an address that has never used Superhero @@ -111,16 +116,19 @@ pending-tip pool and no reclaim path. ## Tips and notifications -There is no tip notification type. The closest is `incoming-transfer`, which fires on any -incoming `SpendTx`, a tip included, above `NOTIF_MIN_AMOUNT_AETTOS` (default 0, meaning -off). That type is mobile push only, so an incoming tip produces a mobile push if the recipient -has a registered device, and nothing in the web bell. See -[Notifications](/social/notifications). +Recognised tips indexed live can trigger `tip-received`, which writes a web bell item and +sends browser push when subscribed. Self-tips, tips below the amount floor and those blocked by +preferences or the rate cap do not notify. The floor is at least one aetto, raised by +`NOTIF_MIN_AMOUNT_AETTOS` when configured higher. + +The same spend can also trigger the Expo-only `incoming-transfer` notification for a +registered mobile device. `tip-received` does not send a second Expo push. See +[Notifications](/social/notifications#no-tip-notification). ## Related - [Posting](/social/posting): the ids and `_v3` suffix convention the payload depends on. - [The Feed](/social/feed): how tip signals influence popular ranking. -- [Notifications](/social/notifications): why a tip does not raise a bell notification. +- [Notifications](/social/notifications): web tip notifications and mobile transfer push. - [Value flow](/concepts/value-flow): where money moves elsewhere in the protocol. - [Transactions](/api-reference/transactions): reading spend transactions and their payloads. diff --git a/pages/tokens/bonding-curve.mdx b/pages/tokens/bonding-curve.mdx index 47d0574..6f9b217 100644 --- a/pages/tokens/bonding-curve.mdx +++ b/pages/tokens/bonding-curve.mdx @@ -7,14 +7,14 @@ description: "The exponential curve that prices every Superhero community token, Every Superhero community token is priced by one deterministic function of its own supply. Buying mints new tokens and moves you up the curve; selling burns tokens and moves you down it. Because -price is computed from supply, there is always a quote and always liquidity. There is no order book, no -matching engine and no counterparty on the other side of your trade. +price is computed from supply, trades use contract quotes and a reserve funded by buys. There is +no order book, matching engine or counterparty on the other side of your trade. Superhero uses an **exponential** curve, implemented by the `BondingCurveExponential` contract. The contract evaluates `e^x` as a bounded Taylor series in integer arithmetic (at most 100 terms, stopping as soon as a term floors to zero), which is what `curve_type()` means when it returns -`"TAYLOR_EXPONENTIAL_V1"`. The series agrees with the closed form below to within `4e-19 AE` at -every supply in the examples below. The integer the contract returns is the price you are charged; +`"TAYLOR_EXPONENTIAL_V1"`. The integer it returns is the closed-form value below, rounded +down: under 1 aetto below it for whole-token counts, under 2 for arbitrary counts. The integer the contract returns is the price you are charged; [Curve Parameters & Units](/tokens/curve-parameters) has a reference implementation that reproduces it exactly. @@ -138,9 +138,10 @@ from supply 10,000,000, where spot is `1.052709e-4 AE`: | 50,000,000 | 21,699.788231 | 4.33996e-4 | +312.3% | Buying 10,000,000 tokens in one transaction doubles the supply and costs a 54% premium to spot. -Splitting the order does **not** help: the curve is path-independent, so ten buys of 1,000,000 from -a rising supply cost exactly the same total as one buy of 10,000,000. Only trade size and starting -supply change your average price. +In the continuous model, splitting the order does **not** reduce this price impact: the curve +integral is path-independent, so ten consecutive buys of 1,000,000 cost the same curve value as +one buy of 10,000,000 with the same starting supply and no intervening trades. Integer rounding +can change the exact totals, and each transaction pays its own network fee. A large sell realises an average price below the quoted spot for the same reason, in reverse. `minimal_return_required` protects you from that. See @@ -186,18 +187,23 @@ small per trade, meaningful in aggregate. Spot prices at a few reference supplie | 100,000,000 | 1.718382e-3 | 1.709790e-3 | | 200,000,000 | 6.389156e-3 | 6.357210e-3 | -The curve is tuned on the expectation that only **10–20% of the total supply** will ever be reached, -which is why the interesting price action is packed into the first couple of hundred million tokens. +The exponent determines how quickly price grows with supply. There is no fixed maximum supply, +so a percentage of maximum supply is not defined for this curve. -## Why the reserve is always solvent +## Why the reserve covers the supply -The sell curve sits strictly below the buy curve at every supply level, so the AE paid into the sale -contract always exceeds the AE it could ever be asked to pay out. Selling the entire circulating -supply back to the curve is always possible. +Full redemption follows in the ideal continuous model. Each buy retains the quote for +immediately selling its newly minted tokens; in that model, these amounts sum to the sell-curve +integral over the circulating supply. Integer truncation means separately rounded quotes need +not sum to the quote for a combined amount, so this argument alone does not prove exact solvency +for every sequence of integer trades. See +[Reserve accounting and rounding](/concepts/value-flow#reserve-accounting-and-rounding) for the +limits of the continuous-model argument. -At a supply of 10,000,000 tokens, buyers have paid in `518.09 AE` in total, and selling every one of -those tokens back would return `515.50 AE`. The `2.59 AE` difference is the DAO's accumulated -spread, and it never has to be given back. +In that model, reaching a supply of 10,000,000 tokens from zero costs `518.09 AE` before the +affiliation fee, and selling the full supply quotes `515.50 AE`. The `2.59 AE` difference is +allocated to the DAO on buys, leaving the reserve for sellers. These rounded examples are not a +proof for every sequence of integer trades or a check of deployed balances. ## The spread @@ -206,7 +212,7 @@ buys, so the **total spread between buy and sell price is 1% of the curve value* community DAO and 0.5% to the affiliation system. From the buyer's side: you hand over `1.005 ×` the curve integral and can immediately sell back for -`0.995 ×` it, so a round trip at unchanged supply returns `0.995 / 1.005 = 0.99502…` of what you +`0.995 ×` it, so a round trip at unchanged supply returns `0.995 / 1.005 = 0.99004975…` of what you paid, a **0.995% loss on an instant round trip**. See [Fees & Slippage](/tokens/fees-and-slippage) for the full breakdown and [Risks](/tokens/risks) for what that means for a position. @@ -221,13 +227,14 @@ for the full breakdown and [Risks](/tokens/risks) for what that means for a posi | Price at zero activity | Defined by the formula | Defined by the formula | Undefined until someone seeds the pool | | Cost of a trade | Integral of the curve over the minted range | Integral of the curve over the minted range | Determined by the invariant x·y = k | | Price impact of a big buy | Compounding: grows exponentially | Proportional to size | Grows as the pool is drained; unbounded | -| Fee model | 1% spread baked into two curves | Implementation-defined | Explicit swap fee (e.g. 0.30%) to LPs | +| Fee model | 0.5% buy/sell curve gap (to the DAO) plus a 0.5% affiliation fee on buys | Implementation-defined | Explicit swap fee (e.g. 0.30%) to LPs | | Rug-pull surface | No LP to withdraw | No LP to withdraw | LPs can remove liquidity | -Two practical consequences. There is no liquidity to pull: the reserve is held by the sale contract -and is sufficient to redeem everything. And an exponential curve punishes large late buys much -harder than a constant-product pool of comparable depth. The price impact of doubling the supply -is a factor of `e^(k·supply)`, not a bounded ratio. +Two practical consequences. The reserve is held by the sale contract, without an LP withdrawal +mechanism. An exponential curve punishes large late buys much harder than a constant-product pool +of comparable depth. Past about a million tokens, doubling the supply multiplies the spot price by +about `e^(k·supply) + 1` (≈2.1× from 10M to 20M tokens, ≈3.7× from 100M to 200M), a ratio that +keeps growing with supply. Community tokens trade only against their own curve. Superhero's AMM for ordinary token pairs is [the DEX](/defi/swap). @@ -254,9 +261,9 @@ tokens. Use `calculate_buy_price` and `calculate_sell_return` for quotes, or `bu exact spot value. `get_minimum_count()` returns `10^12`, and every pricing call requires `count >= minimum_count` -(`MINIMUM_TOKENS_REQUIRED`). Since counts are in 18-decimal units that floor is `10^-6` tokens, a -guard against a trade rounding to zero inside the integer arithmetic, not an order minimum. It fires -when a caller passes a whole-token count where the contract expected token decimal units. +(`MINIMUM_TOKENS_REQUIRED`). Since counts are in 18-decimal units that floor is `10^-6` tokens. It is +enforced on every buy, sell and quote, so a balance under `10^-6` tokens cannot be sold. It also +fires when a caller passes a whole-token count where the contract expected token decimal units. ## Related diff --git a/pages/tokens/buying-and-selling.mdx b/pages/tokens/buying-and-selling.mdx index 58aa1be..434187b 100644 --- a/pages/tokens/buying-and-selling.mdx +++ b/pages/tokens/buying-and-selling.mdx @@ -157,7 +157,8 @@ if (existing === undefined) { `create_allowance` fails if an allowance already exists, which is why the check matters. `change_allowance` takes a signed **delta**, not an absolute value: raising an allowance from 5 to 8 means passing `3`, and lowering it from 8 to 5 means passing `-3`. `reset_allowance(for_account)` -clears it entirely. +sets it to zero but keeps the record. To grant it again after a reset, use `change_allowance`, +not `create_allowance`. A standing allowance authorises the sale contract to move that many tokens until you reduce it. Set it to exactly the amount you are selling on each sell. @@ -223,7 +224,8 @@ const sold = await sale.sell(count, minReturn, { omitUnknown: true }); console.log('sell tx', sold.hash); ``` -`omitUnknown: true` tells the SDK to ignore ACI entries it cannot decode rather than throwing. +`omitUnknown: true` tells the SDK to skip emitted events that have no definition in the supplied +ACIs rather than throwing during event decoding. ## Why the executed price differs from the quote @@ -233,6 +235,7 @@ console.log('sell tx', sold.hash); | Other trades landing between quote and execution | Either way | Bounded by your tolerance; this is what the guards are for | | The 0.5% affiliation fee on a buy | Against you | 0.5% of the curve value, already inside `price()`, not inside `calculate_buy_price()` | | Off-chain estimates using a trapezoidal integral | Overstates by up to ~20 ppm on very large trades | Negligible, but see [Curve Parameters & Units](/tokens/curve-parameters) | +| The web app's sell estimate | Overstates by about 0.5% | It integrates the buy curve without the 0.995 sell factor. The minimum return uses the on-chain `sell_return`, so execution is unaffected | The quote you get from `price()` or `sell_return()` is exact at the supply it was read at. Everything that moves it afterwards is other people. diff --git a/pages/tokens/collections-and-naming.mdx b/pages/tokens/collections-and-naming.mdx index 76e52c5..10000f4 100644 --- a/pages/tokens/collections-and-naming.mdx +++ b/pages/tokens/collections-and-naming.mdx @@ -78,8 +78,9 @@ uppercase Cyrillic. All four cap names at 20 characters. `WORDS` was deployed fr account than the other three on mainnet, so its `-ak_` suffix differs. A collection that exists on-chain but is not in the backend's configuration is not indexed, and -tokens created in it do not appear in the app. There is no factory entrypoint that enumerates -collections; to discover them from the chain, replay `CreateCollection(string, address)` events. +tokens created in it do not appear in the app. The factory's `get_state()` returns the +whole registry, but on mainnet it exceeds the dry-run gas limit; to discover collections from the +chain, replay `CreateCollection(string, address)` events. The API returns the resolved collection on a token as `collection` (the full id) and `collection_info`, which carries `id`, `name`, `description` and `allowed_name_length`. @@ -114,7 +115,7 @@ valid names rather than rejecting them. ## How the app picks a collection for you -Because every collection allows `-`, a name such as `A-B` is valid in all of them at once. The app +Because every collection allows `-`, a name such as `--` is valid in all of them at once. The app resolves this in three steps, re-derived on every keystroke: 1. **Detect.** Every collection whose character rules accept the name, in schema order. @@ -161,9 +162,12 @@ payable stateful entrypoint create_collection(collection_name : string, allowed_ | Where does the 555 AE go? | `Chain.spend` to `ak_11111111111111111111111111111111273Yts`, the all-zero account. It is **burned**, not paid to the platform or to a treasury. | The creator chooses the collection's rules outright: the length cap and the whole character -whitelist are arguments. The only uniqueness check is `collection_ALREADY_EXISTS`, and because the -id is suffixed with the caller's address, it only stops the *same account* creating the same name -twice. +whitelist are arguments. `collection_ALREADY_EXISTS` checks the raw input against registry +keys, but entries are stored under `-`, so the guard never stops a repeat. If the +same account calls `create_collection` again with the same name, the call succeeds, burns +another 555 AE and replaces the registry entry with an empty one: the collection's names stop +resolving through `has_community` and `get_token_sale`, and they can be registered again. +Existing sales keep working, because the factory's set of known sales is not touched. The 555 AE matches the fee for opening a DAO proposal and serves the same purpose: it makes namespace spam expensive. A DAO proposal's 555 AE goes to the community treasury; a collection's is diff --git a/pages/tokens/create-from-cli.mdx b/pages/tokens/create-from-cli.mdx index 12e4ad1..ef9ab9d 100644 --- a/pages/tokens/create-from-cli.mdx +++ b/pages/tokens/create-from-cli.mdx @@ -22,7 +22,7 @@ the skill's root. It signs with an in-memory account built from `AE_PRIVATE_KEY` ## Pre-flight -1. Confirm you have AE for gas (about 0.001 AE for creation, plus whatever you intend to pre-buy): +1. Confirm you have AE for the transaction fee, execution gas and any buffered initial buy: ```bash node scripts/superhero-wallet.mjs balance @@ -57,7 +57,7 @@ node scripts/superhero-token-create.mjs create "MYTOKEN" 0.1 | Parameter | Meaning | | --- | --- | | Name | Uppercase, digits, dash. Max 20 characters. Unique within its collection | -| `buy_ae` | AE to spend on an initial buy at creation. Optional, default `0` | +| `buy_ae` | Target curve cost used to estimate an initial token count. Fees are additional; this is not a strict total-spend cap. Optional, default `0` | On success, one JSON object on stdout: @@ -70,7 +70,7 @@ On success, one JSON object on stdout: "dao_address": "ct_...", "community_management_address": "ct_...", "initial_buy_ae": 0.1, - "estimated_tokens": "131748.00", + "estimated_tokens": "132247.81", "tx_hash": "th_..." } ``` @@ -119,6 +119,9 @@ The check is against `price(initial_buy_count)` on the sale, which **already inc affiliation fee**. The fee comes out of the buffer and the rest is returned, so you spend the real price plus gas. +The numerical estimator can choose a curve cost slightly above or below `buy_ae`. The amount +actually paid also includes the affiliation fee and network charges. + ProtocolDAO tokens are minted on the net amount: the factory mints `(Call.value - overpaid_refund) * 1000`, so you are rewarded on what you spent, not on what you attached. diff --git a/pages/tokens/create-from-dashboard.mdx b/pages/tokens/create-from-dashboard.mdx index 1d69f15..74c1284 100644 --- a/pages/tokens/create-from-dashboard.mdx +++ b/pages/tokens/create-from-dashboard.mdx @@ -45,7 +45,7 @@ from the characters you typed, not chosen up front: 1. Every collection in the factory schema publishes an `allowed_name_chars` rule set. The app turns each into a regular expression and tests your name against all of them. 2. **No collection matches** → a red **Unsupported** badge appears and the submit button is disabled. A name no collection accepts would only fail on-chain, so the UI refuses it first. 3. **Exactly one matches** → a green chip names it, and there is nothing to choose. -4. **More than one matches** → the chip becomes a dropdown. Every collection allows `-`, so a name like `A-B` fits several; English is preferred by default. +4. **More than one matches** → the chip becomes a dropdown. Every collection allows `-`, so a name like `--` fits several; English is preferred by default. The chip shows the human label, not the on-chain id: the `WORDS` collection is displayed as **English**. See [Collections & Naming Rules](/tokens/collections-and-naming) for the full rules. @@ -75,9 +75,10 @@ two ways of expressing the same thing. You type an AE figure; the app tells you how many tokens that buys, solving the curve backwards by bisection from a starting supply of zero. Quick-pick buttons offer 1, 10, 100, 500 and 100,000 AE. -At the launch supply those correspond to: +At the launch supply, the curve-only calculation gives the estimates below. The affiliation +fee and network charges are additional: -| AE spent | Tokens received (approx.) | Average price paid (AE) | Spot price after the buy (AE) | +| Curve cost (AE) | Tokens received (approx.) | Average curve price (AE) | Spot price after the buy (AE) | | --- | --- | --- | --- | | 1 | 437,014 | 2.29e-6 | 4.48e-6 | | 10 | 1,400,993 | 7.14e-6 | 1.42e-5 | @@ -87,22 +88,24 @@ At the launch supply those correspond to: ### Mode 2: Tokens to buy -You type a token count; the app tells you what it costs, labelled *(incl. fees)*: the curve -integral multiplied by 1.005 for the 0.5% affiliation fee. Quick-pick buttons offer 500K, 1M, 5M, +You type a token count; the app tells you what it costs, labelled *(incl. fees)*: a 100-step +trapezoidal estimate of the curve integral, multiplied by 1.005 for the 0.5% affiliation fee. Quick-pick buttons offer 500K, 1M, 5M, 10M and 100M tokens: -| Tokens | Curve cost (AE) | Displayed cost incl. 0.5% fee (AE) | -| --- | --- | --- | -| 500,000 | 1.302086 | 1.308596 | -| 1,000,000 | 5.116708 | 5.142292 | -| 5,000,000 | 127.609638 | 128.247686 | -| 10,000,000 | 518.091808 | 520.682267 | -| 100,000,000 | 71,838.182846 | 72,197.373760 | +| Tokens | Curve cost (AE) | Charged on chain incl. 0.5% fee (AE) | App shows (AE) | +| --- | --- | --- | --- | +| 500,000 | 1.302086 | 1.308596 | 1.31 | +| 1,000,000 | 5.116708 | 5.142292 | 5.14 | +| 5,000,000 | 127.609638 | 128.247686 | 128.25 | +| 10,000,000 | 518.091808 | 520.682267 | 520.68 | +| 100,000,000 | 71,838.182846 | 72,197.373760 | 72,198.81 | The AE-mode estimate is computed from the bare curve and does not subtract the affiliation fee, -while the token-mode estimate adds it, so expect the AE mode to deliver slightly fewer tokens than -it shows. Both estimates are computed from supply zero, which is correct: the token does not exist -yet. The same helpers price the trade card of an existing token, fed the live supply instead. +while the token-mode estimate adds it. Creation submits the estimated token count as +`initial_buy_count` and attaches AE to pay for that count including the fee; it does not reduce +the count to fit the original AE input. The final payment can therefore exceed that input. +Both estimates start from supply zero. The same helpers price the trade card of an existing +token using its live supply. ## What you sign @@ -164,8 +167,8 @@ spot price of `0.0000001 AE`. Anyone, including you, can buy first afterwards. | "Wallet not connected" / no signature prompt | Wallet session dropped | Reconnect and retry | | Nothing on the token page after 5 minutes | Transaction still pending, or it failed | Look up the `txHash` from the URL on [aeScan](https://aescan.io) | -A failed creation costs you gas and nothing else. The whole deployment is one transaction, so no -partial community is left behind. +A creation that is mined and then reverts still costs the transaction fee and consumed gas. +The whole deployment is one transaction, so no partial community is left behind. ## After it is mined diff --git a/pages/tokens/curve-parameters.mdx b/pages/tokens/curve-parameters.mdx index c648566..282a327 100644 --- a/pages/tokens/curve-parameters.mdx +++ b/pages/tokens/curve-parameters.mdx @@ -5,7 +5,7 @@ description: "The constants, decimals and fixed-point conventions you need to co # Curve Parameters & Units -Every integer that crosses the boundary between your code and a Superhero contract is scaled. AE +Monetary amounts passed between your code and Superhero contracts are scaled integers. AE amounts are in aettos (10^18 to the AE), token counts are in the token's own decimal units (also 10^18), and the curve formula is written in *whole* tokens and *whole* AE. Mixing those three conventions is how implementations end up off by a factor of 10^18. @@ -39,8 +39,8 @@ The scaling rule: for a curve `f(x) = α·e^(β·x) − γ`, the constants are ` `calculate_price` requires `count >= minimum_count` and aborts with `MINIMUM_TOKENS_REQUIRED` otherwise. `minimum_count` is `10^12` token decimal units (`10^12 / 10^18 = 10^-6` tokens, one -millionth of a token), so it only guards against a trade rounding to zero inside the integer -arithmetic. In practice it fires when you pass a **whole-token** count where the contract expects +millionth of a token). It is a hard minimum on every buy, sell and quote, so a balance below it +cannot be sold. In practice it fires when you pass a **whole-token** count where the contract expects decimal units: sending `5` instead of `5000000000000000000` aborts with `MINIMUM_TOKENS_REQUIRED` rather than silently buying five attotokens. @@ -56,7 +56,7 @@ code, or read `sell_return()` on the sale contract instead of reconstructing the | --- | --- | --- | --- | | AE amount | aettos, an integer | AE, a decimal | divide by 10^18 | | Token count | token decimal units, an integer | whole tokens, a decimal | divide by 10^(decimals) | -| Curve value | `Frac.frac` rational, or an integer of aettos | AE per token | see below | +| Curve value | `Frac.frac` rational from `buy_curve`/`sell_curve`; `buy_price`/`sell_price` round it up/down to an integer | AE per token | see below | `1 AE = 10^18 aettos`. The æternity SDK exposes this as `AE_AMOUNT_FORMATS.AETTOS` / `AE_AMOUNT_FORMATS.AE` and the helpers `toAe()` and `formatAmount()`. Do the division with @@ -80,8 +80,8 @@ the factory creates: `create_community` passes `decimals = 18` to the sale, and Read the value from one of those entrypoints rather than hardcoding 18. `GET /api/tokens/{address}` also returns `decimals` (as a string) alongside `total_supply`. -`total_supply` from the API is already in token decimal units. Divide it by 10^18 before feeding it -to the curve. +`total_supply` from the API is already in token base units. Pass it unchanged to the contract's +curve entrypoints. Divide it by 10^18 only when using the idealised formula expressed in whole tokens. ## What each entrypoint expects @@ -213,14 +213,15 @@ Three properties matter if you are reimplementing this: to `0` under integer division. In the supply range these tokens trade in, the second bound always fires first; the terms collapse long before the hundredth. 2. **`mc2` starts at the quadratic term.** It returns `scale · (e^z − 1 − z)` rather than - `scale · e^z`, where `z = k·supply / 10^18` is the curve exponent. The missing linear term is + `scale · e^z`, where `z = k·supply / 10^36` for supply in token base units. The missing linear term is what the `(initial_price * count) / decimals` summand restores; that is where the `−0.0009999` offset of the closed form comes from. -3. **Every division floors, and the order is load-bearing.** `(term * x) / (i * scale)` divides once, - after both multiplications. Splitting it into `term * x / i / scale` or pre-scaling `x` changes - the truncation and the answers drift apart. +3. **Integer truncation matters.** Preserve the multiplication before division in + `(term * x) / (i * scale)`. Pre-scaling `x` can discard precision. For non-negative + integers, dividing the product successively by `i` and `scale` gives the same floor as + dividing by their product. -`sell_price` is not a separate curve evaluation: `calculate_sell_return(supply, n)` is +`calculate_sell_return` is not a separate curve evaluation: `calculate_sell_return(supply, n)` is `calculate_price(supply − n, n) × 9950 / 10000`, floored. ## Reference implementation: exact @@ -322,8 +323,8 @@ buyPriceAettos(10_000_000, 1000).toFixed(0); // "105276443948657760" vs 10527644 ``` The residual, a couple of hundred aettos on each, is double rounding, not a difference in the -model: the contract's truncated Taylor series tracks the closed form to within `4e-19 AE` across -this range. A double has about 15–16 significant digits in total while an aettos figure needs 18, +model: the contract's integer result is the closed form rounded down, under 1 aetto below it for +whole-token counts. A double has about 15–16 significant digits in total while an aettos figure needs 18, so **no floating-point implementation can be exact at the aettos level.** Use these for estimates and the contract's own return value for anything you sign. @@ -345,7 +346,7 @@ Because the curve is convex, the trapezoidal rule always *overestimates* slightl | Trade | Exact (AE) | Trapezoidal, n = 100 (AE) | Error | | --- | --- | --- | --- | -| 1,000 tokens from supply 0 | 0.000105000 | 0.000105000 | +0.03 ppm | +| 1,000 tokens from supply 0 | 0.000105000 | 0.000105000 | +0.00000794 ppm | | 1,000,000 tokens from supply 0 | 5.116708417 | 5.116709254 | +0.16 ppm | | 10,000,000 tokens from supply 0 | 518.091807565 | 518.092683989 | +1.69 ppm | | 100,000,000 tokens from supply 0 | 71,838.182845904 | 71,839.614745042 | +19.9 ppm | diff --git a/pages/tokens/fees-and-slippage.mdx b/pages/tokens/fees-and-slippage.mdx index 1b18cff..6572218 100644 --- a/pages/tokens/fees-and-slippage.mdx +++ b/pages/tokens/fees-and-slippage.mdx @@ -7,8 +7,9 @@ description: "Everything between the price you see and the price you get: the 1% Three different things move the number. The **curve spread** is a fixed 1% of the curve value, split between the community DAO and the affiliation system. **Curve slippage** is the cost of your -own trade size, and depends on how big it is relative to the supply. **Gas** is the æternity network -fee, and the smallest of the three by a wide margin. +own trade size, and depends on how big it is relative to the supply. **Network charges** include +the transaction fee and gas used by contract execution. Their size relative to trading costs +depends on the trade amount, gas consumption and network conditions. ## 1. The spread @@ -71,16 +72,18 @@ transaction. The only cost of a generous buffer is that the AE has to be in your ### Where each AE goes +Before integer rounding, the continuous-model allocation is: + ```text -Buyer pays AE - ├── 99.0% → Bonding Curve Reserve (redeemable by sellers) - ├── 0.5% → Community DAO Treasury (governed by token holders) - └── 0.5% → Affiliation System +Buyer pays 1.005 × B AE, where B is the curve integral in AE + ├── 0.995 × B → Bonding Curve Reserve (redeemable by sellers) + ├── 0.005 × B → Community DAO Treasury (governed by token holders) + └── 0.005 × B → Affiliation System ├── 0.300% → Level 1 Referrer ├── 0.125% → Level 2 Referrer ├── 0.050% → Level 3 Referrer └── 0.025% → Level 4 Referrer - (if no referrer: burned) + (percentages are of B; uncredited shares stay in the treasury) Buyer also receives: └── ProtocolDAO Tokens = 1,000 × AE value @@ -90,7 +93,7 @@ The four-level split is credited per level as the treasury walks up the affiliat `AffiliationTreasury.record_sale_transaction(buyer, transaction_value)` credits `300`, then `125`, then `50`, then `25` hundred-thousandths of the transaction value to successive inviters, and stops as soon as an account has no inviter recorded. Levels with no inviter are not paid out; that share -is burned. +remains uncredited in the affiliation treasury contract. It is not transferred to a burn address. Credited rewards are withdrawable for the current and the previous 30-day payout period (`payout_period_interval = 2592000000` milliseconds) and expire after that. `withdraw()` also @@ -115,11 +118,11 @@ state.dao_contract.record_sale_transaction( Call.caller, total_price) ``` -`total_supply()` has already been incremented by the mint, so `reserve` is exactly -`0.995 × bonding_curve_price`, the AE that would be owed if the buyer immediately sold back. The -DAO gets `bonding_curve_price − reserve`, the remaining `0.5%`, and the sale contract keeps the -reserve. The payout obligation is computed first and the treasury receives only what is left over, -which is why the reserve is always solvent. +`total_supply()` has already been incremented by the mint, so `reserve` is the exact integer +quote for immediately selling that same count, approximately `0.995 × bonding_curve_price`. +The DAO gets `bonding_curve_price − reserve`, approximately `0.5%`, and the sale contract keeps +the reserve. This funds sellers in the continuous model; integer rounding needs separate +analysis. See [Reserve accounting and rounding](/concepts/value-flow#reserve-accounting-and-rounding). Both external calls use `protected = true`, so a failing DAO or treasury call cannot block a trade; the value stays in the sale contract instead of reverting the buy. @@ -164,9 +167,10 @@ Buying from a supply of 10,000,000, where spot is `1.052709e-4 AE`: Rule of thumb: **your premium to spot is roughly half the percentage of the supply you are adding**, up to about 10%, and worse than that beyond it. -Splitting the order does not help. The curve is path-independent: ten buys of 1,000,000 from a -rising supply cost exactly the same total as one buy of 10,000,000, because the integral is the same -area either way. The only levers are trade size and the supply you trade at. +In the continuous model, splitting the order does not reduce price impact. Ten consecutive buys +of 1,000,000 cover the same integral as one buy of 10,000,000 with the same starting supply and +no intervening trades. Integer rounding can change exact totals, and each transaction pays its +own network fee. Near supply zero the effect is far larger in relative terms, because the `−0.0009999` offset has cancelled almost all of the exponential: buying the first 1,000 tokens of a brand-new token costs @@ -203,12 +207,12 @@ Every transaction pays an æternity network fee in AE, independent of everything | --- | --- | --- | | Create a token | 1 contract call | About 0.001 AE | | Buy | 1 contract call | Depends on contract execution | -| Sell | 2 contract calls: allowance, then sell | Depends on contract execution | +| Sell through the web app | 2 contract calls: allowance, then sell | Depends on contract execution | | Post | 1 contract call | Depends on contract execution | -Read the exact fee off any mined transaction in [aeScan](https://aescan.io). Two things hold -regardless: a **sell costs two transactions**, not one, because of the allowance step; and the web -app never lets you spend your whole balance. Its "spendable" figure is +Read the exact fee off any mined transaction in [aeScan](https://aescan.io). The web app uses +two transactions for a sell, including its allowance step. A direct sell can use a sufficient +existing allowance without another approval transaction. The web app's "spendable" figure is `balance − balance × (slippage + 1) / 100 − 0.001 AE`, so at the default 1% tolerance it holds back 2% of your balance plus a flat 0.001 AE for the fee. @@ -222,7 +226,7 @@ For a buy of `n` tokens at supply `S`: AE leaving your wallet = ∫ from S to S+n of buy(x) dx ← the curve, including your own slippage × 1.005 ← the affiliation fee; together, this is price(n) - + network gas + + network transaction fee and execution gas ( any buffer you attached above price(n) is refunded in the same transaction ) ``` @@ -231,8 +235,8 @@ And for the matching sell later, at whatever supply `S'` prevails then: ```text AE returning to your wallet = ∫ from S'−n to S' of buy(x) dx - × 0.995 ← the sell factor, i.e. the DAO's cut - − network gas + × 0.995 ← the sell factor; the DAO allocation was funded on buys + − network transaction fee and execution gas ( reverts entirely if below minimal_return_required ) ``` diff --git a/pages/tokens/index.mdx b/pages/tokens/index.mdx index f38cb14..6e87cc8 100644 --- a/pages/tokens/index.mdx +++ b/pages/tokens/index.mdx @@ -5,14 +5,15 @@ description: "Community tokens, the exponential bonding curve that prices them, # Tokens & Bonding Curves -Anyone can turn a topic into a market. Type a name, and a few seconds later that idea has a token, -a price, a chart and a treasury, with no listing, approval or market maker involved. +You can create a community token by choosing a name and submitting a deployment transaction. +Once it is mined, the token has a bonding-curve price and a DAO treasury. The price comes from a curve rather than an order book. Every buy mints new tokens and nudges the -price up; every sell burns them and moves it back down. So there is always a price, always -liquidity, and no counterparty to find: you are trading with the contract itself, which holds -enough reserve to buy the entire supply back. Because the price is a function of supply, tokens bought -before the supply grows cost less. +price up; every sell burns them and moves it back down. You trade with the contract itself, +which computes quotes from supply and retains AE from buys to pay sellers. See +[Reserve accounting and rounding](/concepts/value-flow#reserve-accounting-and-rounding) for the +continuous-model redemption argument and its implementation limits. Tokens bought before the +supply grows cost less. ## The numbers to remember @@ -23,11 +24,11 @@ before the supply grows cost less. | Price of a trade | The integral of the curve across the supply you mint into or burn out of | | Launch price | 0.0000001 AE per token, at supply 0 | | Spread | 1% of the curve value: 0.5% to the community DAO, 0.5% to affiliation | -| Instant round trip | Returns 0.99502 of what you paid, before gas | -| Affiliation split | 0.300% / 0.125% / 0.050% / 0.025% across four referral levels; burned if unreferred | +| Instant round trip | Returns about 0.99005 of what you paid, before gas | +| Affiliation split | 0.300% / 0.125% / 0.050% / 0.025% of curve value across four referral levels; uncredited shares stay in the affiliation treasury | | ProtocolDAO reward | Minted to the buyer on every buy, proportional to its AE value | | Token standard | AEX-9, 18 decimals | -| Solvency | The sell curve is strictly below the buy curve at every supply, so the reserve always covers the full supply | +| Reserve design | Buys retain the immediate sell quote; full redemption follows in the continuous model, subject to integer-rounding analysis | ## Where to start diff --git a/pages/tokens/overview.mdx b/pages/tokens/overview.mdx index d5dd12c..2257b4f 100644 --- a/pages/tokens/overview.mdx +++ b/pages/tokens/overview.mdx @@ -5,8 +5,9 @@ description: "What a community token is, which contracts it deploys, and what ow # Community Tokens -A Superhero community token is an AEX-9 fungible token whose entire supply is minted and burned -against a bonding curve, with a DAO treasury attached. Creating one deploys a small cluster of +A Superhero community token is an AEX-9 fungible token minted through bonding-curve buys and +redeemed through sells, with a DAO treasury attached. Holders can also burn their own tokens +directly without receiving AE. Creating one deploys a small cluster of contracts in a single transaction; holding one gives you a governance stake and a write threshold in that community, not a claim on a company. @@ -18,7 +19,7 @@ that community, not a claim on a company. | Pricing | Exponential bonding curve, a pure function of supply | | Buy/sell spread | 1% of the curve value: 0.5% to the community DAO, 0.5% to affiliation | | Utility | Community governance voting, write-access threshold, community membership | -| Solvency | The full supply is redeemable at all times against the curve reserve | +| Reserve design | Buys retain the immediate sell quote; full redemption follows in the continuous model, subject to integer-rounding analysis | | Supply cap | None. Supply is elastic and grows with demand | ## What gets deployed @@ -28,13 +29,13 @@ order: | Step | Contract | Role | | --- | --- | --- | -| 1 | `FungibleTokenFull` | The AEX-9 token itself: balances, transfers, allowances | -| 2 | `BondingCurveExponential` | Pricing. Pure arithmetic, no state of its own | +| 1 | `CommunityManagement` | Moderators, mute list, write threshold, community metadata | +| 2 | `DAO` | Owner and beneficiary of the sale; holds the treasury | | 3 | `AffiliationBondingCurveTokenSale` | Buy, sell, mint, burn, affiliation fee routing | -| 4 | `DAO` | Owner and beneficiary of the sale; holds the treasury | -| 5 | `CommunityManagement` | Moderators, mute list, write threshold, community metadata | -| 6 | None | Registration in the factory's on-chain community registry | -| 7 | None | Optional initial token purchase, in the same transaction | +| 4 | `FungibleTokenFull` | Created inside the sale's `init`: balances, transfers, allowances | +| 5 | None | Link the DAO, sale and management contracts | +| 6 | None | Optional initial token purchase, in the same transaction | +| 7 | None | Registration in the factory's on-chain community registry | `create_community` returns the tuple `(DAO, TokenSale, CommunityManagement)`. The bonding curve contract is shared: the factory exposes a single `bonding_curve()` and every sale contract points @@ -60,8 +61,8 @@ own address, so an allowance is granted to `sale_address` with its `ct_` prefix ## What holding the token gets you - **Governance.** Holders at or above the community's `minimum_token_threshold` can open DAO votes; any holder can vote, with voting weight equal to the tokens they lock in the vote contract. Opening a vote costs 555 AE, paid to the DAO. See [DAO voting](/dao/voting). -- **A treasury you collectively control.** 0.5% of the curve value on every trade accrues to the community's DAO, and holders vote on how it is spent. See [Treasury](/dao/treasury). -- **Write access and membership.** `CommunityManagement` stores a `minimum_token_threshold` that gates write access in the community for verified accounts, plus the moderator set and mute list. See [Moderators](/dao/moderators). +- **A treasury you collectively control.** Approximately 0.5% of the curve value on each buy is allocated to the community's DAO, and holders vote on how it is spent. Sells make no new DAO allocation. See [Treasury](/dao/treasury). +- **Write access and membership.** `CommunityManagement` stores a `minimum_token_threshold` that gates entry to the community's token-gated chat room (and opening DAO votes), plus the moderator set and mute list. See [Moderators](/dao/moderators). - **ProtocolDAO tokens.** Buying a community token also mints you platform-wide ProtocolDAO tokens, proportional to the AE value of the buy. Their governance framework is not yet live. See [ProtocolDAO](/dao/protocol-dao). ## What it is not @@ -69,8 +70,8 @@ own address, so an allowance is granted to `sale_address` with its `ct_` prefix - **Not equity.** A community token conveys no ownership of any company, no share of profits, and no claim on anyone's assets other than the AE in its own bonding-curve reserve. - **Not a revenue share.** The DAO treasury is spent by vote, not distributed automatically. There is no dividend. - **Not a fixed-supply asset.** Anyone can mint more at any time by buying. Your percentage of the supply falls whenever someone else buys, even if your balance does not change. -- **Not backed by a promise.** The only guarantee is arithmetic: the curve always quotes a sell price, and the reserve can always pay it. Whether that price is higher or lower than what you paid depends on what everyone else does. -- **Not free to enter and exit.** The 1% spread means an instant round trip returns about 0.995 of what you put in, before gas. See [Risks](/tokens/risks). +- **Not backed by a promise.** The curve computes a sell quote from supply, and buys fund the reserve. The continuous-model redemption argument needs a separate check for integer rounding. Whether the quote is higher or lower than what you paid depends on what everyone else does. See [Reserve accounting and rounding](/concepts/value-flow#reserve-accounting-and-rounding). +- **Not free to enter and exit.** Before gas and integer rounding, an instant round trip with no intervening trades returns `0.995 / 1.005`, about `0.99004975` of what you paid. See [Risks](/tokens/risks). ## Two token types on the platform diff --git a/pages/tokens/portfolio.mdx b/pages/tokens/portfolio.mdx index c69185c..9bca347 100644 --- a/pages/tokens/portfolio.mdx +++ b/pages/tokens/portfolio.mdx @@ -36,7 +36,7 @@ token record. | `token_address` | `aex9_address` or `token.address` | The AEX-9 contract, for allowances and transfers | | `balance` | `balance` | Tokens held | | `buy_price_ae` | `token.price` | Current spot **buy** price, per token | -| `sell_price_ae` | `token.sell_price` | Current spot **sell** price, per token, 0.5% below buy | +| `sell_price_ae` | `token.sell_price` | Current spot **sell** price, per token, about 1% below buy (≈0.995 / 1.005) | | `trending_score` | `token.trending_score` | Momentum signal for that token | Value a position at `sell_price_ae`, never at `buy_price_ae`. The buy price is what the next person diff --git a/pages/tokens/risks.mdx b/pages/tokens/risks.mdx index c534ab4..6f73d3c 100644 --- a/pages/tokens/risks.mdx +++ b/pages/tokens/risks.mdx @@ -14,7 +14,7 @@ Nothing here is financial advice. Never risk funds you cannot afford to lose. ## 1. Every position starts about 1% down You buy at the curve price plus a 0.5% affiliation fee. You can only sell at 0.995 times the curve -price. An instant round trip at unchanged supply therefore returns `0.995 / 1.005 = 0.99502` of what +price. An instant round trip at unchanged supply therefore returns `0.995 / 1.005 = 0.99004975…` of what you paid: ```text @@ -28,12 +28,12 @@ sell them straight back loss 0.001052764439 AE = 0.995% of what you paid ``` -Before gas. **The price has to rise about 1% before you are level**, which on this curve means the -supply must grow by roughly the same 1%: somebody else has to buy about as much as you did for you -to break even. +Before gas. **Your sell return must increase by about 1.005% to recover the purchase cost.** +The additional supply needed depends on your entry supply and position size; a 1% price +increase does not imply a 1% supply increase on this curve. For a trader doing many round trips this compounds: ten round trips at unchanged prices leave you -with `0.99502^10 = 0.951` of your capital, a 4.9% loss from friction alone. Frequent trading on a 1% +with `(0.995 / 1.005)^10 ≈ 0.90484` of your capital, a 9.52% loss from friction alone. Frequent trading on a 1% spread loses unless each move is substantially larger than 1%. ## 2. The exit price is not the quoted price @@ -53,8 +53,9 @@ exit.** Call `sell_return(balance)` on the sale contract for the exact number be a position's value. See [Portfolio & PnL](/tokens/portfolio). The same logic makes large entries expensive: adding 10% to a token's supply costs about 5% above -the price you were quoted, and doubling the supply costs about 54% above it. Splitting the order does -not help, because the curve is path-independent. See [Fees & Slippage](/tokens/fees-and-slippage). +the price you were quoted, and doubling the supply costs about 54% above it. Splitting the order +does not reduce this price impact in the continuous model. Integer rounding and per-transaction +network fees can change exact totals. See [Fees & Slippage](/tokens/fees-and-slippage). ## 3. Reflexivity @@ -74,7 +75,7 @@ further up the curve than the people the signal is reporting on. See Most community tokens are small. The specific dangers in a thin one: - **A single holder can be the market.** If one address holds 50% of the supply, their exit walks the price down through every other holder's position first. Check the Holders tab before you buy. -- **The creator's entry was much cheaper than yours.** A pre-buy at creation happens at the very bottom of the curve: the first 437,014 tokens cost exactly 1 AE, while the same 437,014 tokens bought at a supply of 10,000,000 cost 47.06 AE, 47 times more. An early holder can be far ahead while a later one is underwater. +- **The creator's entry was much cheaper than yours.** A pre-buy at creation happens at the bottom of the curve: the first 437,014 tokens have a curve cost of about 1 AE, while the same amount bought at a supply of 10,000,000 has a curve cost of about 47.06 AE. Both purchases also pay the affiliation fee and network charges. An early holder can be ahead while a later one is underwater. - **Low holder count with high supply is one person's position with a price attached**, not a community. - **Dilution.** Supply is unlimited and minted on demand. Your balance does not change when other people buy, but your share of the supply, and therefore your governance weight, falls. @@ -84,11 +85,12 @@ Nothing about a community token expires. If everybody loses interest, the contra prices and the curve keeps working, but: - There is no one to trade against except the curve, and no activity to move it. -- Whatever the DAO treasury accumulated stays there. Opening a DAO vote costs **555 AE** paid by the proposer, so a treasury worth less than 555 AE is effectively unspendable: nobody will rationally pay more to propose a payout than the payout is worth. See [DAO voting](/dao/voting). +- Whatever the DAO treasury accumulated stays there. Opening a DAO vote costs **555 AE**, paid into the same treasury. A passing `VotePayout` pays out the whole balance, deposit included, so a small treasury is still spendable; the proposer risks the 555 AE only if the vote fails or is not applied in time. See [DAO voting](/dao/voting). - Governance requires a quorum of 10% of the token stake and 55% approval within two weeks. In an abandoned community that quorum may be unreachable, which freezes the treasury, the moderator set and the write threshold as they are. -You can always sell back to the curve (solvency is guaranteed), but you will be selling into whatever -supply remains, at whatever price the last trades left behind. +The curve computes your sell quote from the remaining supply, at the price the last trades left +behind. Buys fund the reserve, but the continuous-model redemption argument needs separate +integer-rounding analysis. See [Reserve accounting and rounding](/concepts/value-flow#reserve-accounting-and-rounding). ## 6. Mechanism risk @@ -97,15 +99,17 @@ supply remains, at whatever price the last trades left behind. | Slippage between quote and fill | Other trades land before yours. Guarded by your slippage tolerance on a buy and by `minimal_return_required` on a sell. Both revert rather than fill badly, and a revert still costs gas | | A sell with no floor | `minimal_return_required` of 0 means "fill me at any price". On a falling curve that is exactly wrong | | Standing allowances | Selling requires granting the sale contract an AEX-9 allowance. Leaving a large one in place authorises that contract to move that many tokens until you reduce it | -| Two-step sells | A sell is two transactions. If the second fails, you have granted an allowance and still hold the tokens | +| Two-step sells | In the app and CLI a sell is two transactions. If the second fails, you have granted an allowance and still hold the tokens | | Front-running | Anyone watching the mempool can place a buy ahead of yours, pushing you further up the curve. Your tolerance bounds the damage; it does not prevent it | ## 7. Smart contract risk -The contracts are written in Sophia, a functional language with strong static typing and no mutable -global state, which narrows the surface for reentrancy and state-corruption bugs. The economic design -is solvent by construction: the sell curve sits strictly below the buy curve at every supply, so the -reserve can always redeem the entire supply. The contracts have not undergone a third-party audit. +The contracts are written in Sophia, a functional language with strong static typing and +contract-local mutable state. FATE rejects reentrant calls into an executing contract. The sale contract +retains the immediate sell quote on each buy, which funds full redemption in the ideal continuous +model. Integer truncation requires a separate check for exact solvency across trade sequences; +the continuous argument alone does not establish it for deployed contracts. The contracts have +not undergone a third-party audit. See [Contract security](/contracts/security). - **Bugs in the sale, curve, DAO or factory contracts.** These are immutable once deployed. A `ChangeDAO` vote can migrate a community's DAO, but the token and sale contracts are fixed. diff --git a/pages/tokens/token-page.mdx b/pages/tokens/token-page.mdx index d0e70d3..20b229f 100644 --- a/pages/tokens/token-page.mdx +++ b/pages/tokens/token-page.mdx @@ -29,15 +29,15 @@ Every field in the token summary is a hard fact rather than an interpretation: | --- | --- | | Price | Current spot **buy** price, one token, in AE | | Market cap | See below. Displayed in AE, convertible to fiat | -| DAO balance | AE accumulated in the community treasury from the spread | +| DAO balance | The DAO contract's current AE balance: about 0.5% of every buy, plus 555 AE per proposal and any donations, minus executed payouts | | Total supply | Tokens currently in circulation. Minted by buys, burned by sells | | Creation date | When the community was deployed | | Contract address | The AEX-9 token contract | | Sale address | The bonding-curve sale contract, the handle for all trading | | Created by | The account that called `create_community` | -The API record behind it carries more than the panel shows: `sell_price` (the spot sell price, 0.5% -under `price`), `circulating_supply`, `rank`, `holders_count`, `tx_count`, `trending_score`, +The API record behind it carries more than the panel shows: `sell_price` (the spot sell price, about 1% +under `price`, because `price` includes the 0.5% affiliation fee), `circulating_supply`, `rank`, `holders_count`, `tx_count`, `trending_score`, `trending_score_update_at`, `unlisted`, and a `performance` object with `past_24h`, `past_7d`, `past_30d` and `all_time` sub-objects. See [Tokens API](/api-reference/tokens). @@ -62,9 +62,9 @@ They come from different places and can legitimately disagree: the case on a new token or when the middleware is behind. The two converge; use `total_supply` for anything that has to be right, including the 10% DAO participation quorum. -**DAO balance is the most under-read number on the page.** It is cumulative spread, so it measures -how much value has actually traded through the token since launch. It is much harder to fake than a -price, and not resettable by a single large buy. +**DAO balance is the most under-read number on the page.** It is the treasury today, not a volume +meter: every buy adds about 0.5%, but proposal deposits and donations also raise it, and a passing +payout drains it. Use the Transactions tab to judge volume. ## Market cap, precisely @@ -84,26 +84,31 @@ Two details of that definition: - **The unit price includes the 0.5% affiliation fee.** `TokenSale.price(count)` is the curve integral plus the fee, so `market_cap` is 0.5% above a pure curve valuation. - **It is a marginal price, priced for one token.** It is the cost of the *next* token, applied to every token already minted. -So it is a rectangle, while the AE in the reserve is the area under the curve: +For comparison, the buy-curve spot valuation is a rectangle, while the curve cost and modeled +redemption value are integrals. The following continuous-model examples omit affiliation fees +and integer rounding: ```text market cap = buy(S) × S ← a rectangle: today's price, every token -reserve paid = ∫ from 0 to S of buy(x) dx ← the area under the curve -redeemable = 0.995 × that same integral ← what selling everything would return +curve cost = ∫ from 0 to S of buy(x) dx ← the area under the curve +redemption = 0.995 × that same integral ← full-supply return in the continuous model ``` On a rising convex curve the rectangle is always bigger than the area: -| Total supply | Market cap (AE) | AE ever paid in (AE) | Redeemable if everyone sold (AE) | Market cap overstates by | +| Total supply | Spot valuation before affiliation (AE) | Curve cost from zero (AE) | Modeled full-supply redemption (AE) | Spot valuation overstates by | | --- | --- | --- | --- | --- | | 10,000,000 | 1,052.71 | 518.09 | 515.50 | 2.04× | -| 100,000,000 | 171,838.20 | 71,838.18 | 71,478.99 | 2.40× | +| 100,000,000 | 171,838.18 | 71,838.18 | 71,478.99 | 2.40× | -A token showing a 1,000 AE market cap is backed by roughly 500 AE of reserve, and the gap widens as -the curve steepens. Unlike most assets, the reserve is a number you can check on-chain. +A token showing a 1,000 AE market cap has roughly 500 AE of reserve in this model, and the gap +widens as the curve steepens. Check the actual balance on-chain; the continuous comparison does +not establish exact solvency across integer trades. See +[Reserve accounting and rounding](/concepts/value-flow#reserve-accounting-and-rounding). -**Market cap is a ranking signal, not a valuation.** The trending list defaults to sorting by it so -that larger communities surface first, and for that job it is fine. Do not read it as money that +**Market cap is a ranking signal, not a valuation.** The token list can sort by it (**Market Cap**; the +default is **Trending**), and search results sort by it by default, so larger communities surface +first. For that job it is fine. Do not read it as money that exists. ## The chart @@ -170,7 +175,8 @@ transactions script or the API. See [Transaction History](/tokens/transactions). Before buying, in the order the page makes them available: -1. **DAO balance**: has real volume ever passed through this token? +1. **DAO balance** and **Transactions**: what does the treasury hold, and has real volume passed + through this token? 2. **Holders**: how concentrated is it, and how cheap was the top holder's entry? 3. **Transactions**: distinct accounts, or one address round-tripping? 4. **Feed**: is there a community here, or just a ticker? diff --git a/pages/wallets/aex9-tokens.mdx b/pages/wallets/aex9-tokens.mdx index 072e3f4..e9b2bf0 100644 --- a/pages/wallets/aex9-tokens.mdx +++ b/pages/wallets/aex9-tokens.mdx @@ -12,17 +12,18 @@ Every Superhero community token is an AEX-9 fungible token, the æternity equiva | Entrypoint | Arguments | What it does | | --- | --- | --- | | `meta_info` | none | Name, symbol, decimals | -| `total_supply` | none | Total minted supply | +| `total_supply` | none | Outstanding supply, after burns | | `balance` | `address` | One account's balance, as an option | | `balances` | none | The whole balance map | | `transfer` | `address, int` | Move your own tokens | -| `allowance` | `from_account, for_account` | Read a granted allowance | +| `allowance` | one record: `from_account`, `for_account` | Read a granted allowance | | `allowance_for_caller` | `address` | Read the allowance granted to the caller | | `create_allowance` | `address, int` | Grant a new allowance | | `change_allowance` | `address, int` | Adjust an existing one by a delta | -| `reset_allowance` | `address` | Revoke it entirely | +| `reset_allowance` | `address` | Set an existing allowance to zero, retaining its record | | `transfer_allowance` | `from, to, int` | Spend someone else's allowance | -| `mint` / `burn` | `address, int` / `int` | Supply changes, owner-gated | +| `mint` | `address, int` | Owner-only issuance to an account | +| `burn` | `int` | Destroy tokens from the caller's own balance, without an AE payout | Amounts everywhere are integers in the token's **base units**. Divide by 10 to the power of `decimals` from `meta_info` to get a human figure. Superhero's signing prompt does *not* do that @@ -87,7 +88,13 @@ indexed balance or a DEX listing. Anything else falls back to a name-prefix sear ## Allowances An allowance grants a specific contract permission to move up to a stated number of *your* -tokens. Superhero relies on this in two places. +tokens. Superhero relies on this in three places. + +### Selling to the bonding curve + +A sell pulls your tokens through an allowance for the token's sale contract (again the `ct_` +address re-encoded as `ak_`). The app grants or adjusts it just before the sell, which is why a +sell asks for two signatures. ### DEX swaps @@ -104,15 +111,17 @@ is in fact granted to the router contract. ### DAO vote locking -Governance votes lock the tokens you vote with until the vote closes, and that locking is -implemented with the AEX-9 allowance mechanism, which is what prevents the same tokens being -double-spent across two concurrent votes. Revoking your vote releases the lock. +Community DAO votes transfer the tokens you stake into the vote contract using an AEX-9 +allowance. Holding those tokens in the vote contract prevents the same balance from being +transferred, sold or staked in another proposal. An allowance alone does not lock tokens. +While the vote is open, revoking it returns the stake; after it closes, call `withdraw()`. This is why a vote can ask you to sign twice: once to grant or adjust the allowance, once to cast. ### Revoking an allowance -superhero.com grants allowances just-in-time before a swap or an add-liquidity and does not +superhero.com grants allowances just-in-time before a sell, a swap, an add-liquidity or a DAO +vote, and does not provide a screen to review or revoke them. Revoke per token with a direct contract call: ```text @@ -121,7 +130,8 @@ reset_allowance(for_account) on the AEX-9 token contract where `for_account` is the grantee in `ak_` form. For the DEX, that is the router's contract address with `ct_` swapped for `ak_`. Use the agent skill's SDK setup, `aepp-cli`, or any tool that can call a -contract entrypoint. +contract entrypoint. Resetting retains the allowance record with value zero, so a later grant +uses `change_allowance` rather than `create_allowance`. Every allowance Superhero grants is sized to the specific trade, so a stale allowance is capped at whatever was left over from the operation that created it. That is usually zero, because a swap spends diff --git a/pages/wallets/backup-and-recovery.mdx b/pages/wallets/backup-and-recovery.mdx index 329e3db..ebbd912 100644 --- a/pages/wallets/backup-and-recovery.mdx +++ b/pages/wallets/backup-and-recovery.mdx @@ -17,7 +17,7 @@ you personally kept. | A Ledger or AirGap account inside Superhero Wallet | The device's own recovery words | Wherever that device's maker tells you | | An account imported into Superhero Wallet by private key | That private key | Offline; the seed phrase will not restore it | | Built-in wallet created **from a phrase** | The 12 words, plus the recovery code | Offline; the code is not a substitute for the words | -| Built-in wallet created **from a passkey** | Confirm your passkey **syncs**; keep the recovery code | Sync is the backup; the code only helps on this device | +| Built-in wallet created **from a passkey** | Save the optional 12-word phrase backup; confirm your passkey syncs if you rely on it across devices | Keep the phrase offline; this path does not enroll a recovery code | | An agent key (`AE_PRIVATE_KEY`) | The secret key string | Offline, never in git, never in a log | ## Back up a seed phrase @@ -25,9 +25,10 @@ you personally kept. 1. **Write it down by hand.** Screenshots and text files end up in cloud sync and disk indexes. 2. **Copy it exactly**: all 12 or 24 words, in order, lowercase. BIP39 phrases carry a checksum, so a wrong or transposed word is usually caught on import. -3. **Verify it.** Superhero's built-in wallet makes you re-enter the words before a vault is - created. In the standalone Superhero Wallet the step is **optional and comes later** (see - below). +3. **Verify it.** The built-in phrase-creation flow asks you to re-enter two words before creating + the vault, but allows you to skip, and does not offer the check again later. Passkey + creation instead offers an optional phrase backup after creation. In the standalone Superhero + Wallet the step is **optional and comes later** (see below). 4. **Store two copies in different physical places.** 5. **Never type it into anything but the wallet.** No support agent, no "validator", no airdrop checker will ever need it. See [Security Best Practices](/wallets/security). @@ -64,7 +65,8 @@ It exports **one account**, not the wallet. Use it to move a single account into that supports private-key import. An account you *imported* by private key cannot be restored with your seed phrase, only with that private key, so such accounts need their own backup. -The built-in wallet offers no export of any kind. +The built-in wallet does not offer this single-account private-key export. Its passkey +create/restore flow offers a backup of the full recovery phrase instead. ### Change the wallet password @@ -74,7 +76,8 @@ sets the auto-lock interval: immediately, 1, 5, 15 or 30 minutes of inactivity. ## Back up the built-in wallet -The built-in wallet has three unlock factors and they are **not interchangeable as backups**: +The built-in wallet supports three unlock factors and they are **not interchangeable as backups**. +The table assumes the factor is enrolled; passkey creation does not enroll a recovery code. | Factor | Unlocks on this device | Restores on a new device | | --- | --- | --- | @@ -92,10 +95,13 @@ phrase and, for a wallet created by the passkey path, the passkey itself, becaus - **Phrase-created built-in wallet**: the 12 words are your only portable backup. The recovery code is a same-device fallback for a forgotten passphrase or a broken passkey. Keep both. -- **Passkey-created built-in wallet**: the passkey *is* the backup, but only if it syncs. Confirm - it landed in iCloud Keychain or Google Password Manager. There is no phrase reveal or export - screen, so a device-bound credential like Windows Hello leaves **no other copy of the seed**. - Still enroll the recovery code: it is the only factor that survives a passkey rekey. +- **Passkey-created built-in wallet**: save the optional 12-word phrase backup offered after + creation or passkey restore. Press **Reveal** to write it down. Copy and download options are + also available, but the download is an unencrypted text file, so keep it offline. The phrase + restores the wallet without the passkey, including after passkey + loss or rekeying. If you rely on the passkey across devices, confirm it landed in iCloud + Keychain or Google Password Manager. A device-bound credential like Windows Hello cannot leave + its device. This creation path does not enroll a recovery code. ## Recover on a new device @@ -118,7 +124,9 @@ before anything is stored, then sealed under a new passphrase on the new device. ### Built-in wallet, from a passkey -Choose **"Restore a wallet you created with a passkey."** This runs a discoverable WebAuthn +Tap the **Passkey** card and **cancel** the prompt to create a new passkey (approving it creates a +new, empty wallet). On the screen that follows, choose **"Restore a wallet you created with a +passkey."** This runs a discoverable WebAuthn assertion, derives the wallet the credential implies, and **shows you the derived address before saving anything.** The confirm screen also checks that address for on-chain activity: @@ -129,6 +137,9 @@ saving anything.** The confirm screen also checks that address for on-chain acti - **"Couldn't check on-chain activity"**: the node was unreachable. Advisory only; judge by the address itself. +After confirmation, the app offers the optional recovery phrase backup again. You can also import +a phrase saved from passkey creation into Superhero Wallet without the passkey. + ### An agent key There is no derivation to redo. The secret key is the account: @@ -144,23 +155,26 @@ node scripts/superhero-wallet.mjs balance - **A lost seed phrase with no other factor.** Nobody can reconstruct it. Not Superhero, not æternity, not the wallet developers. - **A built-in wallet whose vault was deleted**, if your only factors were a passphrase and a - recovery code. Clearing site data for superhero.com deletes the IndexedDB vault; Safari's - Intelligent Tracking Prevention can evict it after about seven days of no interaction. Neither - the passphrase nor the code opens anything afterwards. -- **A passkey-created wallet whose device-bound passkey is gone**, if the credential never synced. + recovery code. Deleting the browser storage containing the IndexedDB vault removes it. In a + Safari tab, ITP can also remove it after seven days of Safari use without site interaction; + first-party Home Screen web-app storage is exempt from that rule. Neither the passphrase nor + the code opens anything after the vault is gone. +- **A passkey-created wallet whose device-bound passkey is gone**, if the credential never synced + and you did not save its recovery phrase. - **Funds sent to a wrong address.** Transactions are final. - **A private key that was logged, pasted into a chat, or committed to git.** Treat it as compromised from that moment and move the funds to a fresh account. One common loss that *is* recoverable: the built-in wallet's address list, living in local storage. -If that is cleared while the encrypted vault survives, unlock once and the app re-derives your -addresses from index 0 upward. +If that is cleared while the encrypted vault survives, unlock once and the app rebuilds it (the +built-in wallet has one account, at index 0). ## A backup routine that holds - Write the phrase down and read it back **before** funding the account. - Store two copies in two places. -- Store the recovery code separately from the phrase. They fail in different ways, so hide them in different places. +- If your wallet has a recovery code, store it separately from the phrase. They fail in different + ways, so hide them in different places. - If you rely on a passkey, verify it is present on a *second* device before you trust it as a backup. - Do a restore drill once: import into a second wallet and confirm the first address matches. @@ -169,10 +183,11 @@ addresses from index 0 upward. There is no passphrase-change flow in the built-in wallet, and no way to remove a factor. -- **To change your passphrase, recreate the wallet.** Unlock with any enrolled factor, write down - the recovery phrase, erase the wallet, and create a new one with the same phrase and a new - passphrase. You get a new recovery code; the account and its address are unchanged, because they - come from the seed. +- **To change your passphrase, recreate the wallet in the installed app.** First verify the + recovery phrase you saved at setup. Then open the installed app (Add to Home Screen), erase the + wallet there if it has one, and import that same phrase with a new passphrase. A browser tab + offers no import, so do not erase the wallet from a tab. You get a new recovery code; the + account and its address are unchanged, because they come from the seed. - **A compromised factor cannot be revoked.** Any one factor opens the vault, so a passphrase someone has seen stays valid until the wallet is recreated. Recreate it the same day. diff --git a/pages/wallets/built-in-wallet.mdx b/pages/wallets/built-in-wallet.mdx index 716828c..12d2f71 100644 --- a/pages/wallets/built-in-wallet.mdx +++ b/pages/wallets/built-in-wallet.mdx @@ -17,15 +17,15 @@ standalone extension and mobile app, though both hold the same kind of `ak_...` | Surface | Create a wallet | Import an existing seed | In-page signing | | --- | --- | --- | --- | | Installed PWA (Add to Home Screen) | Yes | Yes | Yes | -| Plain browser tab | Yes | No, use Connect instead | Not installed as the signer | +| Plain browser tab | Yes | No, use Connect instead | Yes, for this browser's wallet | -Creating a wallet (passkey or a fresh recovery phrase) is offered on every surface. Pasting a seed -phrase or private key is offered **only in the installed app**: in a browser tab, "I already have a +Creating a wallet (passkey or a fresh recovery phrase) is offered on every surface. Importing a seed +phrase is offered **only in the installed app**: in a browser tab, "I already have a wallet" means Connect, which hands signing to the extension or the wallet app and never asks for -your secret. +your secret. The built-in import form does not accept a raw private key. -The in-page signer is installed only when the app is running installed *and* the active address -belongs to this device's wallet. An externally connected wallet is never intercepted. +The in-page signer is used when the active address belongs to this browser's wallet, in a browser +tab or the installed app. An externally connected wallet is never intercepted. ## How the key is stored @@ -67,7 +67,8 @@ The passphrase is scored locally with zxcvbn, with no network call. The rules: fallback to a length rule. The passphrase cannot be changed after creation. To change it, recreate the wallet from the -recovery phrase. See [Backup & Recovery](/wallets/backup-and-recovery). +recovery phrase in the installed app, the only place that offers import. See +[Backup & Recovery](/wallets/backup-and-recovery). ### Recovery code @@ -87,39 +88,47 @@ If the first ceremony returns no PRF output, the app runs a follow-up assertion is why you may see two prompts. The Relying Party ID is pinned at build time from `VITE_WEBAUTHN_RP_ID`, defaults to -`superhero.com`, and is never derived from the page's own host. A bundle served from another host -cannot use your Superhero passkey. When that value does not match the origin, the passkey option -fails with no OS prompt at all. See [Troubleshooting](/wallets/troubleshooting). +`superhero.com`, and is never derived from the page's own host. WebAuthn permits that RP ID on +`superhero.com` and its HTTPS subdomains; it does not isolate credentials to one exact hostname. +An unrelated domain cannot use it. An RP ID must equal the origin's hostname or be a registrable +domain suffix of it, or the browser rejects the ceremony. See +[Troubleshooting](/wallets/troubleshooting) and the [WebAuthn RP-ID rules](https://www.w3.org/TR/webauthn-3/#relying-party-identifier). ## Two ways a wallet is created ### From a recovery phrase -A 12-word BIP39 phrase is generated, shown, and **verified by re-entry** before any vault exists. -Then a passphrase factor creates the vault. The recovery code is enrolled next and is mandatory. A -device passkey is offered after that and is optional. +A 12-word BIP39 phrase is generated and shown, followed by a request to re-enter two words to +confirm the backup. You can skip confirmation; in that case the wallet records that the backup +has not been verified. A passphrase factor then creates the vault. An optional device passkey is +offered next, followed by mandatory recovery-code enrollment. Import follows the same path minus the show/verify screens. The phrase is normalized (trimmed, whitespace collapsed, lowercased) and checked against the BIP39 wordlist **and checksum** before a -vault is created, so a typo cannot seal a wrong seed. +vault is created. Invalid mnemonics are rejected; a valid phrase can still belong to a different +wallet, so check the resulting address. ### From a passkey -One ceremony does everything. The passkey is enrolled, and the BIP39 mnemonic is **derived from its -PRF output** at a fixed, public salt, so there is no phrase screen. The seed derivation and the -key that wraps the DEK use separate derivations, so neither can be computed from the other. +The passkey is enrolled, and the BIP39 mnemonic is **derived from its PRF output** at a fixed, +public salt. The app then offers an optional **12-word recovery phrase backup**, hidden until you +press **Reveal**, with copy and download options; the download is an unencrypted text file with +the address and phrase. This path does not enroll a recovery code. The +seed derivation and the key that wraps the DEK use separate derivations, so neither can be computed +from the other. The salt is fixed rather than random so that the seed can be re-derived on any device the passkey -reaches, even after the vault is gone. That makes the passkey a real backup **only if it syncs** -(iCloud Keychain, Google Password Manager). A device-bound platform credential such as Windows -Hello dies with its device, and **there is no phrase reveal or export screen in the app**, so for -those users the passkey is the only copy. +reaches, even after the vault is gone. A syncing passkey (iCloud Keychain, Google Password Manager) +can therefore restore the wallet on another device. A device-bound credential such as Windows +Hello cannot. The saved recovery phrase is a portable backup in either case and restores the wallet +independently of the passkey. If you skip that backup, losing the passkey can mean losing access. **Restoring on a new device** runs a discoverable assertion, derives the wallet the credential implies, and shows you the derived address **before persisting anything**. The confirm screen also -checks whether that address has on-chain activity: a pristine account is a warning that you picked -the wrong passkey, because a phrase-created wallet's device passkey evaluated at the seed salt -derives a valid but empty different wallet. +checks whether that address has on-chain activity: a pristine account can warn that you picked +the wrong passkey. A phrase-created wallet's device passkey evaluated at the seed salt can +derive a different wallet. Check the displayed address. After confirmation, the same optional phrase-backup +screen appears, without recovery-code enrollment. ## Key derivation @@ -197,9 +206,13 @@ Once the vault record is gone: - Your **passkey** still exists in your authenticator, but for a *phrase-created* wallet it only wrapped a DEK that is now gone, so it opens nothing either. -The same loss happens without you touching anything: IndexedDB is evictable, and Safari's -Intelligent Tracking Prevention can evict it after roughly seven days without interaction. A -successful save is **never** a durable backup. +Browser storage can also be evicted. In a Safari tab, Intelligent Tracking Prevention can remove +script-writable storage after seven days of Safari use without interaction with the site. +First-party Home Screen web-app storage is exempt from that ITP rule. See +[WebKit's storage policy](https://webkit.org/tracking-prevention/#intelligent-tracking-prevention-itp). +The exemption does not replace a recovery backup or prevent deliberate data deletion. On iOS, a +Home Screen web app also keeps its storage separate from Safari, so a wallet created in a Safari +tab is not in the installed app until you import its phrase or restore it with its passkey there. What survives a wiped vault: @@ -207,16 +220,17 @@ What survives a wiped vault: | --- | --- | --- | | The written 12/24-word phrase | **Yes** | Standard BIP39 on the standard path, so it re-imports anywhere. | | A **syncing** passkey on a passkey-created wallet | **Yes** | The seed re-derives from the PRF output at the fixed public salt. | -| A device-bound passkey (e.g. Windows Hello) on a passkey-created wallet | Only on that device | It cannot leave the device, and there is no export screen. | +| A device-bound passkey (e.g. Windows Hello) on a passkey-created wallet | Only on that device | The credential stays on that device; a saved phrase is the portable backup. | | A passkey on a **phrase-created** wallet | No | It wraps a DEK; it does not derive the seed. | | The recovery code alone | No | It unwraps a DEK; it does not derive the seed. | | The passphrase alone | No | Same. | Losing only `localStorage` is survivable: unlock once and the app rebuilds the manifest by -re-deriving addresses from index 0 upward. +re-deriving the wallet's single account, at index 0. -Erasing the wallet deliberately is available from the "this device already has a wallet" screen, -and takes two taps because for a passkey wallet it is unrecoverable. +Erasing the wallet deliberately is available from the "this device already has a wallet" screen +and takes two taps. Before erasing, keep a recovery phrase backup or a working passkey that derives +this wallet's seed. ## Related diff --git a/pages/wallets/choosing-a-wallet.mdx b/pages/wallets/choosing-a-wallet.mdx index 6e54b51..8e0ff22 100644 --- a/pages/wallets/choosing-a-wallet.mdx +++ b/pages/wallets/choosing-a-wallet.mdx @@ -12,10 +12,11 @@ what gets you back in. Pick by surface and by recovery model. All of them hold t ## Recommended: passkey -For most people, start with a **passkey**. On superhero.com, tap "Continue with passkey" and -approve with Face ID, a fingerprint or your device PIN. That creates your account: no seed phrase -to write down, nothing to install. Make sure your passkey syncs (iCloud Keychain, Google Password -Manager or a password manager), because on a passkey-created wallet the passkey is your backup. +For most people, start with a **passkey**. On superhero.com, tap the **Passkey** card and +approve with Face ID, a fingerprint or your device PIN. That creates your account with nothing to +install, then offers an optional 12-word phrase backup. Save the phrase offline so you can restore +without the passkey. If you rely on the passkey across devices, make sure it syncs (iCloud Keychain, +Google Password Manager or a password manager). See [The Built-In Wallet](/wallets/built-in-wallet). ## Comparison @@ -24,11 +25,11 @@ See [The Built-In Wallet](/wallets/built-in-wallet). | --- | --- | --- | --- | --- | --- | | Product | Superhero Wallet | Superhero Wallet | Superhero Wallet, at `wallet.superhero.com` | Superhero app itself | Your own process | | Custody | Yours, in the extension | Yours, on the device | Yours, in a hosted page | Yours, in this browser's storage | Yours, in an env var | -| Platforms | Chrome, Brave, Opera, Firefox | iOS, Android | Any browser | Any browser; in-page signing in the installed PWA | Anywhere Node runs | +| Platforms | Chrome, Brave, Opera, Firefox | iOS, Android | Any browser | Browser tab or installed PWA; passkeys require browser/authenticator support | Anywhere Node runs | | Install needed | Yes | Yes | No | No | No | -| Unlocks with | Wallet password | Device biometrics, if enabled | Wallet password | Passkey, passphrase or recovery code | Nothing; the key is live | +| Unlocks with | Wallet password | Device biometrics, if enabled | Wallet password | Passkey (passkey-created); passphrase or recovery code, plus an optional device passkey (phrase-created/imported) | Nothing; the key is live | | Change the unlock secret later | Yes | Biometrics on or off | Yes | **No** | n/a | -| Portable backup | Seed phrase | Seed phrase | Seed phrase | Seed phrase, or a syncing passkey | The secret key | +| Portable backup | Seed phrase | Seed phrase | Seed phrase | Seed phrase, or a syncing passkey (passkey-created wallets) | The secret key | | Export one account's private key | Yes | Yes | Yes | **No** | It *is* the key | | Ledger (æternity app) | Chromium only | No | Yes | No | No | | AirGap cold signing | Yes | Yes | Yes | No | No | @@ -84,15 +85,15 @@ over AEX-2 instead; see [Connecting a Wallet](/wallets/connecting). ### First time, on a phone -Use a **passkey** (recommended): tap "Continue with passkey", approve with Face ID or a -fingerprint, and you have an account. Make sure your passkey syncs. On a passkey-created wallet -the passkey *is* your backup, and there is no phrase export screen. If you prefer a seed phrase, -install the **Superhero Wallet mobile app**. +Use a **passkey** (recommended): tap the **Passkey** card, approve with Face ID or a +fingerprint, and you have an account. Save the optional recovery phrase offered next; it restores +the wallet without the passkey. Make sure your passkey syncs if you rely on it across devices. +For a standalone wallet with a seed phrase, install the **Superhero Wallet mobile app**. ### First time, on a desktop -Install the **browser extension**. A desktop browser tab does not install the in-page signer, so -desktop signing needs it. The extension also gives you the multi-chain wallet, an address book and +Use a **passkey** for the built-in wallet, which signs in a desktop browser tab as well as the +installed app. Or install the **browser extension** for a multi-chain wallet, an address book and `.chain` name management in one place. ### Trading actively and holding real value @@ -135,17 +136,18 @@ superhero.com connects to it. In a browser tab the built-in wallet does not offe | --- | --- | | Extension, mobile, web wallet | The seed phrase or, for one account at a time, that account's exported private key. | | Built-in wallet from a phrase | The seed phrase. Its passphrase and recovery code are **same-device only**. | -| Built-in wallet from a passkey | The passkey, **only if it syncs**. The recovery code is same-device only. | +| Built-in wallet from a passkey | The saved recovery phrase, or the passkey if it syncs. This path does not enroll a recovery code. | | Raw agent key | The secret key string. | | A Ledger or AirGap account held in Superhero Wallet | The device's own recovery words. The Superhero Wallet seed phrase does **not** restore it, because the wallet only stores its public address. | The same applies to an account you imported by pasting a private key: it cannot be restored with the seed phrase, only with that private key. -The built-in wallet's storage is evictable in a way an installed wallet's is not: clearing site data -deletes the encrypted vault, and Safari's tracking prevention can evict it after about seven days -of no interaction. That is survivable with a written phrase or a syncing passkey and fatal without -either. [Backup & Recovery](/wallets/backup-and-recovery) has the full matrix. +The built-in wallet depends on this browser's storage. Deleting the storage containing its vault +removes the encrypted seed. In a Safari tab, ITP can remove script-writable storage after seven +days of Safari use without site interaction; first-party Home Screen web-app storage is exempt +from that rule. Keep a written recovery phrase, or a working passkey that derives this wallet's +seed. [Backup & Recovery](/wallets/backup-and-recovery) has the full matrix. ## You can use more than one diff --git a/pages/wallets/connecting.mdx b/pages/wallets/connecting.mdx index 82531ee..9a5e8f9 100644 --- a/pages/wallets/connecting.mdx +++ b/pages/wallets/connecting.mdx @@ -5,8 +5,9 @@ description: "How superhero.com discovers your wallet, what the connection grant # Connecting a Wallet -superhero.com never holds your keys. To act on your behalf it finds a wallet, opens an RPC session -with it, and sends every transaction there for you to approve. +With an external wallet, superhero.com requests signatures without receiving your keys. Its +built-in wallet instead stores an encrypted seed in this browser and signs in-page after you +approve. The connection path determines where each request goes. ## The three connection paths @@ -14,7 +15,7 @@ with it, and sends every transaction there for you to approve. | --- | --- | --- | | Browser extension | In-page message connection, discovered by the SDK's wallet detector | Desktop browsers with Superhero Wallet installed | | Wallet app or web wallet | Deep link with a callback URL | Mobile, or desktop when no extension answers | -| Built-in wallet | No transport; the signer runs in the page | Installed PWA with an on-device vault | +| Built-in wallet | No transport; the signer runs in the page | Browser tab or installed PWA with this browser's vault | The first two are external custody: the wallet holds the key and Superhero only ever receives a signed result. The third is documented in [The Built-In Wallet](/wallets/built-in-wallet). diff --git a/pages/wallets/index.mdx b/pages/wallets/index.mdx index 8dc2331..545a4c1 100644 --- a/pages/wallets/index.mdx +++ b/pages/wallets/index.mdx @@ -5,8 +5,9 @@ description: "Install, secure, connect and recover an æternity wallet for Super # Wallets -Superhero never holds your keys. Everything you do that touches the chain (posting, tipping, -trading, voting) is a transaction signed by a wallet you control. +Superhero's servers never receive your keys. Everything you do that touches the chain (posting, +tipping, trading, voting) is a transaction signed by a wallet you control: one you install, or the +built-in wallet, which keeps your key encrypted on your device. Two different things are called "a wallet" on Superhero: diff --git a/pages/wallets/security.mdx b/pages/wallets/security.mdx index 65455ec..1633204 100644 --- a/pages/wallets/security.mdx +++ b/pages/wallets/security.mdx @@ -45,16 +45,17 @@ The attack that empties accounts is not a broken cipher; it is a convincing page - **Check the URL before the connect prompt, not after.** A wallet prompt tells you *what* is being signed, not *who* asked. - On the built-in wallet there is one extra signal: passkeys are pinned to a single Relying Party - ID baked into the build. A clone on another domain cannot use your Superhero passkey; the - ceremony fails before it starts. That is a side effect of the design, not a substitute for - checking the URL. + ID baked into the build. An unrelated domain cannot use your Superhero passkey. The default + `superhero.com` RP ID is also valid on its HTTPS subdomains, so it is not an exact-host boundary. + Check the URL even when a passkey prompt appears. ## Approvals and allowances AEX-9 tokens use an allowance mechanism: you grant another contract permission to move a specific -amount of your tokens. Superhero uses it in two places: **DEX swaps** of non-AE tokens, and -**vote locking** in DAO governance, where the allowance stops the same tokens being double-spent -across concurrent votes. +amount of your tokens. Superhero uses allowances for bonding-curve sells, DEX token swaps and +liquidity operations, and DAO voting. A vote contract uses the allowance to transfer your stake +into its custody; holding those tokens there prevents their use in concurrent votes. Granting an +allowance alone does not lock tokens. - **Read the amount in the prompt.** The built-in wallet names these calls explicitly: "Lets another account spend your tokens up to this amount" for `create_allowance`, "Increases or @@ -81,8 +82,10 @@ loop. That is a different threat model from a browser wallet. - **Cap the balance.** Fund it with what you are willing to lose to a bug or a bad prompt, and top it up deliberately. There is no spending limit enforced anywhere in the stack. The balance *is* the limit. -- **Keep the key out of the process list and the shell history.** `export` in a shell, or a - secrets manager; never an argument on a command line, never a file in the repository. +- **Keep the key off command lines and out of shell history.** Load it with + `read -rs AE_PRIVATE_KEY; export AE_PRIVATE_KEY`, from a secrets manager, or from an untracked + env file; a typed `export AE_PRIVATE_KEY=...` lands in shell history. Never pass it as a + command-line argument, and never commit it to the repository. - **Never echo it.** A key printed once is a key in a CI log forever. - **Separate agent identity from personal identity.** An agent that posts, trades and claims a `.chain` name under its own address keeps your main account out of whatever it does. @@ -94,9 +97,11 @@ loop. That is a different threat model from a browser wallet. - **Transactions are final.** There is no reversal and no chargeback. - **Gas is charged on top of the fee**, up to the gas limit, which is why a good prompt shows both a network fee and a "gas, at most" figure. A failed contract call still costs gas. -- **A bonding-curve trade carries a 1% spread** between buy and sell price, split 0.5% to the - community DAO and 0.5% to the affiliation system. That is a structural cost, not a fee you can - avoid by timing. +- **Bonding-curve trades have a structural cost.** At the documented parameters, a buy pays the + curve cost plus a 0.5% affiliation fee, and allocates 0.5% of the curve cost to the DAO. Sells + use a 99.5% return factor and create no new DAO allocation. An immediate ideal-model round + trip returns `0.995 / 1.005`, about 99.005% of the payment before gas and integer rounding. + See [Fees & Slippage](/tokens/fees-and-slippage). - **Community tokens are not equity and carry no promise.** Read [Token Risks](/tokens/risks). Double-check addresses and amounts before signing. Never risk funds you cannot afford to lose. @@ -107,7 +112,7 @@ For the built-in wallet, storage is part of your security model: - The encrypted vault lives in this browser's IndexedDB for this origin. **Clearing site data deletes it**, and your passphrase and recovery code cannot bring it back. Only the written - phrase or a syncing passkey can. + phrase can or, for a wallet created with a passkey, that passkey if it syncs. - The vault's confidentiality equals its **weakest enrolled factor**, because any one factor opens it. A strong passphrase does not compensate for a weak one enrolled alongside. - Choose a real passphrase. The app enforces a zxcvbn score of at least 3, rejects numeric-only diff --git a/pages/wallets/superhero-wallet-mobile.mdx b/pages/wallets/superhero-wallet-mobile.mdx index 638a5f8..f88749e 100644 --- a/pages/wallets/superhero-wallet-mobile.mdx +++ b/pages/wallets/superhero-wallet-mobile.mdx @@ -21,19 +21,23 @@ one wallet across several chains, install the second and connect it. ## Install Superhero as a PWA Superhero is also installable straight from the browser. The installed app gets a home-screen icon, -a full-screen experience, an integrated wallet and push notifications. +a full-screen window, recovery-phrase import, the token chat entry points and, on iOS, Web Push. ### iOS -**Safari only.** Chrome and Firefox on iOS cannot install a PWA. +The steps below use Safari. Since iOS and iPadOS 16.4, supported third-party browsers can also +offer **Add to Home Screen** through the Share menu. A site configured as a web app opens in its +own app window; a plain website shortcut may open in the default browser. See +[WebKit's explanation](https://webkit.org/blog/13878/) and [Chrome's iOS instructions](https://support.google.com/chrome/answer/9658361?co=GENIE.Platform%3DiOS&hl=en). 1. Open [superhero.com](https://superhero.com) in Safari. -2. Open the page menu: the **⋯** menu in the top right, or the **Share** button on older iOS - versions. -3. Scroll and tap **Add to Home Screen**. -4. Tap **Add** in the top right. The icon appears on your home screen. -5. **Launch it from the home-screen icon**, not from Safari. The extra capabilities only exist in - standalone mode. +2. Tap **•••** next to the address bar, then **Share** (on older iOS versions, the **Share** + button in the toolbar). +3. Tap **View More** if you see it, then **Add to Home Screen**. +4. On iOS 26, leave **Open as Web App** on. +5. Tap **Add**. The icon appears on your home screen. +6. **Launch it from the home-screen icon** to use the installed app's features, including phrase + import and Home Screen Web Push on supported iOS versions. ### Android @@ -50,32 +54,35 @@ On desktop, the same install is available from the install button in your browse | Behaviour | Browser tab | Installed app | | --- | --- | --- | | Create a built-in wallet (passkey or new phrase) | Yes | Yes | -| **Import** an existing seed phrase or private key | No, Connect instead | **Yes** | -| In-page signing by the built-in wallet | Not installed as the signer | **Yes** | +| **Import** an existing seed phrase | No, Connect instead | **Yes** | +| In-page signing by the built-in wallet | **Yes**, for this browser's wallet | **Yes** | | Token community chat entry points | Hidden | **Shown** | -| Location sharing on iOS | Not available | Available | -| Push notifications | No | Yes | +| Push notifications | If the browser supports Web Push; unavailable in an ordinary iOS tab | Supported browsers, including iOS/iPadOS 16.4+ Home Screen web apps | In a browser tab the answer to "I already have a wallet" is Connect, which hands signing to the extension or the wallet app through a redirect and never asks for your secret. A redirect out of an -installed app does not come back cleanly, which is why the installed app takes the key directly. +installed app does not come back cleanly, which is why it offers recovery-phrase import. The +built-in import form does not accept a raw private key. ## The built-in wallet on mobile Tapping **Connect** in the installed app offers a passkey option first. On a phone that means Face ID, Touch ID, a fingerprint or your device PIN, and it creates a real æternity account in one -ceremony. There is no seed-phrase screen, because the seed is *derived* from the passkey rather than stored -beside it. +ceremony. The seed is *derived* from the passkey, and the next screen offers an optional +**12-word recovery phrase backup**, hidden until you press **Reveal**, with copy and download +options (the download is an unencrypted text file). Save it offline: it restores the wallet even without the passkey. This path does not +enroll a recovery code. -**That is a backup only if the passkey syncs** (iCloud Keychain, Google Password Manager). There is -no phrase reveal or export screen in the app. Enroll the recovery code the flow offers you, and -read [The Built-In Wallet](/wallets/built-in-wallet) for what each factor does and does not -survive. +If you rely on the passkey across devices, confirm it syncs (iCloud Keychain, Google Password +Manager). A device-bound credential cannot leave its device. Read +[The Built-In Wallet](/wallets/built-in-wallet) for what each factor does and does not survive. ## Push notifications Push is standard Web Push (VAPID), opt-in, and enabled from a control in the app. The permission -prompt requires a tap, so it never appears on load. +prompt requires a tap, so it never appears on load. Installation is not an application-level +requirement: supported ordinary browsers can subscribe. On iOS and iPadOS, Web Push requires a +Home Screen web app and version 16.4 or later. - **Exactly one permission is requested**: the browser's notification permission. No location, no contacts, no background-refresh grant. Subscriptions are `userVisibleOnly`, so the browser will @@ -119,6 +126,6 @@ app through the transaction queue route, described in [Connecting a Wallet](/wal - [The Built-In Wallet](/wallets/built-in-wallet): what the "wallet built in" is, and where its keys live. - [Connecting a Wallet](/wallets/connecting): the deep-link path mobile uses instead of extension detection. - [Choosing a Wallet](/wallets/choosing-a-wallet): built-in versus standalone, decided by recovery model. -- [Backup & Recovery](/wallets/backup-and-recovery): especially the passkey-sync rule. +- [Backup & Recovery](/wallets/backup-and-recovery): the phrase backup and passkey-sync limits. - [Web Wallet](/wallets/web-wallet): what an installed PWA of `wallet.superhero.com` can and cannot do. - [Superhero Wallet on the æternity docs hub](https://docs.aeternity.com/aeternity-user-tools-and-services/superhero-wallet): the standalone wallet's documentation. diff --git a/pages/wallets/troubleshooting.mdx b/pages/wallets/troubleshooting.mdx index 9d40453..d914383 100644 --- a/pages/wallets/troubleshooting.mdx +++ b/pages/wallets/troubleshooting.mdx @@ -13,15 +13,16 @@ Find your symptom, read the cause, apply the fix. The WebAuthn Relying Party ID for wallet passkeys is pinned into the build from `VITE_WEBAUTHN_RP_ID` and is never derived from the host serving the page. If that pinned value is -not a registrable domain suffix of the origin you are on, the browser rejects the ceremony with a +neither the origin's hostname nor a registrable domain suffix of it, the browser rejects the ceremony with a `SecurityError` **before the operating system shows anything**. No Face ID sheet, no Touch ID prompt, no Windows Hello dialog, no error dialog. | Where you are | Correct `VITE_WEBAUTHN_RP_ID` | Passkeys work? | | --- | --- | --- | | `superhero.com` (production) | `superhero.com`, the default | Yes | +| An HTTPS subdomain of `superhero.com` | `superhero.com` is also valid | Yes, with browser/authenticator support | | Local dev on `localhost` | `localhost` | Yes, if set | -| Any other origin | A registrable suffix of that origin | Only if set for that build | +| An unrelated origin | Its hostname or a registrable suffix | Requires a compatible RP ID for that build | **Fix:** on production, report it. On any other origin, rebuild with the right `VITE_WEBAUTHN_RP_ID`, or use a recovery phrase instead. @@ -38,11 +39,13 @@ common causes: - **You picked the wrong passkey** from the OS list. Retry and choose the Superhero one. - **The credential was rekeyed by the platform.** Apple has a known passkey-rekey issue that can - invalidate a previously stable PRF output. This is why the recovery code exists as a - passkey-independent factor. + invalidate a previously stable PRF output. A saved recovery phrase remains independent of it. -**Fix:** unlock with your **recovery code** or **passphrase** instead, on the same device. Both are -offered on the "this device already has a wallet" screen. +**Fix:** on a phrase-created wallet, unlock with your **recovery code** or **passphrase** instead, +on the same device. A passkey-created wallet does not enroll these fallbacks during creation: +restore from the recovery phrase you saved at its optional backup screen (import is offered only +in the installed app; Superhero Wallet also accepts the phrase). Without that phrase or a working +passkey, access may be lost. ### Tapping the passkey card opens an onboarding screen instead of a biometric prompt @@ -190,9 +193,13 @@ address and index pair drifted apart. ### My built-in wallet disappeared -The encrypted vault lives in this browser's IndexedDB for this origin. Clearing site data deletes -it, and Safari's Intelligent Tracking Prevention can evict it after roughly seven days without -interaction. +The encrypted vault lives in this browser's IndexedDB for this origin. Deleting the storage +containing that vault removes it. In a Safari tab, Intelligent Tracking Prevention can remove +script-writable storage after seven days of Safari use without interaction with the site. +First-party Home Screen web-app storage is exempt from that ITP rule; see +[WebKit's policy](https://webkit.org/tracking-prevention/#intelligent-tracking-prevention-itp). +On iOS, the installed Home Screen app also has storage separate from Safari: a wallet created in +a Safari tab does not appear there until you import its phrase or restore it with its passkey. **Neither your passphrase nor your recovery code can bring it back**, because both need the deleted record to unwrap anything. What survives is the written recovery phrase, or a **syncing** passkey @@ -204,7 +211,7 @@ if the wallet was created by the passkey path. The full matrix is in The address list in `localStorage` was cleared while the encrypted vault in IndexedDB survived. This is a normal outcome of some "clear site data" variants. -**Fix:** open the wallet screen and unlock once; addresses are re-derived from index 0 upward and +**Fix:** open the wallet screen and unlock once; the account at index 0 is re-derived and the list is rebuilt. ### Restoring from a passkey shows an address I do not recognise @@ -219,9 +226,9 @@ import with "a vault already exists". ### There is no "Import an existing wallet" option -Importing a seed phrase or private key is offered **only in the installed app** (Add to Home +Importing a seed phrase is offered **only in the installed app** (Add to Home Screen / installed PWA). In a plain browser tab, "I already have a wallet" means Connect, which -never asks for your secret. +never asks for your secret. The built-in import form does not accept a raw private key. ### Nothing persists at all (private browsing) diff --git a/pages/wallets/web-wallet.mdx b/pages/wallets/web-wallet.mdx index 2857e1f..d0c4246 100644 --- a/pages/wallets/web-wallet.mdx +++ b/pages/wallets/web-wallet.mdx @@ -43,7 +43,7 @@ bnb, avalanche, polygonPos and dogecoin. In particular you can: address. - Sign transactions requested by superhero.com. - **Claim additional `.chain` names**, bid in name auctions, set pointers and transfer names. - Superhero sponsors one free name claim per address; further names are claimed here or in any + Superhero can sponsor one name claim per address; further names are claimed here or in any other Superhero Wallet surface. - **Import a Ledger's æternity accounts** over WebUSB, and sign with the device. - **Pair an AirGap Vault** and sign offline. diff --git a/scripts/lint-mdx.py b/scripts/lint-mdx.py index d3c9ec8..4b02280 100644 --- a/scripts/lint-mdx.py +++ b/scripts/lint-mdx.py @@ -50,7 +50,7 @@ def mdx_files(): def route_of(path): - r = path[len(PAGES):] + r = "/" + os.path.relpath(path, PAGES).replace(os.sep, "/") r = r[: -len(".mdx")] if r.endswith("/index"): r = r[: -len("/index")] @@ -125,7 +125,8 @@ def check_meta(report): continue meta_path = os.path.join(root, "_meta.json") try: - meta = json.load(open(meta_path)) + with open(meta_path, encoding="utf-8") as source: + meta = json.load(source) except Exception as exc: # noqa: BLE001 report(meta_path, 1, "META", f"invalid JSON: {exc}") continue @@ -157,7 +158,8 @@ def report(path, lineno, kind, message): routes.add(route_of(path)) for path in files: - text = open(path).read() + with open(path, encoding="utf-8") as source: + text = source.read() lines = text.split("\n") check_frontmatter(path, lines, report) check_body(path, lines, report)