# Run a treasury that follows a member account's signers

This recipe builds a treasury whose spending rule never changes but whose signers can. You create a contract account with one function. The function pays from the treasury when two of the three signers named by the multisig rule of a member user account, X, sign the payment, as X stands in the block the transaction is proved against. When X installs a new signer set, the treasury follows it without being redeployed. This is an example: unaudited and not for real funds.

## How it works

1. X installs a 2-of-3 multisig rule. The rule's entry in X's rule set commits the signers' addresses, a salt and a private blinder, and X's administration rule can replace that entry later.
2. You create the treasury as a contract account. Its one function's configuration commits X's address and the verification key hash of X's multisig rule, under a salt that hides both. A contract account can never be updated, so these terms are fixed for good.
3. To spend, the app asks a node for X's account row and the treasury's row in one snapshot. Every proof names one recent PCASH block, and the function opens X's row in that block's account tree.
4. The function opens X's multisig entry inside that row's rule set, using the salt, blinder and path that X's wallet supplies. The entry gives it X's current signers.
5. Two of those signers sign the transaction's action commitment, a hash of the exact transaction that also names the chain, together with the treasury's address. The function checks both signatures and returns its approval to the protocol kernel, which accepts it only for the treasury contract it authenticated.

## The circuit

The treasury's configuration names X and the multisig rule whose entry names the signers. Everything else the function reads comes from the chain or X's wallet.

```rust examples/delegated-treasury/src/main.nr
// The treasury's fixed terms: the member account it follows and the
// application whose entry in that account names the signers. The salt hides
// both from readers of the published contract body.
pub struct Configuration {
    pub configuration_salt: Field,
    pub member_address: Field,
    pub member_rule_vk_hash: Field,
}

pub fn treasury_configuration_commitment(configuration: Configuration) -> Field {
    pcash_hash([
        REFERENCE_CONFIGURATION_DOMAIN,
        configuration.configuration_salt,
        configuration.member_address,
        configuration.member_rule_vk_hash,
    ])
}
```

The function recomputes X's multisig configuration commitment from the signers it is given. The format must match the multisig rule exactly; a test pins it to that rule's published test vector.

```rust examples/delegated-treasury/src/main.nr
// The multisig rule's configuration commitment:
// poseidon(REFERENCE_CONFIGURATION_DOMAIN, salt, K, signerAddress_0, ..., signerAddress_(N-1)).
pub fn member_rule_configuration_commitment(
    configuration_salt: Field,
    signer_addresses: [Field; N],
) -> Field {
    let mut preimage: [Field; N + 3] = [0; N + 3];
    preimage[0] = REFERENCE_CONFIGURATION_DOMAIN;
    preimage[1] = configuration_salt;
    preimage[2] = K as Field;
    for i in 0..N {
        preimage[i + 3] = signer_addresses[i];
    }
    pcash_hash(preimage)
}
```

This is the core check. It rebuilds X's rule entry from the configured verification key hash and the given signers, requires it in X's rule set, then requires X's row in the recent block's account tree. An entry naming signers X has removed is no longer in X's rule set, so it fails here.

```rust examples/delegated-treasury/src/main.nr
// X's row, holding an entry of the configured application that names
// `signer_addresses`, is in the account tree of the recent block.
fn assert_member_names_signers(
    recent_pcash_block_hash: Field,
    block_header_state_siblings: [Field; BLOCK_HEADER_TREE_DEPTH],
    state_account_siblings: [Field; STATE_TREE_DEPTH],
    configuration: Configuration,
    member: MemberAccount,
    member_rule: MemberRule,
    signer_addresses: [Field; N],
) {
    let entry = account_rule_entry_commitment(
        configuration.member_rule_vk_hash,
        member_rule_configuration_commitment(member_rule.configuration_salt, signer_addresses),
        member_rule.commitment_blinder,
    );
    assert(
        binary_root_from_index(
            entry,
            member_rule.witness.entry_index as Field,
            member_rule.witness.siblings,
        )
            == member.rule_set_commitment,
        "signer entry must be in the member's rule set",
    );
    let leaf = account_state_commitment(
        configuration.member_address,
        member.nullifier_key_commitment,
        member.rule_set_commitment,
        ACCOUNT_KIND_USER,
        member.account_revision,
        member.receive_key_hash,
    );
    let account_state_root =
        binary_root_from_index(leaf, member.witness.leaf_index, member.witness.siblings);
    let state_root = state_root_from_opening(
        account_state_root,
        STATE_KEY_ACCOUNT_STATE_ROOT,
        state_account_siblings,
    );
    assert(
        block_hash_from_opening(
            state_root,
            BLOCK_HEADER_KEY_STATE_ROOT,
            block_header_state_siblings,
        )
            == recent_pcash_block_hash,
        "member row must be in the recent block's account tree",
    );
}
```

The signers must be sorted and distinct, as in the multisig rule, so two approvals at distinct positions come from two different keys.

