# Pay out when an Ethereum contract reports an outcome

Alice and Bob bet on a market that an oracle contract on Ethereum will settle. You build a contract account that holds their stakes and has two functions: one pays the stakes to Alice once the oracle emits `Resolved(marketId, 1)`, and the other pays Bob once it emits `Resolved(marketId, 0)`. Both functions are the same circuit with different configurations. On PCASH, the bet's terms, its parties and the payout stay private. This is an example: unaudited and not for real funds.

## How it works

1. **Create the contract.** Alice and Bob create a contract account with two functions. Each function's configuration commits the oracle's address, the event's signature, the market ID, the outcome that pays, the beneficiary, and the hash of that beneficiary's claim key.
2. **Stake.** Each funds the contract with a note that the contract's address owns, and shares the note's opening with the other, so whoever wins can spend both notes.
3. **The oracle resolves.** The oracle contract emits `Resolved(marketId, outcome)` on Ethereum. Every PCASH block commits every Ethereum block since the chain began, each with a Merkle tree of that block's event logs, so every later PCASH block holds this log.
4. **The winner proves.** The winner's app proves the matching function against a recent PCASH block. The circuit rebuilds the log from its configuration and opens it through three Merkle paths: the log in its Ethereum block's log tree, that block in the PCASH block's L1 origin tree, and the L1 origin root in the PCASH block's header. The transaction executes only while that PCASH block is canonical and recent, so the log must be in canonical Ethereum history.
5. **The stake is paid out.** The same proof requires the transaction to spend one stake note and pay it, less the fee and burn it funds, to the configured beneficiary. Only the holder of the claim key can make that proof: whoever proves chooses the payout's note secret, open fee and burn, so without the key the losing side could prove the payout and strand or skim the winnings.

## The circuit

