Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 21 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ Network: **Testnet** (`Test SDF Network ; September 2015`)

Treasuries are normally created through the factory's `deploy_treasury`. The treasury above is one reference deployment kept for verification; both wasm hashes are reproducible from `stellar contract fetch`.

> The factory listed above predates permissionless deployment and the constructor: it still requires its original deployer to sign every `deploy_treasury`, and it was bound to its wasm hash by a separate `initialize` call. The current source does neither, and has not been deployed yet.

## Quick start

### Prerequisites
Expand All @@ -48,7 +50,7 @@ Treasuries are normally created through the factory's `deploy_treasury`. The tre
# Compile the contracts to wasm
stellar contract build

# Run the test suite (47 treasury + 11 factory = 58 tests)
# Run the test suite (47 treasury + 17 factory = 64 tests)
cargo test
```

Expand All @@ -60,7 +62,8 @@ The scripts under `scripts/` deploy and exercise the contracts end to end. Run t
# 1. Create and fund testnet identities (deployer, admin, approvers, requester)
./scripts/setup-testnet.sh

# 2. Build, upload the treasury wasm, deploy the factory, and initialize it.
# 2. Build, upload the treasury wasm, and deploy the factory with that hash as a
# constructor argument (one step; there is no separate initialize).
# Writes the resulting factory address + treasury wasm hash to scripts/.env
./scripts/deploy.sh

Expand All @@ -70,7 +73,7 @@ The scripts under `scripts/` deploy and exercise the contracts end to end. Run t
./scripts/verify.sh deploy-treasury
```

The factory must be initialized with the treasury's wasm hash before it can deploy treasuries — `deploy.sh` handles this ordering (upload treasury wasm → deploy factory → `initialize`).
The treasury wasm must be uploaded before the factory is deployed, because its hash is a constructor argument: `deploy.sh` uploads the treasury wasm, then deploys the factory with `-- --wasm_hash <hash>`. The hash is set in the same transaction that creates the factory, so no one can set a different one first.

## Architecture