```rust examples/delegated-treasury/src/main.nr
// The signers' addresses, which must be sorted and distinct as in the
// multisig rule, so K approvals at distinct indices come from K keys.
fn signer_addresses(signers: [Secp256k1PubKey; N]) -> [Field; N] {
    let mut addresses: [Field; N] = [0; N];
    for i in 0..N {
        addresses[i] = signers[i].ethereum_address();
    }
    for i in 1..N {
        assert(addresses[i - 1].lt(addresses[i]), "signers must be sorted ascending and distinct");
    }
    addresses
}
```

Each signer signs the multisig rule's approval digest over the action commitment and the treasury's address, so an approval of one of X's own transactions does not approve a treasury payment.

```rust examples/delegated-treasury/src/main.nr
// What each signer signs: the multisig rule's approval digest, naming the
// treasury, so an approval for X's own action does not approve the treasury's.
pub fn approval_digest(action_commitment: Field, treasury_address: Field) -> Field {
    pcash_hash(
        [REFERENCE_MULTISIG_APPROVAL_DOMAIN, action_commitment, treasury_address],
    )
}
```

```rust examples/delegated-treasury/src/main.nr
fn assert_threshold(digest: Field, signers: [Secp256k1PubKey; N], approvals: [Approval; K]) {
    let message: [u8; 32] = digest.to_be_bytes();
    let mut used: [u32; K] = [0; K];
    for a in 0..K {
        let index = signer_index_in_range(approvals[a].signer_index);
        Signature { signature: approvals[a].signature }.verify(message, signers[index]);
        used[a] = index;
    }
    for i in 0..K {
        for j in 0..i {
            assert(used[j] != used[i], "approval signers must be distinct");
        }
    }
}
```

The function serves both ways a contract can spend: paying its own fee, or having another account pay it. The action commitment names which, and the signers sign it, so the role is theirs to choose. The function returns that action with the treasury's authorization and the block it read.

```rust examples/delegated-treasury/src/main.nr
    let action_commitment = contract_action_commitment(
        pcash_chain_id,
        private_value_commitment(private_value),
        fee_paid,
    );
    assert_threshold(
        approval_digest(action_commitment, address),
        signers,
        approvals,
    );
    rule_statement(
        authorization_commitment(address, treasury_configuration_commitment(configuration)),
        action_commitment,
        recent_pcash_block_hash,
        event_entry,
    )
```

<details><summary>The whole circuit</summary>

