DOCS / REFERENCE / CLIENT INTEGRATION

Client integration

Live on testnet

COPIED FROM chimpdao-contracts/docs/CLIENT-INTEGRATION.md · REVISION 6fd752349933 · Repository ↗

What a client must do to work with the Chimp contracts: sign for a Main account with a card or a passkey, find and create accounts, keep a wallet’s code up to date, and avoid the mistakes this system has already paid for. It is client-agnostic. The reference implementation is the web terminal (chimpdao-terminal). Where this document and the Rust sources disagree, the sources win: contracts/account/src/*.rs, contracts/chip-auth/src/*.rs, contracts/pocket-factory/src/*.rs, contracts/pocket/src/*.rs.

The model behind it is in ARCHITECTURE.md and AUTH.md; the update system’s operator side is UPGRADES.md and RELEASE.md.

Contents

  1. Reference implementation
  2. Networks and addresses
  3. The model in one page
  4. The account signature wire
  5. Passkeys, step by step
  6. Updates
  7. Order of signing
  8. Who pays the fee
  9. ABI summary
  10. Errors
  11. Events and limits
  12. What not to do
  13. Verified and not verified on a real network

1. Reference implementation

Paths are in /Users/tupui/Documents/Code/chimpdao-terminal (the sibling repo) unless noted. Match these behaviours; do not copy them blindly.

Topic File
Passkey primitives: base64url, SPKI to SEC1, DER to raw, low-S, user handle, rpId src/chain/passkey/webauthn.ts
navigator.credentials calls, the checks that mirror the contract’s src/chain/passkey/credential.ts
The on-chain encodings of a passkey (AccountAuth, PasskeySigner) src/chain/passkey/account-proof.ts
The signer abstraction (card or passkey, peers) src/chain/account-signer.ts, src/flow/signerPlan.ts
Account creation and passkey sign-in src/modules/onboarding/passkeyAuth.ts
Deploy, constructor args, address prediction, signer management, update routes src/chain/provisioning.ts
Which signers an account lists, shaped for a signing job src/session/mainSigners.ts
Reading the fleet and executables src/chain/fleet.ts
Judging a contract against the fleet src/chain/updates.ts
The idempotent update algorithm src/chain/update-run.ts
The advisory cache src/session/updateCache.ts
When to sign before simulating src/chain/sign-path.ts, src/chain/auth-tree.ts
Claim-time policy choice and batch src/modules/card/claim.ts, src/modules/card/claimPolicy.ts
Wording for the consent screens src/ui/policyCopy.ts
User wording of every error code src/lib/errors.ts
Auth entries: payload hash, V1 and V2, signing slot src/chain/chip-auth.ts (authPayloadHash, restamp, signAuthEntries)

The pinned wire vectors live in contracts/account/src/test.rs (cards and passkeys); the terminal reproduces them in src/chain/passkey/account-proof.test.ts and src/chain/provisioning.signers.test.ts.

2. Networks and addresses

A fact below marked snapshot was read from the network on 2026-11-07 and can have moved. Re-read it with fleet() (§6.1) before relying on it.

Testnet

What Value
RPC https://soroban-testnet.stellar.org
Network passphrase Test SDF Network ; September 2015
Pocket factory (the e2e fleet) CDWPHF7DRJ37GLFZGQDSO6RTX4QR75WTNKJUMFJRETQLIOAHFBU6RGYR
Router CAOL3K7VQTDZELQMKTAJB3WUQGL5JLXJKZ2Y44F77NH4CZNLW5I755XI
Collection CDGFNWFN7ZKU4XDPNXOGDQ4JZ7SZCMXLL3PYFESOCCA2L5DM3ZBCPEKC
Campaign og (the terminal’s default nfcNft) CAHOJMBLANFG7YQGCY4BRWSQ5N5Q5FVM5D3WA4S5ZON3QSNP2OJDRJPT
Campaign chi4 CC6Z7JDXX2RXULI2TMY7OGJJ57WXTBRCQDRR4W4IFEJZZ7SPGCPYJEJT
Fee signer Worker https://chimpdao-signer.tansu-964.workers.dev (§8)

The factory’s fleet record is read with fleet() (§6.1): the current Pocket and account heads and every hash a testnet contract may still run. Nothing here types them, because they move with every pin; the deployment records .config/stellar/*_wasm_hash_testnet (heads) and *_wasm_history_testnet (histories) hold the same values with their full length.

  • The first account wasm (044275ac…, the oldest entry of the account history) has no version(): the call traps, read it as 1. An account on any earlier hash reads available against the head, and a hash older than the 16 the history keeps reads custom.
  • The heads are local builds: a release build has a different hash, and the release-container hash replaces them at release time (RELEASE.md). Each was pinned only after its canary passed (the account canary, and a payment from a fleet-following purse for the Pocket). The terminal’s src/chain/contracts.ts bundles the account head as the wasm new accounts are born on.
  • The factory has fleet(), the epoch that moves with every head change, and the permissionless refresh(). make contract_upgrade_factory prints the hash it replaces and keeps that wasm in .config/stellar/live/ as the rollback target. Before the first version with fleet(), the call trapped and clients read pocket_wasm_hash() (§6.1).
  • Testnet runs protocol 30. Its ledger header carries a StellarValueExt variant (v = 3) that @stellar/stellar-sdk 17.0.1 cannot decode: getLatestLedger and getLedgers throw LedgerHeader.scpValue.ext.v: unknown enum value 3, and every signing flow needs a ledger sequence. Any client must use an SDK that decodes protocol-30 headers (the JavaScript SDK from 17.4.0 does), or avoid decoding the header and read only the sequence from the raw JSON-RPC response. A client built on a different SDK (the Swift one, for example) must prove this before anything else (§12).
  • Installed wasm entries expire, within days on testnet. The operator extends every code entry a flow depends on before any canary or update (RELEASE.md); if a deploy or update fails because a code entry is archived, restore it (§13) or ask the operator.

Mainnet

Do not touch mainnet. Mainnet runs the first account wasm and the pre-audit Pocket wasm. Nothing in this document is released there, and nothing may be pinned, deployed or signed on it until the audit is done and the operator says so (MAINNET-ROLLOUT.md). The addresses are listed so you can recognise them, not to use them.

What Value
Pocket factory CDD4EK5ILEECEZKTON3PC5YWQFMFODMG4X27TTNIZ7WQT3KUR5C7DWYU
Router CAQZ4SWXVCSWMXP42TGMAFVMOPWSIBI27AUL3VHEOOEIEW6L4RXX2Y7W
Collection CCWQBP7UOTSHMNEVE2P2DCLNI37CFA4WNPMUBNES5BH7QEEEUBXL7Y5Z
Campaigns chi1 CCTPN4LRCNJBLC3VVEYET7MRLQHSAAXTQG4YBG7W3HORHZFHJIIQ7BLO, og CD6TCEK4DUGLZJ77YGOIVLNHTQ2HDVBULNAX7MOKPMHCPB6LKSDNMEWA
Account wasm 51ab668924feb73e1c875cc769f293a8573d9126fa050d4ad4bcee7f7fdf90ce
Pocket wasm 30713fde…0fd5b (every mainnet purse is Manual)

Mainnet’s factory predates fleet(): it answers pocket_wasm_hash() only.

3. The model in one page

  • A card is an NFC chip. Its public key is a 65-byte uncompressed SEC1 point. Each card has a purse (a Soroban account contract, the “Pocket”) that answers to that chip and to nothing else. A purse holds the card’s float. Nothing, a passkey included, can move a purse’s funds without the chip.
  • The Main account is a Soroban custom account (contracts/account). Its signers are cards and passkeys, peers: one signature from any signer is enough (1-of-n); every signer has exactly the same power, including adding and removing other signers and changing the account’s code. A Main may hold only cards, only passkeys, or both. Neither kind is a backup or a recovery path for the other.
  • A passkey is a WebAuthn P-256 credential. The contract verifies its assertion inline with the host’s P-256 primitive: no verifier contract, no new cryptography.
  • Both contracts sign over the payload the host computes (§4). There is no app nonce.
  • The account’s code policy is Manual (default) or Managed (the holder’s signed opt-in). Purses use the same two words and the same state machine (§6.7).
  • ChimpDAO never recovers anything. Losing every signer loses the Main; losing a card loses its purse.

XDR conventions the contracts rely on, used throughout: a Rust struct is an ScMap whose keys are the field names as ScSymbol, in sorted order; an enum variant is an ScVec of [Symbol(variant name), payload] (a unit variant is [Symbol(name)]); Bytes/BytesN<n> are ScBytes; u32 is ScU32.

4. The account signature wire

A Main account authorizes a call when the transaction carries a Soroban authorization entry whose credentials address is the account, and whose signature is this value (SorobanAddressCredentials.signature, set directly, not wrapped in a vec):

AccountAuth  { key: BytesN<65>, auth: AccountProof }          ScMap { auth, key }
AccountProof = <a card proof> | Webauthn(WebauthnAuth)        ScVec [Symbol(variant), payload]
WebauthnAuth { authenticator_data: Bytes, client_data_json: Bytes, signature: BytesN<64> }
                                                              ScMap { authenticator_data, client_data_json, signature }

key only selects the signer; the contract verifies the proof against the stored entry. A Webauthn proof is looked up in the passkey set only and a card proof in the card set only; a key in one set is never accepted from the other. A card client that never learns about passkeys builds the same bytes it always did.

The payload every signer signs is the host’s, 32 bytes:

sha256(HashIdPreimage::SorobanAuthorization { network_id, nonce, signature_expiration_ledger, invocation })
  • network_id = sha256(network passphrase).
  • Set signature_expiration_ledger on the entry before hashing; the hash depends on it.
  • An entry from a recording simulation may carry credentials sorobanCredentialsAddressV2 (CAP-71). Its payload is HashIdPreimage::SorobanAuthorizationWithAddress, the same fields plus the authorizing address. Hash the variant the entry carries; never convert one into the other. Entries a client builds itself are V1.
  • A payload is bound to the invocation, so a signature is not portable between two calls. A V1 payload does not carry the authorizing address: a purse and an account that list the same card accept the same signature for an invocation that names neither. Every call in this document names its authorizer, so none is affected (AUTH.md).

Pinned vectors

Each vector is base64 of the exact ScVal XDR. Reproduce them byte for byte.

Passkey (test.rs, generated from a deterministic software authenticator with relying party chimpdao.xyz, flags 0x1d, then checked with an independent ECDSA implementation: a valid low-S P-256 signature):

Item Value
Signed payload adf00fdffb1ae3edd448c4c90a8da03259f3d43f2453bc26ed0f51ffaf13f1bd (sha256("a call the host bound"))
Key (SEC1) 0451a7580833898ea1b183cbd7350a4099078c6ef1c1e18e970cd7683035f25e7d0110522712b0b5a7cff081685486984a94e6831edac46e7360fa9d834a7a81a1
Credential id 16 bytes of 0x33
rp_id_hash = sha256("chimpdao.xyz") 1111887d42eec4e491447860c703804e2a45d3287e7f2e3800df85647fd542df
authenticator_data (37 bytes) 1111887d42eec4e491447860c703804e2a45d3287e7f2e3800df85647fd542df1d00000000
client_data_json {"type":"webauthn.get","challenge":"rfAP3_sa4-3USMTJCo2gMlnz1D8kU7wm7Q9R_68T8b0","origin":"https://chimpdao.xyz","crossOrigin":false}

AccountAuth with Webauthn (TERMINAL_ACCOUNT_AUTH_WEBAUTHN):

AAAAEQAAAAEAAAACAAAADwAAAARhdXRoAAAAEAAAAAEAAAACAAAADwAAAAhXZWJhdXRobgAAABEAAAABAAAAAwAAAA8AAAASYXV0aGVudGljYXRvcl9kYXRhAAAAAAANAAAAJRERiH1C7sTkkUR4YMcDgE4qRdMofn8uOADfhWR/1ULfHQAAAAAAAAAAAAAPAAAAEGNsaWVudF9kYXRhX2pzb24AAAANAAAAhXsidHlwZSI6IndlYmF1dGhuLmdldCIsImNoYWxsZW5nZSI6InJmQVAzX3NhNC0zVVNNVEpDbzJnTWxuejFEOGtVN3dtN1E5Ul82OFQ4YjAiLCJvcmlnaW4iOiJodHRwczovL2NoaW1wZGFvLnh5eiIsImNyb3NzT3JpZ2luIjpmYWxzZX0AAAAAAAAPAAAACXNpZ25hdHVyZQAAAAAAAA0AAABAM//2PL5hyao7PX0eQAiMqBZovkCvUu44aqwS+0wS52YVsLjPGfkQpYnNcoJt15Kz1iwm8I//f7z0yoS0JoTC4AAAAA8AAAADa2V5AAAAAA0AAABBBFGnWAgziY6hsYPL1zUKQJkHjG7xweGOlwzXaDA18l59ARBSJxKwtafP8IFoVIaYSpTmgx7axG5zYPqdg0p6gaEAAAA=

PasskeySigner (TERMINAL_PASSKEY_SIGNER, the argument of add_passkey):

AAAAEQAAAAEAAAADAAAADwAAAA1jcmVkZW50aWFsX2lkAAAAAAAADQAAABAzMzMzMzMzMzMzMzMzMzMzAAAADwAAAANrZXkAAAAADQAAAEEEUadYCDOJjqGxg8vXNQpAmQeMbvHB4Y6XDNdoMDXyXn0BEFInErC1p8/wgWhUhphKlOaDHtrEbnNg+p2DSnqBoQAAAAAAAA8AAAAKcnBfaWRfaGFzaAAAAAAADQAAACAREYh9Qu7E5JFEeGDHA4BOKkXTKH5/LjgA34Vkf9VC3w==

Vec<PasskeySigner> (TERMINAL_VEC_PASSKEYS, the constructor’s second argument, one element):

AAAAEAAAAAEAAAABAAAAEQAAAAEAAAADAAAADwAAAA1jcmVkZW50aWFsX2lkAAAAAAAADQAAABAzMzMzMzMzMzMzMzMzMzMzAAAADwAAAANrZXkAAAAADQAAAEEEUadYCDOJjqGxg8vXNQpAmQeMbvHB4Y6XDNdoMDXyXn0BEFInErC1p8/wgWhUhphKlOaDHtrEbnNg+p2DSnqBoQAAAAAAAA8AAAAKcnBfaWRfaGFzaAAAAAAADQAAACAREYh9Qu7E5JFEeGDHA4BOKkXTKH5/LjgA34Vkf9VC3w==

5. Passkeys, step by step

5.1 The relying party

The relying-party id (rpId) is chimpdao.xyz in production and localhost in development, set explicitly. A credential is bound to its rpId for life: it cannot move to another domain, and a passkey made under the wrong rpId is stranded. Do not derive the rpId from whatever host served the page. The terminal maps chimpdao.xyz and any subdomain to chimpdao.xyz, localhost to itself, and refuses every other host (rpIdFor in webauthn.ts): a client must refuse hosts outside the domain.

The rpId covers the whole domain on purpose: the landing site, the NFT viewer (nft.chimpdao.xyz) and a future web app that manages the Main account all need to ask for passkey signatures, for example to onboard a user at a first payment on the website. The contract therefore does not bind the WebAuthn origin (§5.7). That is safe only while every host under chimpdao.xyz is controlled by ChimpDAO (no third-party hosting or user-generated content on a subdomain, no dangling DNS that could be taken over), because a page on any such host can ask the authenticator for a signature and the user’s verification prompt, which shows no transaction, is the only gate it faces.

rp_id_hash = sha256(utf8(rpId)) is stored with each passkey and must equal the first 32 bytes of every assertion’s authenticator_data.

5.2 Creating a passkey

WebAuthn create with:

Option Value
rp { id: rpId, name: "ChimpDAO" }
user.id the 64-byte handle of §5.3
user.name, user.displayName Chimp Main account
challenge 32 random bytes (it is not verified by the chain)
pubKeyCredParams [{ type: public-key, alg: -7 }] (ES256 only)
authenticatorSelection residentKey: required, userVerification: required
attestation none

Take the credential id (rawId) and the public key: the SubjectPublicKeyInfo DER from getPublicKey(), converted to the 65-byte uncompressed SEC1 point (§5.4). Reject an authenticator that does not answer ES256.

5.3 The 64-byte user handle

user.id = salt (32 random bytes) ‖ account contract id (32 raw bytes)      64 bytes

Both halves are public chain facts; the handle holds no secret and no personal data. The salt makes account creation resumable from the credential alone (§5.8); the contract id lets a later sign-in read the account out of userHandle[32..64] without recomputing anything.

5.4 Public key: SPKI to SEC1

A P-256 SPKI is exactly 91 bytes: the 26-byte prefix 3059301306072a8648ce3d020106082a8648ce3d030107034200 followed by the 65-byte point, whose first byte is 04. Match all 26 prefix bytes and the length; do not just take the last 65 bytes, which would read another curve or key type as P-256.

5.5 Asking a passkey to sign

WebAuthn get with rpId, userVerification: required, challenge = the 32-byte payload of §4 as raw bytes (the browser or OS base64url-encodes it into clientDataJSON itself), and allowCredentials = the stored credential id (or empty for discoverable sign-in, §5.9). Use the returned authenticatorData, clientDataJSON and DER signature.

Check before building the transaction, exactly as the contract will (so a bad response is an error with a reason instead of a trapped transaction):

  1. authenticatorData is at least 37 bytes and its first 32 bytes equal rp_id_hash.
  2. The flags byte (authenticatorData[32]) has user presence 0x01 and user verification 0x04.
  3. clientDataJSON starts with the bytes {"type":"webauthn.get","challenge":" followed by base64url(payload) (unpadded, 43 characters) and ".
  4. If the response names a credential other than the one requested, refuse it.

5.6 The signature: DER to raw, then low-S

An authenticator returns a DER SEQUENCE { INTEGER r, INTEGER s } with variable-length integers. The contract takes raw 64-byte r ‖ s.

  1. Parse the DER (short-form lengths only; a P-256 signature is at most 72 bytes). Strip leading zero bytes from each INTEGER, reject empty, negative, zero or longer-than-32-byte values, and left-pad each to 32 bytes. Reject trailing bytes.
  2. Normalize to low-S. Let n = FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551. If s > n/2 then s := n − s. The host’s secp256r1_verify accepts only the low-S form (a high-S signature traps the transaction), and about half of all authenticator signatures are high-S, so skipping this fails intermittently.
  3. Build WebauthnAuth { authenticator_data, client_data_json, signature = r ‖ s }.

5.7 What the contract checks, and its caps

verify_webauthn in contracts/chip-auth/src/webauthn.rs runs the checks of §5.5 against the stored passkey the proof’s key names, with the size caps of §11, then secp256r1_verify(key, sha256(authenticator_data ‖ sha256(client_data_json)), signature). The challenge compare is a fixed-prefix byte compare: no JSON parsing, no substring search, no base64 decoding (AUTH.md).

A structural failure returns InvalidSignature (#502). A signature that does not verify, or a high-S one, traps. Not checked, on purpose: origin, crossOrigin (§5.1), the signature counter (synced passkeys report 0), backup flags, attestation, extensions. A client that serializes clientDataJSON with the fields in another order fails closed.

5.8 Creating an account with a passkey

  1. Draw a random 32-byte salt.
  2. Predict the account address (a pure function of the fee account and the salt): sha256(HashIdPreimage::ContractId { network_id, ContractIdPreimage::FromAddress { address: <fee account G-address>, salt } }), StrKey-encoded as a C… address. The deployer is the fee/relayer account of §8, so you need its public key.
  3. Create the passkey (§5.2) with user.id = salt ‖ raw contract id.
  4. Write a resume note holding only public values (salt, account, credential id, public key).
  5. Deploy: CreateContractV2 of the account wasm, deployer = the fee account, salt, constructor (cards: Vec<CardSigner>, passkeys: Vec<PasskeySigner>, factory: Address) with cards = [], passkeys = [PasskeySigner { key, credential_id, rp_id_hash }] and the network’s factory from your configuration. Skip the deploy if the instance already exists: it is idempotent on the salt.
  6. Read the chain: has_passkey(key) must be true. Then clear the note and log in.

Before step 5, check the account wasm you are about to deploy is recognised by the fleet: it must be the account head or in account_history, else refuse (an account born on code nobody published can never be offered an update). If the fleet pins no account head yet (null, as on a factory before its first account pin), the fleet has no opinion and the wasm your build is configured for stands. If the address predicted from the stored salt differs from the one in the note (the fee account changed), refuse and say so; do not deploy elsewhere. Resume is safe only under the same fee account.

The constructor requires at least one signer in total, no duplicate card key, no duplicate passkey key or credential id, at most 16 cards and 3 passkeys, and a credential id of 1 to 255 bytes.

5.9 Signing in (discoverable)

  1. get with a random challenge, no allowCredentials, userVerification: required.
  2. Require userHandle to be exactly 64 bytes; otherwise the passkey is not ours.
  3. account = userHandle[32..64] as a C… address.
  4. Read passkeys() on that account. The credential id from step 1 must be in the list. If it is not, the only legitimate reason is an interrupted creation: finish it from the resume note; otherwise refuse.

Nothing is trusted from the answer except the credential id and the handle, and the chain decides. There is no local source of truth.

5.10 Managing signers

All are authorized by the account itself, so any signer on it may sign them:

Call Notes
add_passkey(PasskeySigner) credential id 1 to 255 bytes; refuses duplicate key or credential id; max 3
remove_passkey(key: BytesN<65>)
add_card(CardSigner) / remove_card(key) max 16 cards
abandon() irreversible; clears both sets, every card and every passkey. The way to leave an account whose last signer is going away: move what it holds first. Its code can still move (UPGRADES.md)

remove_card and remove_passkey refuse to remove the last signer of either kind (LastSigner, #504). A client should refuse first, before any prompt, using the same count over cards() and passkeys(). A passkey added later gets a fresh random salt in its user handle (reusing a handle would overwrite the earlier credential on the same authenticator).

A signer can remove a lost one without it present. A removed card keeps its purse and can be added again, to the same account or to another. So does a card left on an abandoned account, which can only join another one.

5.11 The peers rule

If the account lists both kinds, offer both equally; if one kind, use it. Do not label either as primary, backup or recovery, and do not nudge a holder toward one kind (chooseSigner in account-signer.ts; jobSignersFor in session/mainSigners.ts). A passkey whose rp_id_hash does not match this site’s is not offered here (it would only fail at the prompt).

One exception, a second signer. An account with a single signer is one lost device from lost for good, and a passkey cannot be rotated without a second slot. A client may suggest adding a second signer of any kind, in neutral words (“add a second way to open your account”), offering every kind equally: a card, a hardware security key (§5.2 with a security-key credential), or another passkey. The suggestion is about having two signers, never about which kind is the main one. Do not repeat it after the holder dismisses it.

6. Updates

6.1 The fleet

The factory records the latest code. One read, fleet(), simulation only:

Fleet { account: Option<BytesN<32>>, account_history: Vec<BytesN<32>>, epoch: u32,
        pocket:  Option<BytesN<32>>, pocket_history:  Vec<BytesN<32>> }       ScMap, keys sorted
  • pocket / account are the heads (null if never pinned); the histories are oldest first, head last, at most 16.
  • epoch moves whenever a pin changes a head (from none to some, or to a different hash) or a seed adds a hash. Re-pinning the identical head moves nothing. One cheap read tells a client whether anything it cached is stale.
  • A factory that predates fleet() traps on it. Treat a contract trap as “older factory” and fall back to pocket_wasm_hash() (head only, no history, no epoch); take the account head from your own bundled configuration. This is “legacy mode”: with only a head, any other hash reads as Available, because there is no ordering to consult. A transport error is not a trap: never fall back on it.

Also: account_wasm_hash() -> Option<BytesN<32>> and pocket_wasm_hash() -> Option<BytesN<32>>.

6.2 What a contract runs now

Read the contract’s instance ledger entry (getLedgerEntries, no simulation; batch the Main and every purse in one request, 100 keys per request or fewer). Its executable is one of:

  • wasm with a hash: a pinned release;
  • a reference to the factory’s fleet entry (ExternalRef { owner: factory, tag }): it follows the fleet;
  • anything else (a stellar asset executable): not ours.

An absent entry means archived or never deployed; treat it as unknown, never guess a hash.

6.3 Status

Judge each contract against its component’s target (pocket for a purse, account for a Main):

Status Condition The client
managed executable is a fleet reference nothing: it follows the fleet
unknown no head pinned nothing
upToDate hash is the head nothing
available{from,to} hash is in the history but not the head (or, in legacy mode, differs from the head) offers to, the head
custom hash is not in the history leaves it alone: never prompts, never offers a downgrade

A hash older than the 16 the history keeps also reads custom. Nothing ever blocks a payment on any status. Compare hashes as lowercase hex.

6.4 The cache is advisory

It decides what to show and whether to prompt; it never authorizes a write. Reference: src/session/updateCache.ts.

Rule Value
Key per network (chimp.updates.<network> in the terminal); any local store is fine
Contents the fleet (heads, histories, epoch, checked-at), a map contract address to last seen hash with a timestamp, and dismissed heads
Fleet revalidation when unknown or older than 6 hours, when the updates screen opens, on refresh
applied hash trusted for display for 7 days; seeded by one batched executable read when the account view loads, for addresses with no trusted entry; at most 64 entries
managed contracts never cached (a stale hash would only ever be wrong); drop any entry when a read shows a fleet reference
Clock an entry timestamped in the future is not trusted
Corrupt or unknown version treat as empty and re-derive

A stale cache can only cost a missed or a spurious prompt, and the next step corrects both.

6.5 The idempotent update

The target state is “the executable’s hash equals the head”, so repeating it, or doing it from another device or a script, is a no-op. In order (update-run.ts):

  1. Read the executable from the chain. Never the cache.
  2. Already the target: record it, say “Already up to date”, ask for no signature.
  3. A fleet reference: refuse with “follows ChimpDAO’s code” before any prompt (the contract would refuse with #403 or #511).
  4. Check the target wasm is installed and live (getLedgerEntries on its ContractCode key; absent means “not installed yet”; a lapsed liveUntilLedgerSeq means archived, restorable by anyone, §13).
  5. Review (§12), sign, submit.
  6. Read back and compare, whatever happened. On an ambiguous timeout re-read several times (a few seconds apart) before reporting a failure: the transaction may have landed. A success that does not read back as the target is “sent but not confirmed”, not success.

Run the check of steps 1 to 3 before opening a signing screen, so a no-op never costs a tap.

6.6 Updating a Main

Read version() (a trap means 1).

Account Route Signed by
version 2, factory recorded update(): no hash argument; installs what the stored factory pins any signer
version 2, factory() is null set_factory(factory), then update() any signer
version 1 (the first wasm) upgrade(head) and set_factory(factory) as one router batch under one signature any signer
  • update() can only install the wasm ChimpDAO published, so a signature that was mis-shown or phished cannot install an attacker’s. That holds only if the stored factory is the real one. set_factory writes it once (a second call is #514), so it is the one trust point: take the factory address from your own configuration, never from the account or the network, and show it in full in the review.
  • On the first wasm, a recorded Managed was advisory and never true of the executable. After the hop, set_factory resets a stored Managed to Manual; opting into Managed is a fresh signed choice.
  • The v1 hop is one router batch, [account.upgrade(head), account.set_factory(factory)], declared and signed first by one signer: code installed by upgrade is visible to the next call in the same invocation, and this is verified on a real host (§13). Without a router on the network, run the two calls as two transactions, each idempotent; an interrupted hop is then finished by the next run (accountNeedsFactory).
  • update() takes no argument and is not guarded by the account’s current hash: called when the account already runs the pinned wasm it succeeds as a reinstall of the same hash, costs a fee, emits update and changes no state. Called on code that has no update it fails with Error(WasmVm, MissingValue). So the client’s re-read of the executable (§6.5 steps 1 and 2) is the only thing that spares a holder a pointless signature; do not skip it.
  • upgrade(hash) stays as the signer’s own escape hatch for any installed wasm; it is refused while Managed. Prefer update().

6.7 Updating a purse

Purse Route Signed by
Manual Pocket::upgrade(head) that card (its chip, and PIN if set)
Managed nothing: it follows the fleet nobody

upgrade on a Managed purse is #403. A purse update needs that card on the reader, so a list of out-of-date cards is one tap per card.

After the update, apply once. When the upgrade has read back (§6.5, step 6), call apply_upgrade_policy() with no card and take #405 as the expected answer. A purse minted on the first mainnet Pocket wasm can still owe an apply after its update (that wasm owes one for every signed set_upgrade_policy, changed or not, and its upgrade cancels none), and anyone could spend it later to pin the purse to a head its card never accepted. Applied now, it pins the head the card has just installed, so nothing changes and nothing is left owed.

6.8 The Manual and Managed choice

The same two words and the same state machine for a purse and a Main (policy.rs):

  • set_upgrade_policy(policy) is signed (purse: its chip; Main: any signer). Policy is an enum value, ScVec [Symbol("Managed")] or [Symbol("Manual")]. It records the decision and marks one apply as owed, only if the value changed (on the first mainnet Pocket wasm, every signed call owes one; §6.7).
  • apply_upgrade_policy() is permissionless and single-shot: it makes the executable match the decision (Managed: a reference to the factory’s "pocket"/"account" entry; Manual: the hash the factory reports now). With nothing owed it is #405 (purse) or #512 (account). Anyone, including a fee-paid transaction with no card, may call it. A successful apply emits apply_upgrade_policy (§11); a refused one emits nothing.
  • Order: sign the decision, then apply. A decision that landed without its apply is finished by the next run with no signature.
  • The default for a Main is Manual; nobody is enrolled in Managed. Because Managed lets the factory’s admin change the code that guards the holder’s funds, a client must say so plainly before asking for it, giving both halves of the trade with equal weight and recommending neither. The terminal’s required sentences (src/ui/policyCopy.ts):
    • Managed: “ChimpDAO can change this account’s code, and new releases arrive without your signature. If a release turns out to be bad, ChimpDAO can move your account back to a good one.”
    • Manual: “your account keeps the code it runs until you sign to update it. If you accept a release that turns out to be bad, nothing can repair your account.”
    • Consent dialog title “Let ChimpDAO update this account?” with the statement that ChimpDAO will be able to change this account’s code, and that Manual can be chosen again.
  • Show the toggle for a Main only when version() >= 2; on version 1 the recorded policy means nothing, the executable on the ledger is the truth, and updates need the holder’s signature.

6.9 Claim-time choice (a card becoming someone’s)

Stock cards may be enrolled Managed. The first time a card is bound to a holder’s account, if its purse’s upgrade_policy() is Managed, ask which they want (“Automatic updates” or “I update it myself”, equal weight, no preselection) and sign it together with the binding:

  • One router batch, signed by the same card: purse.set_owner(account) then purse.set_upgrade_policy(choice); the router is batch(caller = purse, calls) with Call { contract, method: Symbol, args: Vec<Val> }. Then the permissionless apply_upgrade_policy if the decision changed anything.
  • Without a router on the network: set_owner first, then set_upgrade_policy, and tell the user the pair is not atomic.
  • Convergent: read what the chain already says and skip what is done; a resumed ceremony finishes with no chip.
  • Ask only when the purse names itself as owner (pocketOwner == pocketId, minted and held by nobody) and is Managed. A Manual purse has nothing to choose.

7. Order of signing

A recording simulation is how a transaction normally discovers its authorization entries. It fails inside the host’s auth emulation when an authorizer is a custom account whose executable is a fleet reference: on a real host a recording simulation of a Managed Main’s set_upgrade_policy fails with Error(Auth, InvalidAction), with diagnostics host.0.storage.try_borrow_mut failed then previous invocation is missing - no auth data to get. The same call signed first succeeds. So:

  • A purse is always declared and signed before simulation, whatever its policy.
  • A Main is signed first only while its executable is a fleet reference (Managed); a plain-wasm Main is discovered by recording simulation, then each entry is signed.
  • Signing first means declaring the authorization tree (src/chain/auth-tree.ts), signing every entry, and only then simulating in enforce mode. A signed tree can never authorize more than it declares.
  • Never guess: if the executable read fails, stop; falling back to discovery would fail after the user has already approved.
  • Leaving Managed is sign-first too: a signed set_upgrade_policy(Manual) through the fleet reference works, and the permissionless apply_upgrade_policy that follows turns the executable back into a pinned Wasm equal to the factory’s head. While Managed, upgrade(hash) reaches the contract (__check_auth accepts the signer) and is refused with #511.

Whichever order applies, the user reviews the call before the OS passkey sheet or the card tap (the sheet shows no call details).

8. Who pays the fee

No shipped client holds a signing secret. A Cloudflare Worker (signer/ in the terminal repo; signer/README.md) signs the fee for the relayer account and never submits.

  • POST https://chimpdao-signer.tansu-964.workers.dev with JSON {"xdr": "<tx envelope>", "network": "<passphrase>"} returns {"xdr": "<signed envelope>"}. The transaction’s source must be the relayer; one operation; invokeHostFunction (invoke or create contract), extendFootprintTtl or restoreFootprint; fee at most 10 XLM; one signature per caller per 5 s (429 carries retry-after); wasm upload is refused. A native app sends no Origin and needs no CORS entry.
  • There is one relayer per network. Its public key is configuration (VITE_STELLAR_RELAYER_PUBLIC_TESTNET and VITE_STELLAR_RELAYER_PUBLIC_MAINNET in the terminal’s config; the terminal still accepts the old single VITE_STELLAR_RELAYER_PUBLIC). You need it to build transactions and to predict account addresses (§5.8). A client must use the relayer of the network its request names, for the transaction source and for predicting account addresses. Testnet’s is GDZE7UWGO3PS6R6RI6F3XIJLX7WGIEFD3X4YQO4AJH4LS3KDY6LLFXG2; mainnet’s is not created yet. The README of this repo lists them under Keys.
  • Installing wasm is an operator job (make targets), not something a client does.

9. ABI summary

Account (contracts/account), version 2. Authorization column: self = authorized by the account itself, any signer; none = permissionless view or apply.

Function Auth Notes
__constructor(cards: Vec<CardSigner>, passkeys: Vec<PasskeySigner>, factory: Address) n/a ≥ 1 signer total
add_card(CardSigner), remove_card(BytesN<65>) self
add_passkey(PasskeySigner), remove_passkey(BytesN<65>) self
abandon() self clears both sets
cards() -> Vec<CardSigner>, passkeys() -> Vec<PasskeySigner> none
has_card(BytesN<65>) -> bool, has_passkey(BytesN<65>) -> bool none never panic
upgrade(BytesN<32>) self refused while Managed (#511)
update() self no argument; refused while Managed (#511); needs a recorded factory (#516) and a pinned head (#513)
set_upgrade_policy(UpgradePolicy) self
apply_upgrade_policy() none single-shot (#512)
upgrade_policy() -> UpgradePolicy none defaults Manual
set_factory(Address) self once (#514); resets Managed to Manual; emits SEP-50 mint
factory() -> Option<Address>, version() -> u32 none version is 2; the first wasm traps
balance(Address) -> u32, owner_of(u32) -> Address, name(), symbol(), token_uri(u32) none SEP-50, read-only, token id 0 only (#515 otherwise); no transfer

CardSigner { curve: Curve, key: BytesN<65> }. PasskeySigner { credential_id: Bytes, key: BytesN<65>, rp_id_hash: BytesN<32> }. UpgradePolicy = [Symbol("Managed")] or [Symbol("Manual")]. SEP-50: name “Chimp Main account”, symbol “CHIMPMAIN”, token_uri(0) = https://nft.chimpdao.xyz/account/<account C-address>.

Factory (contracts/pocket-factory): fleet(), pocket_wasm_hash(), account_wasm_hash(), get_account(BytesN<65>) -> Option<Address> are views a client uses. The permissionless keepalive refresh() is never called by a client (UPGRADES.md). Admin-only (never called by a client): set_pocket_wasm_hash, set_account_wasm_hash, seed_history(kind, hashes), create_account, upgrade, set_admin.

Purse (contracts/pocket): chip-signed set_owner(Address), set_upgrade_policy(UpgradePolicy), upgrade(BytesN<32>); permissionless apply_upgrade_policy(); views owner(), upgrade_policy(), balance(Address). There is no transfer or sweep: a payment is a plain SAC transfer the host routes to the purse’s __check_auth.

Router (contracts/router): batch(caller: Address, calls: Vec<Call>), Call { args: Vec<Val>, contract: Address, method: Symbol }. It calls caller.require_auth() first, so every leg joins one authorization tree and one signature. No state, no admin, no upgrade path.

10. Errors

A failed call reaches a client as Error(Contract, #N). The codes below are the current contracts’. Mainnet runs older code that uses the numbers from before the renumbering; the terminal still accepts 200 and 201 (invalid signature), 202 (managed), 203 (no code published), 204 (nothing to apply) and 303 (last card) for that reason. Do not branch on a number alone against mainnet. User wording is src/lib/errors.ts.

Code Contract Name Meaning Terminal wording
301 factory MissingWasmHash no Pocket wasm pinned “ChimpDAO has not published this code yet”
401 Pocket InvalidChip
402 Pocket InvalidSignature chip signature did not verify “Card declined”
403 Pocket UpgradeIsManaged upgrade on a purse that follows the fleet “This follows ChimpDAO’s code — switch to Manual first”
404 Pocket MissingWasmHash factory pins nothing “ChimpDAO has not published this code yet”
405 Pocket NothingToApply apply with no decision pending “Nothing to apply — the code already matches your choice”
501 account UnknownCard proof names a key that is not a card (none; the terminal shows “Something went wrong”)
502 account InvalidSignature card signature failed, or a passkey assertion is malformed or binds another payload “Card declined”
503 account DuplicateCard (none)
504 account LastSigner would remove the last signer, card or passkey “That is the only way to sign in to this account — add another first”
505 account NoSigners constructed with no signer (none)
506 account TooManyCards more than 16 (none)
507 account UnknownPasskey “That passkey is not on this account”
508 account DuplicatePasskey key or credential id already listed “That passkey is already on this account”
509 account TooManyPasskeys more than 8 “This account already has as many passkeys as it can hold”
510 account InvalidPasskey credential id empty or longer than 255 bytes “That passkey did not work — try again or use another way to sign in”
511 account UpgradeIsManaged upgrade/update while Managed “This follows ChimpDAO’s code — switch to Manual first”
512 account NothingToApply “Nothing to apply — the code already matches your choice”
513 account MissingWasmHash factory pins no account wasm “ChimpDAO has not published this code yet”
514 account FactoryAlreadySet set_factory twice “This account already knows where its updates come from”
515 account NonExistentToken SEP-50 query for a token other than 0 (none)
516 account NoFactory no factory recorded “This account has not been told where its updates come from — update it again”

A trap (no #N) is what a signature that does not verify, a high-S passkey signature and an out-of-range recovery value produce (§5.7); they fail closed.

Client-side faults the terminal names (no contract code): passkey unsupported, cancelled, timeout (“The passkey prompt timed out — try again”), invalid; “Already up to date”; “That version is not on the network yet — try again later”; “Sent, but the update is not confirmed yet — check again in a moment”; “This app and the network disagree on the account version — update the app”; “This account can no longer be created from this device — start again with a new passkey”.

11. Events and limits

The events of every contract, with their topics and data, are in ARCHITECTURE.md.

An indexer that follows account code changes subscribes to upgrade, update and apply_upgrade_policy: the last is the permissionless switch between Manual and Managed, which nobody signs. A Managed account’s later moves with the fleet emit nothing of its own; they are the factory’s set_*_wasm_hash. The factory’s refresh emits nothing.

Limit Value
Cards per account (MAX_CARDS) 16
Passkeys per account (MAX_PASSKEYS) 3
Credential id (MAX_CREDENTIAL_ID) 1 to 255 bytes
authenticator_data 37 to 512 bytes
client_data_json at most 1024 bytes
Fleet history 16 hashes per component
Transaction build window 60 s; 300 s when the user reviews first
Passkey prompt bounded at 60 s

12. What not to do

  • No app-held signing secret. The fee is paid by the Worker’s relayer; authority is a card or a passkey. A stored account secret key (S…) is exactly what this model replaces.
  • No local storage as a source of truth. Discovery is on-chain (§5.9). A cache is a hint that is always re-verified before a write (§6.4).
  • No new keys. Do not create, derive or enumerate keys to make a flow work. Test with the existing fixtures and the operator’s accounts.
  • No mainnet before the audit and an explicit operator go-ahead (§2).
  • Do not use an SDK that cannot decode the network’s ledger header (§2): testnet is on protocol 30 and the JavaScript SDK before 17.4.0 throws on getLatestLedger. Prove the SDK against the live RPC before building a flow on it, or read only the sequence from the raw response.
  • Never shorten an address in a review. Show a contract or factory address in full wherever a user approves a call; the factory address in set_factory especially.
  • Sign first, then simulate wherever §7 says so. Never fall back to discovery on a failed read.
  • Peers. Do not rank passkeys above or below cards, label one “recovery” or “backup”, or nudge a holder toward either.
  • Do not rely on a passkey for a purse. A purse accepts its chip only; there is no path.
  • Do not hash on top of the host payload for the account, and do not add an app nonce.
  • Do not widen rpId or change it. It is permanent per credential.

13. Verified and not verified on a real network

Everything above was derived from the Rust sources and the terminal code, then exercised on the testnet e2e fleet (§2) on 2026-11-06 and 2026-11-07. Mainnet was never touched.

Verified on testnet

  • The fleet record. The factory was upgraded in place and fleet() answers; its pinned Pocket read back as its own history (the in-place backfill); seed_history with its JSON arguments (--kind '"Account"' --wasm_hashes '["<hash>","<hash>"]') works with the real Stellar CLI and moves the epoch; the account head was pinned with set_account_wasm_hash and fleet() reads back the history in §2. The Makefile targets that did this were exercised: contract_upgrade_factory (prints the previous hash it can be rolled back to), contract_seed_history and contract_push_account.
  • The account canary. A throwaway account deployed on 044275ac… at a random salt was upgraded to 4f2906b5… with the card wire that already-deployed clients use, signed one call afterwards (__check_auth accepted the card), and answered version() = 2. The pin followed it.
  • The v1 hop as one router batch. [account.upgrade(4f2906b5…), account.set_factory(factory)] under one card signature landed (tx 48d39c4b59eaa0efa74baab5030fe3e9c34361e459b8bc17ed92da45393e7a80); the account then ran 4f2906b5…, answered version() = 2 and factory() = the e2e factory.
  • A Managed Main on a real host. Opt-in and apply_upgrade_policy turned the executable into a fleet reference to the factory’s "account" entry. A recording simulation of the next self-authorized call fails with Error(Auth, InvalidAction) (host.0.storage.try_borrow_mut failed); upgrade(hash) is refused with #511; a call signed first works; Manual plus apply_upgrade_policy pins a Wasm equal to the factory’s head again (§7).
  • update(). It installs exactly the hash the stored factory pins (checked by re-pinning a disposable factory’s head to an installed Pocket wasm and reading the executable back), reads the factory before authorizing, reinstalls harmlessly when already current, and fails with Error(WasmVm, MissingValue) on code without it (§6.6).
  • Passkeys end to end. With a CDP virtual authenticator (Chromium, ctap2, internal, resident key, user verification on) on the live e2e fleet: create an account with a passkey and no card, see that its only sign-in method is a passkey and cannot be removed, sign out and back in from the passkey alone, pay from the Main with the passkey, add a card with the passkey approving it and remove it the same way, add a second passkey and have either remove the other. Six scenarios, all pass.
  • Protocol 30. The SDK finding in §2 was found on this network, by the canary, and fixed by @stellar/stellar-sdk 17.4.0.

Not verified

  • A real device and an OS passkey sheet. Only a virtual authenticator has signed. An iPhone’s native rawClientDataJSON ordering is unknown. The contract insists on the exact prefix {"type":"webauthn.get","challenge":". Desktop browsers, the virtual authenticator and the test vectors follow it. Capture a real device’s value before building on it (the iOS brief makes this a gate).
  • restoreWasm (a permissionless restoreFootprint for an archived wasm entry) and the detection of an archived entry in wasmState (it assumes getLedgerEntries returns the entry with a lapsed liveUntilLedgerSeq; if the RPC omits archived entries, restorable code reads as “missing”). Several testnet instances read liveUntil 0 from the RPC, which the helper reports as archived; that reading has not been confirmed by restoring one.
  • The claim-time batch (set_owner and set_upgrade_policy in one router batch) and the apply after it, on a network.
  • A release-container build. Every testnet hash above is a local build. The reproducible build, its hashes and their comparison with the Stellar Registry (RELEASE.md) have not been run for these wasm.
  • Legacy mode on mainnet (a factory that predates fleet()), by design untouched.

Conformance checklist

A client is in step with this document when:

  1. It reproduces every vector in §4 byte for byte (the three passkey constants from the key, authenticator data, client data and signature given there).
  2. It builds the §5.8 account address and a constructor argument list equal to TERMINAL_VEC_PASSKEYS for the vector passkey.
  3. For a real authenticator it produces a low-S raw signature, a clientDataJSON prefix match, and an rp_id_hash match before it builds a transaction.
  4. readFleet, updateStatus and the idempotent update (§6) pass the same truth table as src/chain/updates.test.ts and src/chain/update-run.test.ts.
  5. It shows the factory address in full in the set_factory review and takes it from its own configuration.
  6. Its SDK reads the live network’s latest ledger sequence without throwing (§2, protocol 30).
  7. After a purse update it calls apply_upgrade_policy once and accepts #405 (§6.7).