The configuration holds everything the function checks. A 32-byte Ethereum word does not fit in one field element, so the event signature (the log's first topic) and the market ID are each held as two 128-bit halves, the form in which PCASH stores a log.

```rust examples/event-payout/src/main.nr
// `topic0` and the market ID are 32-byte words held as big-endian 128-bit
// halves. The outcome is the low half of the log's one data word, whose high
// half the leaf fixes to zero. The claim-key hash names who may settle, and
// its entropy keeps the published configuration commitment from being guessed.
pub struct Configuration {
    pub claim_key_hash: Field,
    pub oracle: Field,
    pub topic0_high: Field,
    pub topic0_low: Field,
    pub market_id_high: Field,
    pub market_id_low: Field,
    pub outcome: Field,
    pub beneficiary: Field,
}
```

The contract body publishes only a hash of each function's configuration. The claim-key hash is in it, so the hash also keeps anyone without the opening from guessing the terms.

```rust examples/event-payout/src/main.nr
pub fn configuration_commitment(configuration: Configuration) -> Field {
    pcash_hash([
        CONFIGURATION_DOMAIN,
        configuration.claim_key_hash,
        configuration.oracle,
        configuration.topic0_high,
        configuration.topic0_low,
        configuration.market_id_high,
        configuration.market_id_low,
        configuration.outcome,
        configuration.beneficiary,
    ])
}

pub fn claim_key_hash(claim_key: Field) -> Field {
    pcash_hash([CLAIM_KEY_DOMAIN, claim_key])
}
```

PCASH stores each Ethereum log as one hash over its position in the block, its emitter, its topics split into halves, and its data split into 16-byte chunks. The function rebuilds the hash the oracle's log must have from the configuration, so only the log's position comes from the prover. The outcome is the low chunk of the log's one data word, and its high chunk must be zero.

```rust examples/event-payout/src/main.nr
// The leaf of the oracle's log reporting the configured outcome, at a log
// position the opening supplies.
pub fn resolution_log_leaf(
    configuration: Configuration,
    transaction_index: Field,
    log_index: Field,
) -> Field {
    normalized_log_leaf(
        transaction_index,
        log_index,
        configuration.oracle,
        2,
        [
            configuration.topic0_high,
            configuration.topic0_low,
            configuration.market_id_high,
            configuration.market_id_low,
            0,
            0,
            0,
            0,
        ],
        32,
        [0, configuration.outcome, 0, 0, 0, 0, 0, 0],
    )
}
```

The prover must know the claim key that the configuration's hash names.

```rust examples/event-payout/src/main.nr
    // The prover chooses the payout's note secret and the open fee and burn
    // the stake funds, so only the claim-key holder may prove.
    assert(
        claim_key_hash(claim_key) == configuration.claim_key_hash,
        "claim key must open the configured hash",
    );
```

`assert_normalized_log` hashes the rebuilt leaf up its path to the Ethereum block's log root, hashes that block's record, with its number, hash, timestamp, log root and log count, up the L1 origin tree, and requires the header of `recent_pcash_block_hash` to commit the result. A log from another emitter, market or outcome has a different leaf, so no path opens it.

```rust examples/event-payout/src/main.nr
    assert_normalized_log(
        recent_pcash_block_hash,
        resolution,
        resolution_log_leaf(
            configuration,
            resolution.transaction_index,
            resolution.log_index,
        ),
    );
```

The payout checks come from the marketplace's escrow contract. Input slot 0 must open to a stake note the contract owns, output slot 0 must pay the whole stake, less the open fee and burn it funds, to the beneficiary, and the other slots must be padding. A token stake is paid in full, and a sponsoring account pays the fee.

```rust examples/event-payout/src/main.nr
    // No private relay output: the stake funds only the public open fee and burn.
    let _ = assert_escrow_release(
        private_value,
        fee_paid,
        Note {
            owner: address,
            note_secret: stake.note_secret,
            asset_id: stake.asset_id,
            amount: stake.amount,
        },
        stake_output_index,
        owner_commitment(configuration.beneficiary, payout_note_secret),
        0,
        0,
    );
```

The function returns the four-value rule statement. The kernel computes the same values and requires them to match, which binds the contract's address and configuration, the transaction, and the recent block the log was opened under.

```rust examples/event-payout/src/main.nr
    rule_statement(
        authorization_commitment(address, configuration_commitment(configuration)),
        contract_action_commitment(
            pcash_chain_id,
            private_value_commitment(private_value),
            fee_paid,
        ),
        recent_pcash_block_hash,
        event_entry,
    )
```

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

```rust examples/event-payout/src/main.nr
// Approves paying one note this contract holds to the configured beneficiary once the configured Ethereum oracle has logged the configured outcome for a market.
// Example only: unaudited, not for real funds.
//
// The function opens one `Resolved(bytes32 indexed marketId, uint256 outcome)`
// log of the oracle through the recent block's L1 origin tree, as the
// deposit-mint rule opens a deposit, and requires the transaction to release
// the note in input slot 0 to the beneficiary in output slot 0. The release is
// the escrow's: a native note funds the open fee and native burn from the
// payout, and a token note is paid in full beside a sponsor's native fee.

use escrow_common::assert_escrow_release;
use pcash_protocol::authorization::statement::{
    authorization_commitment, contract_action_commitment, rule_statement, RULE_STATEMENT_LENGTH,
};
use pcash_protocol::ledger::note::owner_commitment;
use pcash_protocol::ledger::private_value::{
    private_value_commitment, SmallPrivateValue as PrivateValue,
};
use pcash_protocol::primitives::hash::pcash_hash;
use pcash_protocol::primitives::types::Note;
use pcash_protocol::state::l1_logs::{assert_normalized_log, L1LogGrounding, normalized_log_leaf};

// The domain tag of context "example_event_payout_configuration".
global CONFIGURATION_DOMAIN: Field =
    0x215ec49164d659ed059f50a385b158fe346efb68a28381cab3e92ea49d3e20dc;
// The domain tag of context "example_event_payout_claim_key".
global CLAIM_KEY_DOMAIN: Field = 0x2a39b1bbc344d22169048f91c055a3e3c2ec7874bf0b0f1de7805e07bc28265d;

// `topic0` and the market ID are 32-byte words held as big-endian 128-bit
// halves. The outcome is the low half of the log's one data word, whose high
// half the leaf fixes to zero. The claim-key hash names who may settle, and
// its entropy keeps the published configuration commitment from being guessed.
pub struct Configuration {
    pub claim_key_hash: Field,
    pub oracle: Field,
    pub topic0_high: Field,
    pub topic0_low: Field,
    pub market_id_high: Field,
    pub market_id_low: Field,
    pub outcome: Field,
    pub beneficiary: Field,
}

pub fn configuration_commitment(configuration: Configuration) -> Field {
    pcash_hash([
        CONFIGURATION_DOMAIN,
        configuration.claim_key_hash,
        configuration.oracle,
        configuration.topic0_high,
        configuration.topic0_low,
        configuration.market_id_high,
        configuration.market_id_low,
        configuration.outcome,
        configuration.beneficiary,
    ])
}

pub fn claim_key_hash(claim_key: Field) -> Field {
    pcash_hash([CLAIM_KEY_DOMAIN, claim_key])
}

// The note the contract's address owns, as its funder delivered it.
pub struct StakeOpening {
    pub note_secret: Field,
    pub asset_id: Field,
    pub amount: Field,
}

// The leaf of the oracle's log reporting the configured outcome, at a log
// position the opening supplies.
pub fn resolution_log_leaf(
    configuration: Configuration,
    transaction_index: Field,
    log_index: Field,
) -> Field {
    normalized_log_leaf(
        transaction_index,
        log_index,
        configuration.oracle,
        2,
        [
            configuration.topic0_high,
            configuration.topic0_low,
            configuration.market_id_high,
            configuration.market_id_low,
            0,
            0,
            0,
            0,
        ],
        32,
        [0, configuration.outcome, 0, 0, 0, 0, 0, 0],
    )
}

// The kernel binds `address`, the chain, the anchor and the event entry by
// requiring the returned statement to equal its own.
fn main(
    recent_pcash_block_hash: Field,
    address: Field,
    pcash_chain_id: Field,
    fee_paid: bool,
    configuration: Configuration,
    claim_key: Field,
    resolution: L1LogGrounding,
    private_value: PrivateValue,
    stake: StakeOpening,
    stake_output_index: Field,
    payout_note_secret: Field,
    event_entry: Field,
) -> return_data [Field; RULE_STATEMENT_LENGTH] {
    // The prover chooses the payout's note secret and the open fee and burn
    // the stake funds, so only the claim-key holder may prove.
    assert(
        claim_key_hash(claim_key) == configuration.claim_key_hash,
        "claim key must open the configured hash",
    );

    assert_normalized_log(
        recent_pcash_block_hash,
        resolution,
        resolution_log_leaf(
            configuration,
            resolution.transaction_index,
            resolution.log_index,
        ),
    );

    // No private relay output: the stake funds only the public open fee and burn.
    let _ = assert_escrow_release(
        private_value,
        fee_paid,
        Note {
            owner: address,
            note_secret: stake.note_secret,
            asset_id: stake.asset_id,
            amount: stake.amount,
        },
        stake_output_index,
        owner_commitment(configuration.beneficiary, payout_note_secret),
        0,
        0,
    );

    rule_statement(
        authorization_commitment(address, configuration_commitment(configuration)),
        contract_action_commitment(
            pcash_chain_id,
            private_value_commitment(private_value),
            fee_paid,
        ),
        recent_pcash_block_hash,
        event_entry,
    )
}

mod tests {
    use super::{
        claim_key_hash, Configuration, configuration_commitment, main, resolution_log_leaf,
        StakeOpening,
    };
    use escrow_common::test_support::release_transaction;
    use pcash_protocol::authorization::statement::{
        authorization_commitment, rule_statement, RULE_STATEMENT_LENGTH, transfer_action_commitment,
    };
    use pcash_protocol::ledger::note::owner_commitment;
    use pcash_protocol::ledger::private_value::{
        private_value_commitment, SmallPrivateValue as PrivateValue,
    };
    use pcash_protocol::primitives::params::{L1_LOG_TREE_DEPTH, L1_ORIGIN_TREE_DEPTH};
    use pcash_protocol::primitives::types::Note;
    use pcash_protocol::state::block::{block_hash_from_opening, BLOCK_HEADER_KEY_L1_ORIGIN_ROOT};
    use pcash_protocol::state::l1_logs::{l1_origin_leaf, L1LogGrounding};
    use pcash_protocol::state::merkle::binary_root_from_index;

    global CHAIN: Field = 7;
    global CONTRACT: Field = 0x77;
    global EVENT_ENTRY: Field = 0xe7;
    global ORACLE: Field = 0x5fbdb2315678afecb367f032d93f642f64180aa3;
    // keccak256("Resolved(bytes32,uint256)") as big-endian 128-bit halves.
    global TOPIC0_HIGH: Field = 0x1df120a9d15c6a6a6551e1f2e7fcfac6;
    global TOPIC0_LOW: Field = 0x6d4290fd830f071ef252255e039e2548;
    // keccak256("world cup 2026 final") as big-endian 128-bit halves.
    global MARKET_HIGH: Field = 0x92c675537277b45d481ffabe4de23b0c;
    global MARKET_LOW: Field = 0xdad80ffaa7c6036b6bcd84fac6a523a0;
    global ALICE: Field = 0x70997970c51812dc3a010c7d01b50e0d17dc79c8;
    global BOB: Field = 0x3c44cdddb6a900fa2b585dd299e03d12fa4293bc;
    global ALICE_KEY: Field = 0xc1a1;
    global BOB_KEY: Field = 0xb0b;
    global STAKE_SECRET: Field = 0x99;
    global STAKE_INDEX: Field = 3;
    global PAYOUT_SECRET: Field = 0x66;
    global BLOCK: Field = 100;
    global TRANSACTION: Field = 5;
    global LOG: Field = 2;
    // The log's index among its Ethereum block's logs.
    global LEAF: Field = 9;

    // Frozen from the SDK: `poseidon` and `domainTag` over alice_wins(), and
    // `normalizedL1LogLeaf` of the oracle's `Resolved(market, 1)` log at
    // transaction 5, log 2, with `abi.encode(uint256(1))` as its data.
    global KAT_CONFIGURATION_COMMITMENT: Field =
        0x15fed27d4b6e368047e729faed521ee1193c431456f905e35eab1239ab6fc94d;
    global KAT_LOG_LEAF: Field = 0x245d0925d87e4ebf975cfd38c99baef834d72e2dd29ae6d3a10084717586551f;

    fn alice_wins() -> Configuration {
        Configuration {
            claim_key_hash: claim_key_hash(ALICE_KEY),
            oracle: ORACLE,
            topic0_high: TOPIC0_HIGH,
            topic0_low: TOPIC0_LOW,
            market_id_high: MARKET_HIGH,
            market_id_low: MARKET_LOW,
            outcome: 1,
            beneficiary: ALICE,
        }
    }

    // The same circuit under the contract's other function.
    fn bob_wins() -> Configuration {
        let mut configuration = alice_wins();
        configuration.claim_key_hash = claim_key_hash(BOB_KEY);
        configuration.outcome = 0;
        configuration.beneficiary = BOB;
        configuration
    }

    // A recent block whose L1 origin tree holds the log `emitter` emitted for
    // `market_id_low` and `outcome`, and that log's opening.
    fn emitted(emitter: Field, market_id_low: Field, outcome: Field) -> (Field, L1LogGrounding) {
        let mut source = alice_wins();
        source.oracle = emitter;
        source.market_id_low = market_id_low;
        source.outcome = outcome;
        let leaf = resolution_log_leaf(source, TRANSACTION, LOG);
        let log_siblings: [Field; L1_LOG_TREE_DEPTH] = [0; L1_LOG_TREE_DEPTH];
        let logs_root = binary_root_from_index(leaf, LEAF, log_siblings);
        let block_leaf = l1_origin_leaf(BLOCK, 0xaaaa, 0xbbbb, 1700000000, logs_root, LEAF + 1);
        let l1_origin_siblings: [Field; L1_ORIGIN_TREE_DEPTH] = [0; L1_ORIGIN_TREE_DEPTH];
        let l1_origin_root = binary_root_from_index(block_leaf, 0, l1_origin_siblings);
        let header_siblings = [7, 8, 9, 10];
        (
            block_hash_from_opening(
                l1_origin_root,
                BLOCK_HEADER_KEY_L1_ORIGIN_ROOT,
                header_siblings,
            ),
            L1LogGrounding {
                l1_origin_root_siblings: header_siblings,
                l1_block_number: BLOCK,
                l1_block_hash_high: 0xaaaa,
                l1_block_hash_low: 0xbbbb,
                l1_block_timestamp: 1700000000,
                l1_origin_index: 0,
                l1_origin_siblings,
                log_count: LEAF + 1,
                log_leaf_index: LEAF,
                log_siblings,
                transaction_index: TRANSACTION,
                log_index: LOG,
            },
        )
    }

    // A 100-unit native stake paid to `payee`, less a 10-unit open fee.
    fn payout_to(payee: Field) -> PrivateValue {
        release_transaction(
            Note { owner: CONTRACT, note_secret: STAKE_SECRET, asset_id: 0, amount: 100 },
            STAKE_INDEX,
            owner_commitment(payee, PAYOUT_SECRET),
            90,
            10,
        )
    }

    fn settle(
        configuration: Configuration,
        claim_key: Field,
        log: (Field, L1LogGrounding),
        private_value: PrivateValue,
    ) -> [Field; RULE_STATEMENT_LENGTH] {
        let (recent, resolution) = log;
        main(
            recent,
            CONTRACT,
            CHAIN,
            false,
            configuration,
            claim_key,
            resolution,
            private_value,
            StakeOpening { note_secret: STAKE_SECRET, asset_id: 0, amount: 100 },
            STAKE_INDEX,
            PAYOUT_SECRET,
            EVENT_ENTRY,
        )
    }

    #[test]
    fn test_formulas_match_the_sdk() {
        assert(configuration_commitment(alice_wins()) == KAT_CONFIGURATION_COMMITMENT);
        assert(resolution_log_leaf(alice_wins(), TRANSACTION, LOG) == KAT_LOG_LEAF);
    }

    #[test]
    fn test_pays_alice_once_the_oracle_reports_outcome_one() {
        let log = emitted(ORACLE, MARKET_LOW, 1);
        let (recent, _) = log;
        let value = payout_to(ALICE);
        assert(
            settle(alice_wins(), ALICE_KEY, log, value)
                == rule_statement(
                    authorization_commitment(CONTRACT, KAT_CONFIGURATION_COMMITMENT),
                    transfer_action_commitment(CHAIN, private_value_commitment(value)),
                    recent,
                    EVENT_ENTRY,
                ),
        );
    }

    #[test]
    fn test_the_other_function_pays_bob_on_outcome_zero() {
        let _ = settle(
            bob_wins(),
            BOB_KEY,
            emitted(ORACLE, MARKET_LOW, 0),
            payout_to(BOB),
        );
    }

    #[test(should_fail_with = "block header field must be in the block header tree")]
    fn test_rejects_the_other_outcome() {
        let _ = settle(
            alice_wins(),
            ALICE_KEY,
            emitted(ORACLE, MARKET_LOW, 0),
            payout_to(ALICE),
        );
    }

    #[test(should_fail_with = "block header field must be in the block header tree")]
    fn test_rejects_another_market() {
        let _ = settle(
            alice_wins(),
            ALICE_KEY,
            emitted(ORACLE, MARKET_LOW + 1, 1),
            payout_to(ALICE),
        );
    }

    // Another contract that emits the same event is not the oracle.
    #[test(should_fail_with = "block header field must be in the block header tree")]
    fn test_rejects_a_log_from_another_emitter() {
        let _ = settle(
            alice_wins(),
            ALICE_KEY,
            emitted(ORACLE + 1, MARKET_LOW, 1),
            payout_to(ALICE),
        );
    }

    #[test(should_fail_with = "payout output must pay the payout owner")]
    fn test_rejects_a_payout_to_anyone_else() {
        let _ = settle(
            alice_wins(),
            ALICE_KEY,
            emitted(ORACLE, MARKET_LOW, 1),
            payout_to(BOB),
        );
    }

    #[test(should_fail_with = "claim key must open the configured hash")]
    fn test_rejects_a_prover_without_the_claim_key() {
        let _ = settle(
            alice_wins(),
            BOB_KEY,
            emitted(ORACLE, MARKET_LOW, 1),
            payout_to(ALICE),
        );
    }
}
```

</details>

## Use it from an app

`createBetContract` builds the contract body with both functions, and the first stake's funding transfer can attach it to create the contract. After the oracle resolves, `provePayout` builds the call to the winner's function from an account proof of the contract, asks the PCASH node to open the oracle's log beneath the same block, and proves the payout.

```typescript examples/event-payout/client.ts
// Sketch: create a two-sided bet contract and prove the winner's payout of one stake.
// Example only: unaudited, not for real funds.

import { encodeAbiParameters, hexToBytes, type Hex } from "viem";
import { domainTag, poseidon } from "@pcash/sdk/crypto";
import {
  buildContractBody, functionSelector, l1LogGroundingWitnessMap, nativeBurnAmount, type ContractBody, type NativeBurn,
} from "@pcash/sdk/protocol";
import { buildContractFunctionCall, fm, privateValueMap, snapshotFromAccountProof } from "@pcash/sdk/builders";
import type { AccountProofResult, PcashNodeClient } from "@pcash/sdk/browser";
import type { Prover } from "@pcash/sdk/browser-prover";

/** One side of the bet. `topic0` is keccak256("Resolved(bytes32,uint256)"). */
export interface PayoutTerms {
  claimKeyHash: bigint;
  oracle: bigint;
  topic0: Hex;
  marketId: Hex;
  outcome: bigint;
  beneficiary: bigint;
}

export const claimKeyHash = (claimKey: bigint) => poseidon([domainTag("example_event_payout_claim_key"), claimKey]);

// The circuit's `Configuration`, in its field order.
const CONFIGURATION_FIELDS = ["claim_key_hash", "oracle", "topic0_high", "topic0_low", "market_id_high", "market_id_low", "outcome", "beneficiary"];
const halves = (word: Hex) => [BigInt(word) >> 128n, BigInt(word) & ((1n << 128n) - 1n)];
const configuration = (t: PayoutTerms) =>
  [t.claimKeyHash, t.oracle, ...halves(t.topic0), ...halves(t.marketId), t.outcome, t.beneficiary];

/**
 * Selector 0 pays Alice on outcome 1 and selector 1 pays Bob on outcome 0, both with the payout circuit. Funders
 * encrypt stake openings to `mlKemPublicKey`; a stake's funding transfer may attach `{ kind: "contract", body }`.
 */
export function createBetContract(nkRoot: bigint, payoutVkHash: bigint, mlKemPublicKey: Uint8Array, alice: PayoutTerms, bob: PayoutTerms) {
  const payout = (selector: number, terms: PayoutTerms) => ({
    selector: functionSelector(selector),
    applicationVkHash: payoutVkHash,
    configurationCommitment: poseidon([domainTag("example_event_payout_configuration"), ...configuration(terms)]),
  });
  return buildContractBody({ nullifierKey: { publishesNkRoot: true, nkRoot }, mlKemPublicKey, functions: [payout(0, alice), payout(1, bob)] });
}

/** Prove one native stake's payout through `selector`, once the oracle's log is in `resolution`'s Ethereum block. */
export async function provePayout(p: {
  node: PcashNodeClient; prover: Prover; circuitUrl: string; chainId: bigint;
  contract: ContractBody; selector: number; terms: PayoutTerms; claimKey: bigint;
  account: Extract<AccountProofResult, { status: "present" }>;
  stake: { amount: bigint; noteSecret: bigint; outputIndex: number; siblings: readonly bigint[] };
  resolution: { l1BlockNumber: bigint; transactionIndex: bigint; logIndex: bigint };
  openFeeAmount: bigint; burn: NativeBurn; validUntilTimestamp: bigint; beneficiaryReceiveKey: Uint8Array;
}): Promise<Uint8Array> {
  const call = buildContractFunctionCall({
    chainId: p.chainId, contract: p.contract, selector: functionSelector(p.selector),
    recipientAddress: p.terms.beneficiary, recipientReceiveKey: p.beneficiaryReceiveKey,
    paymentAmount: p.stake.amount - p.openFeeAmount - nativeBurnAmount(p.burn),
    inputs: [p.stake], ...snapshotFromAccountProof(p.account),
    accountIndex: Number(p.account.account.index), accountSiblings: p.account.accountSiblings,
    openFeeAmount: p.openFeeAmount, burn: p.burn, issuanceOwnerCommitment: 0n, validUntilTimestamp: p.validUntilTimestamp,
  });
  // The log the oracle emitted, opened beneath the block the account proof names.
  const { transactionIndex, logIndex } = p.resolution;
  const data = hexToBytes(encodeAbiParameters([{ type: "uint256" }], [p.terms.outcome]));
  const log = { transactionIndex, logIndex, emitter: p.terms.oracle, topics: [hexToBytes(p.terms.topic0), hexToBytes(p.terms.marketId)], data };
  const opening = await p.node.getL1LogProof(call.recentPcashBlockHash, p.resolution.l1BlockNumber, transactionIndex, logIndex, log);
  const witness = {
    recent_pcash_block_hash: fm(call.recentPcashBlockHash), address: fm(call.address), pcash_chain_id: fm(p.chainId), fee_paid: false,
    configuration: Object.fromEntries(configuration(p.terms).map((value, i) => [CONFIGURATION_FIELDS[i], fm(value)])),
    claim_key: fm(p.claimKey),
    resolution: l1LogGroundingWitnessMap({ ...opening, logsRoot: opening.l1LogsRoot, logCount: opening.l1LogCount }),
    private_value: privateValueMap(call.transaction),
    stake: { note_secret: fm(p.stake.noteSecret), asset_id: fm(0n), amount: fm(p.stake.amount) },
    stake_output_index: fm(p.stake.outputIndex),
    payout_note_secret: fm(call.outputNoteSecrets[0]!),
    event_entry: fm(call.eventOpening.eventEntry),
  };
  const proved = await p.prover.proveTransfer({
    authorizationWitnessMap: witness, buildKernelWitnessMap: call.buildKernelWitnessMap,
    expectedPublicInputs: call.publicInputs, authorizationCircuitUrl: p.circuitUrl, authorizationLabel: "event payout",
  });
  return call.encodeTransaction(proved.proof);
}
```

## Limits

- The oracle is trusted completely. Whoever can make it emit `Resolved` decides the payout, and if it ever emits both outcomes, both sides can claim whatever stakes remain.
- If the market never resolves, or resolves to an outcome no function names, the stakes stay locked. A real contract needs a refund function that runs only after a deadline.
- The winner needs the opening of the other side's stake note to claim it. Check that you can open the other stake before you treat the bet as live.
- Each payout spends one stake note, so a bet with two stakes takes two payout transactions.
- Losing the claim key locks the winnings.
- The event's shape is fixed: the market ID is its one indexed topic and the outcome its one data word. A different event needs a different leaf.
- The app code handles PCASH stakes only. A token stake needs a sponsored call, with another account paying the fee.

## Run the tests

`nargo test --program-dir examples/event-payout` runs this circuit's tests, and `just test-examples-noir` runs every example's tests.

The specification defines [the L1 origin tree and normalized logs](../protocol-spec.md#72-l1-origin-tree-and-normalized-logs), [what a proof can open](../protocol-spec.md#84-what-a-proof-can-open) and [the rule statement](../protocol-spec.md#82-the-rule-statement).