```rust examples/delegated-treasury/src/main.nr
// Approves a treasury transfer signed by 2 of the 3 signers member account X currently names.
// Example only: unaudited, not for real funds.

// The treasury is a contract account whose configuration names a member user
// account X and the multisig rule X installs. The function opens X's account
// row in the recent block's account tree, opens X's installed multisig entry
// from that row's rule set, and requires two of the entry's signers to sign
// this action and the treasury's address. The contract never changes; X's
// administration rule changes the signers by installing another entry.

use pcash_protocol::authorization::account::{
    ACCOUNT_KIND_USER, account_rule_entry_commitment, account_state_commitment,
};
use pcash_protocol::authorization::statement::{
    authorization_commitment, contract_action_commitment, rule_statement, RULE_STATEMENT_LENGTH,
};
use pcash_protocol::ledger::private_value::{
    private_value_commitment, SmallPrivateValue as PrivateValue,
};
use pcash_protocol::primitives::hash::pcash_hash;
use pcash_protocol::primitives::params::{BLOCK_HEADER_TREE_DEPTH, STATE_TREE_DEPTH};
use pcash_protocol::primitives::types::{AccountRuleMembershipWitness, MerkleWitness};
use pcash_protocol::state::block::{
    block_hash_from_opening, BLOCK_HEADER_KEY_STATE_ROOT, STATE_KEY_ACCOUNT_STATE_ROOT,
    state_root_from_opening,
};
use pcash_protocol::state::merkle::binary_root_from_index;
use reference_rule_common::generated::reference_rule_constants::{
    REFERENCE_CONFIGURATION_DOMAIN, REFERENCE_MULTISIG_APPROVAL_DOMAIN,
};
use signature_common::secp256k1::{Secp256k1PubKey, Signature};

// The signer count and threshold of the repository's multisig rule
// (circuits/fixtures/multisig), whose configuration format X's entry uses.
global N: u32 = 3;
global K: u32 = 2;

// The treasury's fixed terms: the member account it follows and the
// application whose entry in that account names the signers. The salt hides
// both from readers of the published contract body.
pub struct Configuration {
    pub configuration_salt: Field,
    pub member_address: Field,
    pub member_rule_vk_hash: Field,
}

pub fn treasury_configuration_commitment(configuration: Configuration) -> Field {
    pcash_hash([
        REFERENCE_CONFIGURATION_DOMAIN,
        configuration.configuration_salt,
        configuration.member_address,
        configuration.member_rule_vk_hash,
    ])
}

// The multisig rule's configuration commitment:
// poseidon(REFERENCE_CONFIGURATION_DOMAIN, salt, K, signerAddress_0, ..., signerAddress_(N-1)).
pub fn member_rule_configuration_commitment(
    configuration_salt: Field,
    signer_addresses: [Field; N],
) -> Field {
    let mut preimage: [Field; N + 3] = [0; N + 3];
    preimage[0] = REFERENCE_CONFIGURATION_DOMAIN;
    preimage[1] = configuration_salt;
    preimage[2] = K as Field;
    for i in 0..N {
        preimage[i + 3] = signer_addresses[i];
    }
    pcash_hash(preimage)
}

// What each signer signs: the multisig rule's approval digest, naming the
// treasury, so an approval for X's own action does not approve the treasury's.
pub fn approval_digest(action_commitment: Field, treasury_address: Field) -> Field {
    pcash_hash(
        [REFERENCE_MULTISIG_APPROVAL_DOMAIN, action_commitment, treasury_address],
    )
}

// X's account row at the recent block, as the node serves it. The address
// comes from the treasury's configuration.
pub struct MemberAccount {
    pub nullifier_key_commitment: Field,
    pub rule_set_commitment: Field,
    pub account_revision: Field,
    pub receive_key_hash: Field,
    pub witness: MerkleWitness,
}

// X's multisig entry. Only X's wallet holds the salt, the blinder and the
// rule-set path.
pub struct MemberRule {
    pub configuration_salt: Field,
    pub commitment_blinder: Field,
    pub witness: AccountRuleMembershipWitness,
}

pub struct Approval {
    pub signer_index: Field,
    pub signature: [u8; 64],
}

// X's row, holding an entry of the configured application that names
// `signer_addresses`, is in the account tree of the recent block.
fn assert_member_names_signers(
    recent_pcash_block_hash: Field,
    block_header_state_siblings: [Field; BLOCK_HEADER_TREE_DEPTH],
    state_account_siblings: [Field; STATE_TREE_DEPTH],
    configuration: Configuration,
    member: MemberAccount,
    member_rule: MemberRule,
    signer_addresses: [Field; N],
) {
    let entry = account_rule_entry_commitment(
        configuration.member_rule_vk_hash,
        member_rule_configuration_commitment(member_rule.configuration_salt, signer_addresses),
        member_rule.commitment_blinder,
    );
    assert(
        binary_root_from_index(
            entry,
            member_rule.witness.entry_index as Field,
            member_rule.witness.siblings,
        )
            == member.rule_set_commitment,
        "signer entry must be in the member's rule set",
    );
    let leaf = account_state_commitment(
        configuration.member_address,
        member.nullifier_key_commitment,
        member.rule_set_commitment,
        ACCOUNT_KIND_USER,
        member.account_revision,
        member.receive_key_hash,
    );
    let account_state_root =
        binary_root_from_index(leaf, member.witness.leaf_index, member.witness.siblings);
    let state_root = state_root_from_opening(
        account_state_root,
        STATE_KEY_ACCOUNT_STATE_ROOT,
        state_account_siblings,
    );
    assert(
        block_hash_from_opening(
            state_root,
            BLOCK_HEADER_KEY_STATE_ROOT,
            block_header_state_siblings,
        )
            == recent_pcash_block_hash,
        "member row must be in the recent block's account tree",
    );
}

// The signers' addresses, which must be sorted and distinct as in the
// multisig rule, so K approvals at distinct indices come from K keys.
fn signer_addresses(signers: [Secp256k1PubKey; N]) -> [Field; N] {
    let mut addresses: [Field; N] = [0; N];
    for i in 0..N {
        addresses[i] = signers[i].ethereum_address();
    }
    for i in 1..N {
        assert(addresses[i - 1].lt(addresses[i]), "signers must be sorted ascending and distinct");
    }
    addresses
}

fn assert_threshold(digest: Field, signers: [Secp256k1PubKey; N], approvals: [Approval; K]) {
    let message: [u8; 32] = digest.to_be_bytes();
    let mut used: [u32; K] = [0; K];
    for a in 0..K {
        let index = signer_index_in_range(approvals[a].signer_index);
        Signature { signature: approvals[a].signature }.verify(message, signers[index]);
        used[a] = index;
    }
    for i in 0..K {
        for j in 0..i {
            assert(used[j] != used[i], "approval signers must be distinct");
        }
    }
}

fn signer_index_in_range(signer_index: Field) -> u32 {
    let mut selected: u32 = 0;
    let mut is_valid = false;
    for i in 0..N {
        if signer_index == i as Field {
            selected = i;
            is_valid = true;
        }
    }
    assert(is_valid, "signer index must be below the signer count");
    selected
}

// A function cannot derive its own address, which hashes this function's
// key, so it takes `address` as a witness; the kernel compares the returned
// authorization commitment with the contract it authenticated. `fee_paid`
// selects the transfer or the sponsored-transfer role, and the signers sign
// the action commitment, which names the role.
fn main(
    pcash_chain_id: Field,
    recent_pcash_block_hash: Field,
    address: Field,
    fee_paid: bool,
    configuration: Configuration,
    private_value: PrivateValue,
    block_header_state_siblings: [Field; BLOCK_HEADER_TREE_DEPTH],
    state_account_siblings: [Field; STATE_TREE_DEPTH],
    member: MemberAccount,
    member_rule: MemberRule,
    signers: [Secp256k1PubKey; N],
    approvals: [Approval; K],
    event_entry: Field,
) -> return_data [Field; RULE_STATEMENT_LENGTH] {
    assert_member_names_signers(
        recent_pcash_block_hash,
        block_header_state_siblings,
        state_account_siblings,
        configuration,
        member,
        member_rule,
        signer_addresses(signers),
    );
    let action_commitment = contract_action_commitment(
        pcash_chain_id,
        private_value_commitment(private_value),
        fee_paid,
    );
    assert_threshold(
        approval_digest(action_commitment, address),
        signers,
        approvals,
    );
    rule_statement(
        authorization_commitment(address, treasury_configuration_commitment(configuration)),
        action_commitment,
        recent_pcash_block_hash,
        event_entry,
    )
}

mod tests {
    use super::{
        Approval, Configuration, main, member_rule_configuration_commitment, MemberAccount,
        MemberRule, N, treasury_configuration_commitment,
    };
    use pcash_protocol::authorization::account::{
        ACCOUNT_KIND_USER, account_rule_entry_commitment, account_state_commitment,
    };
    use pcash_protocol::authorization::statement::{
        assert_rule_statement, authorization_commitment, RULE_STATEMENT_LENGTH,
        transfer_action_commitment,
    };
    use pcash_protocol::ledger::private_value::{
        private_value_commitment, SmallPrivateValue as PrivateValue,
    };
    use pcash_protocol::primitives::params::MERKLE_DEPTH;
    use pcash_protocol::primitives::types::{AccountRuleMembershipWitness, MerkleWitness};
    use pcash_protocol::state::block::{
        block_hash_from_opening, BLOCK_HEADER_KEY_STATE_ROOT, STATE_KEY_ACCOUNT_STATE_ROOT,
        state_root_from_opening,
    };
    use pcash_protocol::state::merkle::binary_root_from_index;
    use reference_rule_common::test_support::small_transaction;
    use signature_common::secp256k1::Secp256k1PubKey;

    global CHAIN_ID: Field = 7;
    global TREASURY: Field = 0x7e45;
    global MEMBER: Field = 0xa11ce;
    global MEMBER_RULE_VK_HASH: Field = 0x5555;
    global EVENT_ENTRY: Field = 0xe7;
    global HEADER_SIBLINGS: [Field; 4] = [1, 2, 3, 4];
    global STATE_SIBLINGS: [Field; 4] = [5, 6, 7, 8];

    fn configuration() -> Configuration {
        Configuration {
            configuration_salt: 0x51,
            member_address: MEMBER,
            member_rule_vk_hash: MEMBER_RULE_VK_HASH,
        }
    }

    // X at `revision`, with a multisig entry naming `signer_addresses` at
    // rule index 3, and the recent block hash that commits that row.
    fn member_state(
        signer_addresses: [Field; N],
        revision: Field,
    ) -> (Field, MemberAccount, MemberRule) {
        let rule = MemberRule {
            configuration_salt: 0x52,
            commitment_blinder: 0x53,
            witness: AccountRuleMembershipWitness {
                entry_index: 3,
                siblings: [0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28],
            },
        };
        let entry = account_rule_entry_commitment(
            MEMBER_RULE_VK_HASH,
            member_rule_configuration_commitment(rule.configuration_salt, signer_addresses),
            rule.commitment_blinder,
        );
        let account = MemberAccount {
            nullifier_key_commitment: 0x6b,
            rule_set_commitment: binary_root_from_index(entry, 3, rule.witness.siblings),
            account_revision: revision,
            receive_key_hash: 0,
            witness: MerkleWitness { leaf_index: 5, siblings: [0x31; MERKLE_DEPTH] },
        };
        let leaf = account_state_commitment(
            MEMBER,
            account.nullifier_key_commitment,
            account.rule_set_commitment,
            ACCOUNT_KIND_USER,
            revision,
            0,
        );
        let state_root = state_root_from_opening(
            binary_root_from_index(leaf, 5, account.witness.siblings),
            STATE_KEY_ACCOUNT_STATE_ROOT,
            STATE_SIBLINGS,
        );
        let block =
            block_hash_from_opening(state_root, BLOCK_HEADER_KEY_STATE_ROOT, HEADER_SIBLINGS);
        (block, account, rule)
    }

    // Four signers in ascending address order, and A's, B's and D's signatures
    // over the approval digest of `transaction()` for TREASURY on CHAIN_ID.
    global SIGNER_A: Secp256k1PubKey = Secp256k1PubKey {
        x: [
            0x6b, 0x55, 0x06, 0x67, 0x08, 0x48, 0xbf, 0xa1, 0xa3, 0xab, 0x3b, 0xff, 0xa5, 0x71,
            0x6c, 0xd8, 0xb6, 0xbe, 0xa2, 0x1b, 0x83, 0x62, 0x90, 0xe6, 0x96, 0x20, 0xbd, 0xba,
            0xdb, 0x3b, 0x3f, 0xac,
        ],
        y: [
            0x74, 0xf6, 0xa9, 0xd6, 0x2e, 0x40, 0xf9, 0x9e, 0x2a, 0xbd, 0x94, 0x79, 0x3f, 0x97,
            0xfc, 0xe7, 0xf0, 0x57, 0xb6, 0xec, 0x23, 0xd5, 0x0b, 0xd2, 0xdd, 0x96, 0x22, 0x00,
            0x64, 0xf5, 0x20, 0x76,
        ],
    };
    global SIGNATURE_A: [u8; 64] = [
        0x5e, 0xf3, 0x33, 0x12, 0xac, 0x72, 0xff, 0x14, 0xdb, 0x8f, 0x39, 0x37, 0x7c, 0x72, 0x13,
        0xa3, 0xbf, 0x05, 0xcc, 0xba, 0x10, 0xb5, 0x70, 0xb2, 0x07, 0x5d, 0x78, 0x9f, 0x0f, 0x24,
        0x14, 0x33, 0x70, 0xb9, 0x5f, 0xc8, 0xd1, 0xd3, 0xa9, 0xb6, 0xdb, 0x5d, 0xc6, 0x05, 0xe5,
        0x2a, 0x02, 0x38, 0x30, 0x00, 0x34, 0xe8, 0x02, 0x6a, 0xe0, 0x4d, 0xda, 0x51, 0x92, 0xcb,
        0x30, 0x7a, 0x56, 0xf1,
    ];
    global SIGNER_B: Secp256k1PubKey = Secp256k1PubKey {
        x: [
            0x83, 0x95, 0xbe, 0x7c, 0xc3, 0xd7, 0x12, 0x32, 0xe5, 0xf7, 0x93, 0x99, 0x51, 0x59,
            0xc3, 0x28, 0x1a, 0x5d, 0x0e, 0xd0, 0x51, 0x5d, 0x60, 0xa1, 0xc4, 0x5e, 0x39, 0x73,
            0x26, 0x35, 0x39, 0x1a,
        ],
        y: [
            0x7a, 0x8c, 0x45, 0xff, 0x1e, 0xe9, 0x22, 0x97, 0x1d, 0x68, 0x35, 0x18, 0xa6, 0x63,
            0xff, 0x4e, 0xd7, 0x86, 0xa6, 0xe8, 0x7b, 0x7b, 0x39, 0x0e, 0xf7, 0x80, 0xd5, 0x58,
            0x1e, 0x33, 0x20, 0xd7,
        ],
    };
    global SIGNATURE_B: [u8; 64] = [
        0x1c, 0xa8, 0x03, 0x55, 0x6b, 0xbf, 0xcb, 0xb4, 0xf8, 0xc3, 0xd2, 0xca, 0x66, 0x56, 0xb4,
        0xcd, 0x91, 0x1a, 0x4d, 0x3f, 0xaf, 0x19, 0x1f, 0x0c, 0xb5, 0xe0, 0x3c, 0x0b, 0xaa, 0x65,
        0x44, 0x45, 0x3b, 0xb2, 0x3d, 0x4a, 0x4b, 0x61, 0x93, 0x47, 0x4f, 0x97, 0x52, 0x3f, 0x3f,
        0xea, 0x37, 0x5d, 0x91, 0x44, 0x2d, 0x40, 0xfb, 0x7b, 0x98, 0xc3, 0xf9, 0x9e, 0x32, 0x38,
        0x87, 0x61, 0xac, 0x6a,
    ];
    global SIGNER_C: Secp256k1PubKey = Secp256k1PubKey {
        x: [
            0xcc, 0x37, 0x9a, 0xef, 0x9b, 0xc8, 0xd6, 0xd5, 0xbe, 0x61, 0xd5, 0xec, 0xb5, 0xaa,
            0x08, 0xf7, 0x6f, 0xb2, 0x76, 0xe3, 0x89, 0x75, 0x88, 0x19, 0x1a, 0xdd, 0xbc, 0xf2,
            0x5b, 0x0c, 0x38, 0xd0,
        ],
        y: [
            0x07, 0x6d, 0xa3, 0x78, 0x32, 0x81, 0xf0, 0xb8, 0x77, 0x60, 0x3d, 0x58, 0xd9, 0xaa,
            0xfd, 0x2c, 0xfb, 0x65, 0x10, 0x53, 0x18, 0xe8, 0x70, 0xb4, 0x8c, 0x3c, 0x3a, 0xa4,
            0xdb, 0x0d, 0x7f, 0xd6,
        ],
    };
    global SIGNER_D: Secp256k1PubKey = Secp256k1PubKey {
        x: [
            0xbf, 0x4d, 0x76, 0xc3, 0xda, 0xfe, 0x95, 0xfe, 0x92, 0xa6, 0xee, 0xef, 0xcc, 0x0b,
            0x76, 0xb5, 0x7f, 0x01, 0x6c, 0x44, 0x4e, 0xb0, 0x76, 0x58, 0x9a, 0x3b, 0xdd, 0x3d,
            0x1b, 0x59, 0xcd, 0x8b,
        ],
        y: [
            0x57, 0x64, 0xbb, 0x46, 0x1a, 0x36, 0x43, 0xa6, 0x2d, 0x9f, 0xf0, 0xd5, 0x96, 0x49,
            0x07, 0x2b, 0xbb, 0x16, 0x86, 0x57, 0x57, 0xf7, 0x22, 0x4f, 0x01, 0x76, 0x9e, 0xdc,
            0xef, 0x78, 0xe5, 0x21,
        ],
    };
    global SIGNATURE_D: [u8; 64] = [
        0x85, 0x47, 0x80, 0xd4, 0x90, 0xbd, 0x02, 0xa0, 0xaf, 0x49, 0xc1, 0x24, 0xd5, 0x6d, 0x05,
        0x41, 0x16, 0x49, 0x6a, 0xf0, 0xd4, 0xe0, 0x6d, 0x4a, 0xb0, 0xf7, 0xe3, 0x0a, 0x8f, 0x9f,
        0xbc, 0x28, 0x32, 0x9a, 0xe0, 0x64, 0xd7, 0x46, 0xc8, 0x8f, 0x73, 0x2e, 0xf7, 0x80, 0x8a,
        0x1b, 0x4b, 0xde, 0xee, 0x84, 0xa3, 0x5a, 0x36, 0xe2, 0xc8, 0x9a, 0xbc, 0xe4, 0xa2, 0xde,
        0x4c, 0x20, 0xcc, 0x03,
    ];

    fn transaction() -> PrivateValue {
        small_transaction(0, 2000000000)
    }

    fn approve(
        recent_pcash_block_hash: Field,
        member: MemberAccount,
        member_rule: MemberRule,
        signers: [Secp256k1PubKey; N],
        approvals: [Approval; 2],
    ) -> [Field; RULE_STATEMENT_LENGTH] {
        main(
            CHAIN_ID,
            recent_pcash_block_hash,
            TREASURY,
            false,
            configuration(),
            transaction(),
            HEADER_SIBLINGS,
            STATE_SIBLINGS,
            member,
            member_rule,
            signers,
            approvals,
            EVENT_ENTRY,
        )
    }

    fn assert_treasury_statement(statement: [Field; RULE_STATEMENT_LENGTH], block: Field) {
        assert_rule_statement(
            statement,
            authorization_commitment(TREASURY, treasury_configuration_commitment(configuration())),
            transfer_action_commitment(CHAIN_ID, private_value_commitment(transaction())),
            block,
            EVENT_ENTRY,
        );
    }

    fn addresses(signers: [Secp256k1PubKey; N]) -> [Field; N] {
        signers.map(|signer: Secp256k1PubKey| signer.ethereum_address())
    }

    global OLD_SIGNERS: [Secp256k1PubKey; N] = [SIGNER_A, SIGNER_B, SIGNER_C];
    global NEW_SIGNERS: [Secp256k1PubKey; N] = [SIGNER_B, SIGNER_C, SIGNER_D];

    #[test]
    fn accepts_two_of_the_members_signers() {
        let (block, member, rule) = member_state(addresses(OLD_SIGNERS), 1);
        let approvals = [
            Approval { signer_index: 0, signature: SIGNATURE_A },
            Approval { signer_index: 1, signature: SIGNATURE_B },
        ];
        assert_treasury_statement(approve(block, member, rule, OLD_SIGNERS, approvals), block);
    }

    // X replaced A with D. The same contract accepts the new set.
    #[test]
    fn follows_the_members_new_signers() {
        let (block, member, rule) = member_state(addresses(NEW_SIGNERS), 2);
        let approvals = [
            Approval { signer_index: 2, signature: SIGNATURE_D },
            Approval { signer_index: 0, signature: SIGNATURE_B },
        ];
        assert_treasury_statement(approve(block, member, rule, NEW_SIGNERS, approvals), block);
    }

    // After the rotation, the old set no longer opens in X's rule set at the
    // recent block, even with valid signatures.
    #[test(should_fail_with = "signer entry must be in the member's rule set")]
    fn rejects_signers_the_member_removed() {
        let (block, member, rule) = member_state(addresses(NEW_SIGNERS), 2);
        let approvals = [
            Approval { signer_index: 0, signature: SIGNATURE_A },
            Approval { signer_index: 1, signature: SIGNATURE_B },
        ];
        let _ = approve(block, member, rule, OLD_SIGNERS, approvals);
    }

    #[test(should_fail_with = "approval signers must be distinct")]
    fn rejects_one_signer_approving_twice() {
        let (block, member, rule) = member_state(addresses(OLD_SIGNERS), 1);
        let approvals = [
            Approval { signer_index: 1, signature: SIGNATURE_B },
            Approval { signer_index: 1, signature: SIGNATURE_B },
        ];
        let _ = approve(block, member, rule, OLD_SIGNERS, approvals);
    }

    // The published reference vector of the multisig rule's configuration
    // (circuits/fixtures/multisig), so X's entry and this formula agree.
    #[test]
    fn member_rule_configuration_matches_the_multisig_rule() {
        assert(
            member_rule_configuration_commitment(
                0x0102030405060708090a0b0c0d0e0f01,
                [0x1111, 0x2222, 0x3333],
            )
                == 0x198f3472707b88c0bd4841c0b68db6af8c7b7d1df1bf68929a3adef81ee987dc,
        );
    }
}
```