Expand All @@ -81,7 +84,7 @@ contracts/
└── test-token/ # Minimal mintable token used only in tests and verification
scripts/
├── setup-testnet.sh # Create + fund testnet identities
├── deploy.sh # Build, upload, deploy, initialize
├── deploy.sh # Build, upload, deploy (wasm hash via constructor)
└── verify.sh # Exercise factory read/deploy paths on-chain
```

Expand All @@ -99,7 +102,7 @@ Caps are lifetime totals: a category tracks cumulative `spent` against its `cap`

### Factory

The factory is initialized once with the treasury wasm hash. Each `deploy_treasury` call deploys a treasury at a deterministic address (salted by a sequential org id), initializes it, and records an on-chain org registry entry. Reads are available through `get_org`, `get_org_count`, and the paginated `get_orgs`.
The factory's constructor binds it to the treasury wasm hash when the factory is deployed. Each `deploy_treasury` call deploys a treasury at a deterministic address (salted by a sequential org id), initializes it, and records an on-chain org registry entry. Reads are available through `get_org`, `get_org_count`, and the paginated `get_orgs`.

## Contract reference

Expand Down Expand Up @@ -202,17 +205,21 @@ struct Request {

### Factory

Deploys treasuries from a single uploaded treasury wasm and records each as an org. Deploy authority is a single `deployer` account.
Deploys treasuries from a single uploaded treasury wasm and records each as an org. Org creation is permissionless: any account can deploy a treasury for an org it administers by signing as that org's `admin`. There is no factory-level deployer or operator.

```rust
fn initialize(deployer: Address, wasm_hash: BytesN<32>) // auth: deployer
fn deploy_treasury(name: String, admin: Address, approvers: Vec<Address>, threshold: u32, token: Address) -> u32 // auth: deployer + admin; returns org_id
fn __constructor(wasm_hash: BytesN<32>) // runs once, when the factory is deployed; not callable afterwards
fn deploy_treasury(name: String, admin: Address, approvers: Vec<Address>, threshold: u32, token: Address) -> u32 // auth: admin; per-admin cooldown; returns org_id
fn get_org(org_id: u32) -> OrgRecord
fn get_org_count() -> u32
fn get_orgs(start: u32, limit: u32) -> Vec<OrgRecord> // limit capped at 50
```

`deploy_treasury` requires **both** the `deployer` and the new treasury's `admin` to sign: the admin signature is needed because the factory immediately sub-calls the treasury's `initialize`, which itself requires `admin` auth. The org id doubles as the deploy salt, so every treasury address is deterministic.
`deploy_treasury` requires only the new treasury's `admin` to sign. That signature also covers the factory's sub-call to the treasury's `initialize`, which itself requires `admin` auth. The org id doubles as the deploy salt, so every treasury address is deterministic.

**Spam limit:** each `admin` address can deploy at most one org per `DEPLOY_COOLDOWN_LEDGERS` (720 ledgers, about an hour). A deploy that fails does not start the cooldown. The limit throttles a single admin identity; it does not stop someone who uses many admin accounts. Every deploy also costs the caller network fees and storage rent.

**Deployment:** the treasury wasm hash is a constructor argument (`stellar contract deploy … -- --wasm_hash <hash>`), so it is set in the same transaction that creates the factory. There is no `initialize` step, and nothing can set or replace the hash afterwards. The constructor does not check that the hash has been uploaded, so upload the treasury wasm first.

**Data types:**

Expand All @@ -226,17 +233,18 @@ struct OrgRecord { name: String, treasury: Address, admin: Address, created_ledg
|-------|--------|------|
| `TreasuryDeployed` | `org_id` | `name`, `treasury`, `admin` |

> `initialize` does not currently emit an event; adding `FactoryInitialized` is tracked in [issue #2](https://github.com/Ch-rter/contract/issues/2).
> Creating the factory does not emit an event; [issue #2](https://github.com/Ch-rter/contract/issues/2) tracks adding one (it predates the constructor and still refers to `initialize`).

**Errors:**

| Code | Name | Raised when |
|------|------|-------------|
| 1 | `NotInitialized` | `deploy_treasury` is called before `initialize` |
| 2 | `AlreadyInitialized` | `initialize` is called a second time |
| 3 | `NotDeployer` | reserved — deploy authority is enforced via `require_auth` on the stored deployer |
| 1 | — | retired (was `NotInitialized`; the constructor sets the wasm hash, so a factory can't be uninitialized); not reused |
| 2 | — | retired (was `AlreadyInitialized`; there is no `initialize` to call twice); not reused |
| 3 | — | retired (was `NotDeployer`, removed when deployment became permissionless); not reused |
| 4 | `OrgNotFound` | `get_org` is called with an unknown id |
| 5 | `TreasuryInitFailed` | the new treasury's `initialize` fails (e.g. invalid threshold); the treasury's own error code is not passed through |
| 6 | `DeployCooldown` | the same `admin` deploys again less than `DEPLOY_COOLDOWN_LEDGERS` after its last successful deploy |

### Test token

Expand Down
2 changes: 1 addition & 1 deletion SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ Out of scope:

- `contracts/test-token`, which is a minimal token used only for tests and
on-chain verification and is not intended for production use.
- Issues that require a compromised deployer key, admin key, or approver key.
- Issues that require a compromised admin key or approver key.
Charter's security model assumes these signers are honest and their keys are
kept secret; loss or compromise of a threshold of keys is outside the trust
model.
Expand Down
13 changes: 7 additions & 6 deletions contracts/factory/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,16 @@ use soroban_sdk::contracterror;
#[contracterror]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Error {
/// Factory not initialized: `initialize` has not been called.
NotInitialized = 1,
/// Factory already initialized.
AlreadyInitialized = 2,
/// Caller is not the deployer authorized to deploy treasuries.
NotDeployer = 3,
// 1 was `NotInitialized` and 2 was `AlreadyInitialized`, retired when the
// wasm hash moved into the constructor: a factory can no longer exist
// uninitialized or be initialized twice. Do not reuse either code.
// 3 was `NotDeployer`, retired when deployment became permissionless.
// Do not reuse it: existing clients may still decode 3 as that error.
/// Org id does not exist.
OrgNotFound = 4,
/// The new treasury's `initialize` sub-call failed. Wraps any treasury
/// error so treasury codes never surface as factory codes.
TreasuryInitFailed = 5,
/// The admin deployed an org less than `DEPLOY_COOLDOWN_LEDGERS` ago.
DeployCooldown = 6,
}
87 changes: 55 additions & 32 deletions contracts/factory/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,33 +24,38 @@ use treasury_wasm::Client as TreasuryContractClient;

const MAX_ORG_LIMIT: u32 = 50;

/// Minimum number of ledgers between two successful `deploy_treasury` calls
/// by the same admin (about one hour at ~5 s per ledger).
pub const DEPLOY_COOLDOWN_LEDGERS: u32 = 720;

/// Charter factory contract.
///
/// Deploys and tracks treasury contracts from an uploaded treasury wasm. The
/// deployer authorizes every deployment; org ids are assigned sequentially and
/// used as the deploy salt so addresses are deterministic.
/// Deploys and tracks treasury contracts from an uploaded treasury wasm, whose
/// hash is fixed by the constructor when the factory itself is created.
/// Deployment is permissionless: any account can create an org by signing as
/// that org's own `admin`, and each admin can deploy at most once per
/// `DEPLOY_COOLDOWN_LEDGERS`. Org ids are assigned sequentially and used as the
/// deploy salt so addresses are deterministic.
#[contract]
pub struct FactoryContract;

#[contractimpl]
impl FactoryContract {
/// Initializes the factory.
/// Creates the factory and binds it to the treasury wasm it deploys.
///
/// Runs exactly once, inside the transaction that creates the contract, so
/// the wasm hash is set atomically at deploy. The host rejects any later
/// call to `__constructor`, and no other function writes the hash, so
/// nobody can set or replace it after deployment.
///
/// # Arguments
/// * `deployer` - The address authorized to deploy treasuries.
/// * `wasm_hash` - Hash of the treasury wasm to deploy.
/// * `wasm_hash` - Hash of the treasury wasm to deploy. Upload that wasm
/// first; the constructor does not check that it exists.
///
/// # Auth
/// * Requires `deployer.require_auth()`.
///
/// # Panics
/// * `Error::AlreadyInitialized` if already initialized.
pub fn initialize(env: Env, deployer: Address, wasm_hash: BytesN<32>) {
deployer.require_auth();
if env.storage().instance().has(&DataKey::Deployer) {
panic_with_error!(&env, Error::AlreadyInitialized);
}
env.storage().instance().set(&DataKey::Deployer, &deployer);
/// * None. Whoever creates the contract chooses the hash, as part of the
/// creation itself.
pub fn __constructor(env: Env, wasm_hash: BytesN<32>) {
env.storage().instance().set(&DataKey::WasmHash, &wasm_hash);
env.storage().instance().set(&DataKey::OrgCount, &0u32);
Self::extend_instance_ttl(&env);
Expand All @@ -74,13 +79,17 @@ impl FactoryContract {
/// * The newly assigned org id.
///
/// # Auth
/// * Requires the stored `deployer` to sign (`Error::NotDeployer`
/// otherwise).
/// * Requires `admin` to sign so the treasury's `initialize` sub-call
/// succeeds on-chain.
/// * Requires `admin` to sign, and nothing else: any account can create an
/// org it administers. The same signature covers the treasury's
/// `initialize` sub-call, which also requires `admin`.
///
/// # Rate limit
/// * Each `admin` can deploy at most once per `DEPLOY_COOLDOWN_LEDGERS`.
/// A deploy that fails does not start the cooldown.
///
/// # Panics
/// * `Error::NotInitialized` if the factory was not initialized.
/// * `Error::DeployCooldown` if `admin` deployed an org less than
/// `DEPLOY_COOLDOWN_LEDGERS` ledgers ago.
/// * `Error::TreasuryInitFailed` if the treasury's `initialize` fails for
/// any reason (e.g. an invalid threshold). The treasury's own error code
/// is not propagated.
Expand All @@ -92,21 +101,23 @@ impl FactoryContract {
threshold: u32,
token: Address,
) -> u32 {
let deployer: Address = env
.storage()
.instance()
.get(&DataKey::Deployer)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
deployer.require_auth();
// The treasury's `initialize` calls `admin.require_auth()`. Requiring
// the admin's signature at the top invocation ties it to the root call
// so the sub-call auth succeeds.
admin.require_auth();
// Always present: the constructor sets it when the contract is created.
let wasm_hash: BytesN<32> = env
.storage()
.instance()
.get(&DataKey::WasmHash)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized));
.unwrap();
// The org's own admin is the only required signer. The treasury's
// `initialize` also calls `admin.require_auth()`; requiring it at the
// top invocation ties it to the root call so the sub-call auth succeeds.
admin.require_auth();

let cooldown_key = DataKey::LastDeploy(admin.clone());
if let Some(last_deploy) = env.storage().temporary().get::<_, u32>(&cooldown_key) {
if env.ledger().sequence() < last_deploy.saturating_add(DEPLOY_COOLDOWN_LEDGERS) {
panic_with_error!(&env, Error::DeployCooldown);
}
}

let org_id: u32 = env
.storage()
Expand Down Expand Up @@ -138,6 +149,18 @@ impl FactoryContract {
_ => panic_with_error!(&env, Error::TreasuryInitFailed),
}

// Start this admin's cooldown. Only reached on success: a failed
// deploy panics and reverts, so it never locks the admin out. The
// entry is temporary because it only has to outlive the window.
env.storage()
.temporary()
.set(&cooldown_key, &env.ledger().sequence());
env.storage().temporary().extend_ttl(
&cooldown_key,
DEPLOY_COOLDOWN_LEDGERS,
DEPLOY_COOLDOWN_LEDGERS,
);

env.storage().instance().set(&DataKey::OrgCount, &org_id);
env.storage().persistent().set(
&DataKey::Org(org_id),
Expand Down
Loading
Loading