DOCS / REFERENCE / CONTRACTS ARCHITECTURE
Contracts architecture
COPIED FROM chimpdao-contracts/docs/ARCHITECTURE.md · REVISION 6fd752349933
·
Repository ↗
Chimp binds Stellar state to a physical NFC chip whose private key never leaves silicon.
Every contract that checks a chip signature links the same
chimpdao-chip-auth rlib.
Card A ───┐ Chimp account = the account (durable root)
Card B ───┤ · a flat set of signers, cards and passkeys as peers; any one signs (1-of-n)
Passkey ──┘ · a card is its 65-byte SEC1 key; a passkey is its P-256 key + credential id
· its own token (SEP-50, id 0), and its own upgrade policy
Card A ───┐
Card B ───┤──> Pocket purse (per card, salt = sha256(pubkey))
│ the card's float and its DeFi positions
│ chip-authorized only; no recovery path
└──> card NFT (one per physical card, owned by that card's purse)
Adding or replacing a signer is add_card / remove_card / add_passkey / remove_passkey
on the account and never changes the account address or its holdings. An account may hold only
cards, only passkeys, or both; neither kind is a backup of the other. The purse is keyed by chip
pubkey because it is per card: it travels with the card, so a loaded card can be given away with
no unwind. A passkey never authorizes a purse.
There is no rule, policy or signer-id layer. A signer is in its set or it is not.
Signing details: AUTH.md.
Crates
| Path | Package | Role |
|---|---|---|
contracts/chip-auth/ |
chimpdao-chip-auth |
Shared digest + WebAuthn verify + fleet-code helpers (rlib, not deployed) |
contracts/collection/ |
collection |
Deploy nfc-nft + cross-collection ownership index |
contracts/nfc-nft/ |
nfc-nft |
SEP-50-shaped NFT; one chip-gated mint provisions token + purse. No transfer: tokens are soulbound to the purse |
contracts/account/ |
chimpdao-account |
The Chimp account — cards and passkeys are the signers; Manual/Managed upgrade policy; a read-only SEP-50 surface for its own token |
contracts/pocket-factory/ |
chimpdao-pocket-factory |
Deploy Pocket (salt = sha256(pubkey)); the fleet record: Pocket and account wasm heads, their histories and an epoch |
contracts/pocket/ |
chimpdao-pocket |
Pocket — per-card purse; CustomAccountInterface |
contracts/router/ |
chimpdao-router |
Atomic multi-call: batch(caller, calls) anchors one auth tree (caller.require_auth()), so a position move or card handover across several contracts is all-or-nothing. Stateless, adminless, no upgrade path |
examples/prize/ |
prize |
Example vault app, not core protocol |
No OpenZeppelin (stellar-accounts and stellar-contract-utils are absent from Cargo.toml
and Cargo.lock) and no verifier contracts: verification is linked, not delegated
(AUTH.md).
Dependency graph
flowchart TB
subgraph shared [Shared rlib, linked not deployed]
ChipAuth[chimpdao-chip-auth]
end
subgraph central [Central, admin-run]
Collection[collection]
Factory[pocket-factory]
NfcNft[nfc-nft]
end
subgraph holder [Per card]
Account[account]
Pocket[pocket]
end
Router[router]
Prize["prize (example)"]
NfcNft ==>|verifies with| ChipAuth
Pocket ==>|verifies with| ChipAuth
Account ==>|verifies with| ChipAuth
Factory -.->|types only| ChipAuth
Prize -.->|call_digest only| ChipAuth
Account -.->|"account_wasm_hash (update, apply)"| Factory
Collection -->|deploys| NfcNft
NfcNft -->|assign_collectible| Collection
NfcNft -->|create_account, get_account| Factory
Factory -->|"deploys (Managed: ref to fleet entry, Manual: wasm hash)"| Pocket
Prize -->|verify_for_card, owner_of| NfcNft
Router -.->|"invokes as caller"| Pocket
Router -.->|"invokes as caller"| Account
Thick edges verify a chip signature with chimpdao-chip-auth. Dotted edges into it do not:
pocket-factory links it for the shared Curve and UpgradePolicy types and the fleet’s tag
names, prize for call_digest. The account also verifies a passkey’s WebAuthn assertion inline,
through the same crate (verify_webauthn), with the same host primitive (secp256r1_verify) and no
other dependency; pocket and account share its fleet-code helpers for holding a Managed or
Manual executable. The
dotted edge from the account to the factory is the only call it ever makes to another contract:
update and apply_upgrade_policy ask the stored factory for account_wasm_hash, and
__check_auth never leaves the account. The router links no workspace crate and invokes whatever
legs a caller hands it, as that caller.
No contract compiles against another’s wasm; cross-contract interfaces are declared locally
(#[contractclient] traits, raw invoke_contract). Only the tests load built wasm
(contractimport! / include_bytes!) from target/wasm32v1-none/release/, so
make contract_test builds first. Nothing built is committed.
Deploy
sequenceDiagram
actor Admin
Admin->>Factory: deploy (admin)
Admin->>Factory: set_pocket_wasm_hash(hash)
Admin->>Factory: set_account_wasm_hash(hash)
Admin->>Collection: deploy (admin)
Admin->>Collection: create_collection(nfc-nft wasm, symbol, ...)
Collection-->>NftContract: deploy at sha256(symbol)
Admin->>NftContract: set_factory(factory)
Admin->>NftContract: mint(auth, public_key, ...) per card
NftContract->>Factory: create_account(public_key, curve, policy)
Factory-->>Pocket: deploy at sha256(public_key)
NftContract->>Collection: assign_collectible(...)
- Collection salt =
sha256(symbol). Pocket salt =sha256(chip_pubkey). - The factory needs its approved Pocket wasm hash pinned (
make contract_configure_factory, which also pins the account wasm hash if it has none). Under CAP-85 a re-pin is a live fleet upgrade, so the bring-up pins the Pocket only when the factory does not already pin the built hash and never moves an account pin; the deliberate push has its own targets (RELEASE.md). Older hashes and the permissionlessrefresh(): UPGRADES.md. - Pocket constructor:
(chip, curve, owner, upgrade_policy, factory). The curve is stored in the purse, so it verifies inline and depends on no registry.factoryis stored because aManagedpurse holds its code as a reference to that factory’s fleet entry.create_accounttakes noowner: the factory passes the purse’s own address, so a new purse owns itself until the card points it at a root. - nfc-nft needs
set_factorypointed at the factory (make contract_set_factory).mintdeploys the card’s purse through the factory and panicsMissingPocketwithout it, before writing anything.contract_deploy_allchains it. - Holder accounts are deployed by the terminal from the installed account wasm hash
(
make contract_upload_account), constructor(cards: Vec<CardSigner>, passkeys: Vec<PasskeySigner>, factory: Address). At least one signer in total; either set may be empty. The factory is recorded for good: it is where the account asks what the fleet runs. - The router takes no constructor and no wiring;
contract_deploy_alldeploys it afterset_factory.
NFT lifecycle
stateDiagram-v2
[*] --> OwnedByPurse: mint (admin + chip attestation)
OwnedByPurse --> HeldByAdmin: clawback (admin)
HeldByAdmin --> [*]
note right of OwnedByPurse
No transfer entry point: the token cannot leave its purse.
end note
note right of HeldByAdmin
The chip stays registered, so it cannot be minted again.
end note
Every change of owner is announced with SEP-50’s transfer event. mint emits mint
(topics ["mint", to], data the bare token_id); clawback emits transfer (topics
["transfer", from, to], data the bare token_id, from the purse, to the admin). An indexer
that follows ownership reads those two.
There is no unowned state. mint is a single call that provisions the trio: it allocates the
token, deploys the card’s purse through the factory, and writes Owner = pocket. Owner takes
exactly one write in a token’s life, to a destination derived from the card’s own key. There is
no to parameter and no transfer entry point, so a token cannot leave the purse it was minted
into. That is the soulbinding.
It is one call so a token never exists without its purse and no caller has to predict the purse
address, which is unknown until the factory deploys it. A root account has no say in what a
card’s purse holds, so mint takes no destination and asks no account to vouch.
mint writes PublicKey / TokenIdByPublicKey / ChipCurveByPublicKey / Owner / Balance
and calls collection.assign_collectible (the caller must be a registered collection
contract); so does clawback. Its guards (already minted, factory set, supply remaining) run
before the attestation, because verify_chip consumes the card’s nonce and none of them depend
on the signature: a call that cannot succeed costs no tap.
Beyond the token, nfc-nft is the card auth layer. verify_for_card(public_key, digest, auth) -> bool is a stateless oracle over the registry’s stored pubkey and curve, for integrators (see
examples/prize) that should not link the rlib; the core contracts link chimpdao-chip-auth
directly. It keeps no nonce: replay is the caller’s digest contract.
Handing a card to someone is not an NFT operation. The token and purse never move; the card’s
link to a root does (add_card / remove_card on Stellar, a SignerList seat on XRPL), and no
money moves. The terminal owns that choreography (useCardCeremonies.ts). The contracts enforce
only that remove_card and remove_passkey never remove an account’s last signer
(LastSigner, #504); emptying one is
an explicit abandon, which no ceremony calls. Where a router is deployed, the purse’s
set_owner and the account’s remove_card run as one router batch.
Dynamic traits (ERC-7496)
nfc-nft implements ERC-7496 (an Ethereum ERC; no SEP defines NFT traits): trait_value,
trait_values, set_trait, trait_metadata_uri, with the schema in
metadata.json.
There is one trait, tier: stored, admin-set, event-emitting, and it drives the art. The
standard requires every trait change to be an explicit on-chain action that emits an event, which
a value computed live from another contract cannot honour.
set_trait emits set_trait (topics ["set_trait", token_id], data map {trait_key, new_value}; SEP-50’s
trait update, the token id a topic so the events of one token can be filtered), then metadata
(topics ["metadata"], data the bare token_id), because tier drives the art and a client that
cached the token’s metadata should fetch it again. mint does not emit metadata: nothing is
cached yet. set_trait_metadata_uri emits set_trait_metadata_uri (data map {uri}).
A card’s money is therefore not a trait. pocket(token_id) -> Option<Address> returns the purse
address and the purse answers for itself, since it knows its float and positions and its assets
span chains this contract cannot see. It resolves through the factory best-effort: a missing or
trapping factory reads as None.
Events
An event is named after the function that emits it: bare imperative, no tense, setters keep
set_. This is how SEP-41, CAP-46-6 and the SEP-50 core name theirs (transfer, mint,
set_admin), so an indexer subscribes by a name it already knows. Topics are the name, then the
fields marked topic; data is the rest (a map, except where noted).
| Contract | Event (topics) | Data |
|---|---|---|
nfc-nft mint |
["mint", to] |
bare token_id |
nfc-nft clawback |
["transfer", from, to] |
bare token_id |
nfc-nft set_trait |
["set_trait", token_id] |
{trait_key, new_value} |
nfc-nft set_trait (tier) |
["metadata"] |
bare token_id |
nfc-nft set_trait_metadata_uri |
["set_trait_metadata_uri"] |
{uri} |
nfc-nft set_factory |
["set_factory"] |
{factory} |
nfc-nft, collection, pocket-factory set_admin |
["set_admin", admin] |
bare new_admin (SEP-41) |
nfc-nft, collection, pocket-factory, account, pocket upgrade |
["upgrade"] |
{wasm_hash} |
collection create_collection |
["create_collection"] |
{symbol, contract_address} |
pocket-factory create_account |
["create_account"] |
{public_key, contract_address} |
pocket-factory set_pocket_wasm_hash |
["set_pocket_wasm_hash", wasm_hash] |
{} |
pocket-factory set_account_wasm_hash |
["set_account_wasm_hash", wasm_hash] |
{} |
pocket-factory seed_history |
["seed_history"] |
{added, kind} |
pocket-factory refresh |
none | no recorded state moves |
account add_card / remove_card |
["add_card"] / ["remove_card"] |
{key} |
account add_passkey / remove_passkey |
["add_passkey"] / ["remove_passkey"] |
{key} |
account abandon |
["abandon"] |
{} |
account set_upgrade_policy |
["set_upgrade_policy", policy] |
{} |
account, pocket apply_upgrade_policy |
["apply_upgrade_policy", policy] |
{wasm_hash} when Manual (the hash now pinned), {} when Managed (a reference has no hash). Nothing when the apply is refused |
account update |
["update"] |
{wasm_hash} |
account set_factory |
["set_factory"] |
{factory} |
account constructor, set_factory |
["mint", to] (SEP-50; to is the account) |
bare token_id, always 0 |
pocket set_owner |
["set_owner", old] |
{new} |
pocket set_upgrade_policy |
["set_upgrade_policy", policy] |
{} |
Per-chip C-address implementing CustomAccountInterface. The chip signs the host’s
authorization payload, so every call it authorizes is bound to that call’s contract, function,
arguments, network, nonce and expiration ledger.
There is no transfer entry point. A payment is a plain SAC transfer(pocket, merchant, amount)
that the host routes to __check_auth, so the same purse works with Blend or any protocol
without new contract code; that is why DeFi positions live here and travel with the card.
Verification is linked (AUTH.md § Account auth). set_owner is chip-gated and
sweep does not exist, so Owner is a signpost the card rewrites, and a lost card is lost
money.
mint deploys the purse, so token and purse appear together. The factory’s create_account is
also admin-callable on its own, as a recovery path for a purse without a token.
UpgradePolicy is enforced on the purse via CAP-85 and decides how it holds its code:
- Managed: the purse’s executable is a reference to the factory’s executable-ref entry
(owner = factory, tag
"pocket"). Oneset_pocket_wasm_hashre-points every Managed purse atomically, with no per-purse transaction and no tap.Pocket::upgraderefuses (UpgradeIsManaged, #403): pinning a hash would silently take the purse out of the fleet, so leaving means choosing Manual first. - Manual: the purse holds a pinned hash that only its own chip can move; a fleet push does not touch it.
set_upgrade_policy is authorized by the card’s chip and records the decision; apply_upgrade_policy carries
it out. Only the decision needs the chip: applying can only make the executable match a choice
already signed, so it needs no authorization. The host forces the split, since a chip-signed
frame cannot also switch its executable to a reference in the same invocation.
Apply is single-shot. set_upgrade_policy marks one apply as owed (PendingApply), and
apply_upgrade_policy refuses (NothingToApply, #405) without the mark, clearing it as it
goes. Otherwise apply would be a permissionless re-pin: Manual pins whatever hash the fleet is
on now, so anyone could move a purse back onto the fleet after its chip pinned its own code.
An apply that switches the executable emits apply_upgrade_policy, as upgrade and update
emit theirs, so the holder’s events show the switch even though nobody signed it.
stateDiagram-v2
[*] --> Managed: deployed Managed, code is a ref to the fleet entry
[*] --> Manual: deployed Manual, code is a pinned hash
Managed --> PendingManual: set_upgrade_policy(Manual), chip
PendingManual --> Manual: apply_upgrade_policy, anyone, once
PendingManual --> Manual: upgrade(hash) by the chip, clears the pending apply
Manual --> PendingManaged: set_upgrade_policy(Managed), chip
PendingManaged --> Managed: apply_upgrade_policy, anyone, once
Manual --> Manual: upgrade(hash), chip
upgrade pins the chip’s own code and so voids a pending apply: a stranger cannot replace the
pinned code with the fleet’s afterwards.
The Chimp account runs the same machine under the same words (Chimp account),
with the factory’s "account" entry in place of "pocket" and update() in place of a
chip-chosen hash. The Pocket’s upgrade(hash) and the account’s both refuse while Managed
(UpgradeIsManaged, #403 and #511).
Chimp account
The durable root. Two signer sets in one instance entry each, Cards and Passkeys, caps
MAX_CARDS = 16 and MAX_PASSKEYS = 3 (a platform passkey, a hardware key, and a free slot to replace either). One signature from either kind authorizes anything:
__check_auth ignores auth_contexts, so a card and a passkey have the same power, including
adding or removing the other kind. The last signer of either kind cannot be removed
(LastSigner, #504); abandon clears both sets on purpose.
pub struct CardSigner { key: BytesN<65>, curve: Curve }
pub struct PasskeySigner { key: BytesN<65>, credential_id: Bytes, rp_id_hash: BytesN<32> }
pub struct AccountAuth { key: BytesN<65>, auth: AccountProof }
pub enum AccountProof { <a card proof>, Webauthn(WebauthnAuth) }
pub struct WebauthnAuth { authenticator_data: Bytes, client_data_json: Bytes, signature: BytesN<64> }
Webauthn is looked up in Passkeys only and the card variants in Cards only, so a key listed
as one kind is never accepted as the other. The verification steps are in
AUTH.md.
Upgrade policy. Default Manual: the account pins a wasm hash that only a signer moves.
Managed is the holder’s signed opt-in: the executable becomes a CAP-85 reference to the
factory’s "account" entry, so one set_account_wasm_hash re-points every opted-in account with
no signature. The decision and its single-shot apply work as the Pocket’s above
(NothingToApply, #512). upgrade(hash) is the signer-chosen escape hatch and update() takes
no hash: it installs whatever the stored factory pins (account_wasm_hash), so a signature that
was phished or mis-shown can only install the wasm ChimpDAO published. Both refuse while
Managed (#511). set_factory(factory) records the factory once on an account that has none
(FactoryAlreadySet, #514); it is the one trust point of update(), and it resets a stored
Managed to Manual. version() returns 2. Operator and client procedure:
UPGRADES.md.
SEP-50. The account is its own one token, id 0, owned by itself: balance, owner_of,
name, symbol and token_uri (https://nft.chimpdao.xyz/account/<C-address>), with the
signatures nfc-nft uses. There is no transfer or approve, so the token is soulbound by
absence, and any other id is NonExistentToken (#515). The constructor, and set_factory on an
upgraded account, emit the SEP-50 mint once.
Errors. Codes 501 to 516, per contract, with the client wording: CLIENT-INTEGRATION.md.
Prize (example)
Deposit locks SEP-41 under a chip pubkey (resolved via nfc public_key(token_id)). Redeem needs wallet auth, a chip attestation under the prize domain, and owner_of == redeemer. See examples/prize/README.md.
Storage (compact)
collection — Instance: Admin, Collections. Persistent: Collectibles(collection, token_id) → owner, OwnerCollectibles(owner) → Vec<(collection, token_id)>.
nfc-nft — Instance: Admin, CollectionContract, metadata, NextTokenId, MaxTokens, TraitUri, Factory. Persistent: Owner/Balance/PublicKey/TokenIdByPublicKey, ChipNonceByPublicKey, ChipCurveByPublicKey, Tier(token_id), TokenUri(token_id) (only for a token minted with a URI).
account — Instance: Cards → Vec<CardSigner>, Passkeys → Vec<PasskeySigner>, UpgradePolicy, Factory (set by the constructor, or once by set_factory), PendingApply (present only between a signed set_upgrade_policy that changed the policy and its apply_upgrade_policy). No nonce (the host owns replay) and no rules. Each is its own key, so a missing Passkeys reads as empty; the UpgradePolicy getter returns Manual until a policy is set.
Pocket — Instance: Chip, Curve, Owner, UpgradePolicy, Factory (the deployer, and so the owner of the fleet entry a Managed purse references), PendingApply (present only between a chip-signed set_upgrade_policy and its apply_upgrade_policy). No Nonce: the host owns replay protection.
factory — Instance: Admin, PocketWasmHash, AccountWasmHash, Epoch, PocketWasmHistory, AccountWasmHistory. Persistent: Account(pubkey) → Address. Executable-ref entries "pocket" and "account" → the fleet wasm hash: the CAP-85 entries every Managed purse and every Managed account references, written together with the matching head and never deletable, so the tags are constants. The head, history and epoch rules are in UPGRADES.md.
prize — Instance: Admin, Token, NfcContract. Persistent: Vault(pubkey) → i128, Nonce(pubkey) → u32.
router: no keys. Every batch call bumps the instance TTL (floor 30 days, target 90).
Stack and memory
A Rust contract reserves a 1 MiB shadow stack in linear memory by default, so every contract started
life with 17 memory pages, and every invocation, each cross-contract call included, paid for them.
build.rs, which each contract crate names as its build script, links with a 4 KiB
stack instead: one 64 KiB page. The deepest entry point of any contract measures 192 B (nfc-nft
mint), by wasm-stack-estimator, so the stack
has 21x headroom or more (make contract_stack fails below 1.5x). An overflow traps rather than
corrupting data, since the stack sits at the start of memory. pocket and account also run their
__check_auth in the built wasm on both curves in tests, which would fail with a stack of 64 B.
TTL
Every state-changing entry point of nfc-nft, collection, pocket-factory and the router starts
by extending its own instance and code TTL (floor 30 days, target 90). set_pocket_wasm_hash
and set_account_wasm_hash also extend their fleet’s executable-ref entry, so a single push keeps the entry every Managed
purse (or account) points at alive.
Between pushes the factory’s permissionless refresh() does the same for the factory and each
reference entry, so a Managed holder does not depend on how often the admin pushes. The wasm code
entry behind a head has a separate TTL that no contract can extend; the keepalive procedure,
including that half, is UPGRADES.md.
Nothing extends a holder’s entries, and using an entry does not extend it. Purses, accounts and a
card’s token data are kept alive by whoever extends them, with an operation anyone can submit
(stellar contract extend). An archived entry is restored by anyone, and the RPC simulation
reports when a transaction needs it.