</details>

## Use it from an app

`createTreasury` builds the contract creation, including the receive key that payments into the treasury and its change are encrypted to; the treasury's participants hold its secret. `payFromTreasury` reads X's row, the treasury's row and the spent notes from one node snapshot, builds the contract call, asks two of X's signers to approve its action commitment, fills the circuit's inputs and proves the transaction. X's wallet supplies its multisig entry's salt, blinder and rule-set path.

```typescript examples/delegated-treasury/client.ts
// Creates the delegated treasury and spends from it with two of member account X's current signers.
// Example only: unaudited, not for real funds.
import type { Prover } from "@pcash/sdk/browser-prover";
import {
  buildContractFunctionCall, buildUnfundedContractCreation, fieldArrayMap, fm, privateValueMap, snapshotFromAccountProof,
} from "@pcash/sdk/builders";
import type { PcashNodeClient } from "@pcash/sdk/clients";
import {
  contractActionCommitment, functionSelector, nullifierKeyCommitment, verifyContract, type ContractBody, type NativeBurn,
} from "@pcash/sdk/protocol";
import { referenceConfigurationCommitment } from "@pcash/sdk/rules";
import { addressHex } from "@pcash/sdk/utils";

const SELECTOR = functionSelector(0);

/** The member X the treasury follows, and the multisig rule whose entry in X names the signers. */
export interface TreasuryTerms { configurationSalt: bigint; memberAddress: bigint; memberRuleVkHash: bigint }

/** A private contract (only P is published). Funders and change encrypt to `receiveKey`, whose secret the participants hold. */
export function createTreasury(p: TreasuryTerms & {
  pcashChainId: bigint; recentPcashBlockHash: bigint; validUntilTimestamp: bigint; nkRoot: bigint; treasuryVkHash: bigint;
  receiveKey: Uint8Array;
}) {
  const configurationCommitment = referenceConfigurationCommitment(p.configurationSalt, [p.memberAddress, p.memberRuleVkHash]);
  return buildUnfundedContractCreation({
    pcashChainId: p.pcashChainId, recentPcashBlockHash: p.recentPcashBlockHash, validUntilTimestamp: p.validUntilTimestamp,
    contract: {
      nullifierKey: { publishesNkRoot: false, nullifierKeyCommitment: nullifierKeyCommitment(p.nkRoot) },
      mlKemPublicKey: p.receiveKey,
      functions: [{ selector: SELECTOR, applicationVkHash: p.treasuryVkHash, configurationCommitment }],
    },
  });
}

/** Pays `amount` from treasury notes; change goes to the body's receive key. Returns the transaction bytes to post. */
export async function payFromTreasury(p: {
  node: PcashNodeClient; prover: Prover; circuitUrl: string; pcashChainId: bigint;
  treasury: ContractBody; terms: TreasuryTerms; nkRoot: bigint;
  // From X's wallet: its multisig entry's salt, blinder and rule-set path.
  memberRule: { configurationSalt: bigint; commitmentBlinder: bigint; entryIndex: number; siblings: readonly bigint[] };
  // X's current signers, sorted by address, and two approvals: signMultisigApproval(key, action, treasury) from @pcash/sdk/fixtures.
  signers: readonly { pubX: Uint8Array; pubY: Uint8Array }[];
  approve: (actionCommitment: bigint, treasury: bigint) => Promise<{ signerIndex: number; signature: Uint8Array }[]>;
  notes: readonly { amount: bigint; noteSecret: bigint; outputIndex: number; outputCommitment: bigint }[];
  recipient: bigint; recipientReceiveKey: Uint8Array; amount: bigint; burn: NativeBurn; validUntilTimestamp: bigint;
}): Promise<Uint8Array> {
  // One snapshot: X's row and the treasury's row open under the same recent block.
  const snapshot = await p.node.getWitnessSnapshot({
    accounts: [addressHex(p.terms.memberAddress)],
    contracts: [addressHex(verifyContract(p.treasury).address)],
    outputs: p.notes.map(({ outputIndex, outputCommitment }) => ({ outputIndex, outputCommitment })),
  });
  const [member] = snapshot.accounts, [contract] = snapshot.contracts, paths = snapshot.outputs?.paths;
  if (member?.status !== "present" || contract?.status !== "contract" || !paths) throw new Error("snapshot incomplete");
  const call = buildContractFunctionCall({
    chainId: p.pcashChainId, contract: p.treasury, selector: SELECTOR, nkRoot: p.nkRoot,
    recipientAddress: p.recipient, paymentAmount: p.amount, recipientReceiveKey: p.recipientReceiveKey,
    inputs: p.notes.map((note, i) => ({ ...note, siblings: paths[i]!.siblings })),
    ...snapshotFromAccountProof(contract.accountProof),
    accountIndex: Number(contract.accountProof.account.index), accountSiblings: contract.accountProof.accountSiblings,
    openFeeAmount: 0n, issuanceOwnerCommitment: 0n, burn: p.burn, validUntilTimestamp: p.validUntilTimestamp,
  });
  const approvals = await p.approve(contractActionCommitment(call.pcashChainId, call.privateValueCommitment, false), call.contractAddress);
  const bytes = (value: Uint8Array) => Array.from(value, String), row = member.account, rule = p.memberRule;
  const witness = {
    pcash_chain_id: fm(call.pcashChainId), recent_pcash_block_hash: fm(call.recentPcashBlockHash),
    address: fm(call.contractAddress), fee_paid: false,
    configuration: { configuration_salt: fm(p.terms.configurationSalt), member_address: fm(p.terms.memberAddress), member_rule_vk_hash: fm(p.terms.memberRuleVkHash) },
    private_value: privateValueMap(call.transaction),
    block_header_state_siblings: fieldArrayMap(member.stateRootHeaderSiblings),
    state_account_siblings: fieldArrayMap(member.accountStateRootStateSiblings),
    member: { // X's row as the node serves it
      nullifier_key_commitment: fm(row.nullifierKeyCommitment), rule_set_commitment: fm(row.accountRuleSetCommitment),
      account_revision: fm(row.accountRevision), receive_key_hash: fm(row.receiveKeyHash),
      witness: { leaf_index: fm(row.index), siblings: fieldArrayMap(member.accountSiblings) },
    },
    member_rule: { configuration_salt: fm(rule.configurationSalt), commitment_blinder: fm(rule.commitmentBlinder),
      witness: { entry_index: rule.entryIndex, siblings: fieldArrayMap(rule.siblings) } },
    signers: p.signers.map(({ pubX, pubY }) => ({ x: bytes(pubX), y: bytes(pubY) })),
    approvals: approvals.map(({ signerIndex, signature }) => ({ signer_index: fm(signerIndex), signature: bytes(signature) })),
    event_entry: fm(call.eventOpening.eventEntry),
  };
  const proof = await p.prover.proveTransfer({ authorizationWitnessMap: witness, buildKernelWitnessMap: call.buildKernelWitnessMap,
    expectedPublicInputs: call.publicInputs, authorizationCircuitUrl: p.circuitUrl, authorizationLabel: "delegated treasury" });
  return call.encodeTransaction(proof.proof);
}
```

## Limits

- The function reads X's multisig signer set; it does not run X's rule. It works only with a rule that uses this exact configuration format and the one verification key the treasury names. Running X's own rule in the same transaction needs a protocol change that is under discussion.
- Whoever can update X controls the treasury. With the reference administration rule, that is X's one Ethereum key, which can install any signers and can never itself be replaced.
- Every entry in X's rule set with the named verification key counts. To remove a signer, remove every entry that names it.
- A removed signer can still approve for up to an hour after the update, because a proof may name any recent block in the one-hour window, including one from before the update.
- Signers sign a hash, not a readable message. Their wallets must rebuild the transaction to show what they approve.
- The threshold is fixed at two of three by the multisig rule's format.
- Whoever builds the proof needs the treasury's nullifier key root and X's entry opening: its salt, blinder and rule-set path.

## Run the tests

`nargo test --program-dir examples/delegated-treasury` runs the circuit's tests, including one where signers X removed are rejected, and `just test-examples-noir` runs every example's tests.

Further reading: [rule entries and rule sets](../protocol-spec.md#52-account-rule-entries-and-rule-sets), [the rule statement](../protocol-spec.md#82-the-rule-statement), [what a proof can open](../protocol-spec.md#84-what-a-proof-can-open), [the recent block window](../protocol-spec.md#106-recent-block-window-and-validity-conditions) and [contract accounts](../protocol-spec.md#124-contract-account-creation-txtype-0x02).
