> Aztec.nr API reference, v6.0.0 (mainnet and testnet). Index: https://docs.aztec.network/aztec-nr-api/mainnet/llms.txt

# Struct PrivateContext

Module: `noir_aztec::context`

```rust
pub struct PrivateContext
{ /* private fields */ }
```

## PrivateContext

The **main interface** between an #\[external("private")] function and the Aztec blockchain.

An instance of the PrivateContext is initialized automatically at the outset of every private function, within the #\[external("private")] macro, so you'll never need to consciously instantiate this yourself.

The instance is always named `context`, and it is always be available within the body of every #\[external("private")] function in your smart contract.

> For those used to "vanilla" Noir, it might be jarring to have access to > `context` without seeing a declaration `let context = PrivateContext::new(...)` > within the body of your function. This is just a consequence of using > macros to tidy-up verbose boilerplate. You can use `nargo expand` to > expand all macros, if you dare.

Typical usage for a smart contract developer will be to call getter methods of the PrivateContext.

*Pushing* data and requests to the context is mostly handled within aztec-nr's own functions, so typically a smart contract developer won't need to call any setter methods directly.

> Advanced users might occasionally wish to push data to the context > directly for lower-level control. If you find yourself doing this, please > open an issue on GitHub to describe your use case: it might be that > new functionality should be added to aztec-nr.

## Responsibilities

- Exposes contextual data to a private function:
- Data relating to how this private function was called.
- msg_sender
- this_address - (the contract address of the private function being executed)
- See `CallContext` for more data.
- Data relating to the transaction in which this private function is being executed.
- chain_id
- version
- gas_settings
- Provides state access:
- Access to the "Anchor block" header. Recall, a private function cannot read from the "current" block header, but must read from some historical block header, because as soon as private function execution begins (asynchronously, on a user's device), the public state of the chain (the "current state") will have progressed forward. We call this reference the "Anchor block". See `BlockHeader`.
  - Enables consumption of L1->L2 messages.
- Enables calls to functions of other smart contracts:
- Private function calls
- Enqueueing of public function call requests (Since public functions are executed at a later time, by a block proposer, we say they are "enqueued").
- Writes data to the blockchain:
- New notes
- New nullifiers
- Private logs (for sending encrypted note contents or encrypted events)
  - New L2->L1 messages.
- Provides args to the private function (handled by the #\[external("private")] macro).
- Returns the return values of this private function (handled by the #\[external("private")] macro).
- Makes Key Validation Requests.
- Private functions are not allowed to see master secret keys, because we do not trust them. They are instead given "app-siloed" secret keys with a claim that they relate to a master public key. They can then request validation of this claim, by making a "key validation request" to the protocol's kernel circuits (which *are* allowed to see certain master secret keys).

## Advanced Responsibilities

- Ultimately, the PrivateContext is responsible for constructing the PrivateCircuitPublicInputs of the private function being executed. All private functions on Aztec must have public inputs which adhere to the rigid layout of the PrivateCircuitPublicInputs, in order to be compatible with the protocol's kernel circuits. A well-known misnomer:
- "public inputs" contain both inputs and outputs of this function.
- By "outputs" we mean a lot more side-effects than just the "return values" of the function.
- Most of the so-called "public inputs" are kept *private*, and never leak to the outside world, because they are 'swallowed' by the protocol's kernel circuits before the tx is sent to the network. Only the following are exposed to the outside world:
- New note_hashes
- New nullifiers
- New private logs
  - New L2->L1 messages
- New enqueued public function call requests All the above-listed arrays of side-effects can be padded by the user's wallet (through instructions to the kernel circuits, via the PXE) to obscure their true lengths.

## Syntax Justification

Both user-defined functions *and* most functions in aztec-nr need access to the PrivateContext instance to read/write data. This is why you'll see the arguably-ugly pervasiveness of the "context" throughout your smart contract and the aztec-nr library. For example, `&mut context` is prevalent. In some languages, you can access and mutate a global variable (such as a PrivateContext instance) from a function without polluting the function's parameters. With Noir, a function must explicitly pass control of a mutable variable to another function, by reference. Since many functions in aztec-nr need to be able to push new data to the PrivateContext, they need to be handed a mutable reference *to* the context as a parameter. For example, `Context` is prevalent as a generic parameter, to give better type safety at compile time. Many `aztec-nr` functions don't make sense if they're called in a particular runtime (private, public or utility), and so are intentionally only implemented over certain \[Private|Public|Utility]Context structs. This gives smart contract developers a much faster feedback loop if they're making a mistake, as an error will be thrown by the LSP or when they compile their contract.

## Implementations

```rust
impl PrivateContext
```

```rust
pub fn new(inputs: PrivateContextInputs, args_hash: Field) -> Self
```

```rust
pub fn maybe_msg_sender(self) -> Option<AztecAddress>
```

Returns the contract address that initiated this function call.

This is similar to `msg.sender` in Solidity (hence the name).

Important Note: Since Aztec doesn't have a concept of an EoA (Externally-owned Account), the msg_sender is "none" for the first function call of every transaction. The first function call of a tx is likely to be a call to the user's account contract, so this quirk will most often be handled by account contract developers.

#### Returns

- `Option<AztecAddress>` - The address of the smart contract that called this function (be it an app contract or a user's account contract). Returns `Option<AztecAddress>::none` for the first function call of the tx. No other *private* function calls in the tx will have a `none` msg_sender, but *public* function calls might (see the PublicContext).

```rust
pub fn this_address(self) -> AztecAddress
```

Returns the contract address of the current function being executed.

This is equivalent to `address(this)` in Solidity (hence the name). Use this to identify the current contract's address, commonly needed for access control or when interacting with other contracts.

#### Returns

- `AztecAddress` - The contract address of the current function being executed.

```rust
pub fn chain_id(self) -> Field
```

Returns the chain ID of the current network.

This is similar to `block.chainid` in Solidity. Returns the unique identifier for the blockchain network this transaction is executing on.

Helps prevent cross-chain replay attacks. Useful if implementing multi-chain contract logic.

#### Returns

- `Field` - The chain ID as a field element

```rust
pub fn version(self) -> Field
```

Returns the Aztec protocol version that this transaction is executing under. Different versions may have different rules, opcodes, or cryptographic primitives.

This is similar to how Ethereum has different EVM versions.

Useful for forward/backward compatibility checks

Not to be confused with contract versions; this is the protocol version.

#### Returns

- `Field` - The protocol version as a field element

```rust
pub fn gas_settings(self) -> GasSettings
```

Returns the gas settings for the current transaction.

This provides information about gas limits and pricing for the transaction, similar to `tx.gasprice` and gas limits in Ethereum. However, Aztec has a more sophisticated gas model with separate accounting for L2 computation and data availability (DA) costs.

#### Returns

- `GasSettings` - Struct containing gas limits and fee information

```rust
pub fn selector(self) -> FunctionSelector
```

Returns the function selector of the currently executing function.

Low-level function: Ordinarily, smart contract developers will not need to access this.

This is similar to `msg.sig` in Solidity, which returns the first 4 bytes of the function signature. In Aztec, the selector uniquely identifies which function within the contract is being called.

#### Returns

- `FunctionSelector` - The 4-byte function identifier

#### Advanced

Only #\[external("private")] functions have a function selector as a protocol- enshrined concept. The function selectors of private functions are baked into the preimage of the contract address, and are used by the protocol's kernel circuits to identify each private function and ensure the correct one is being executed.

Used internally for function dispatch and call verification.

```rust
pub fn is_static_call(self) -> bool
```

Returns whether this call is being executed as part of a static call.

Similar to Solidity's `STATICCALL`, a static call is read-only: neither this function nor any of its nested calls may emit side-effects (new notes, nullifiers, logs, L2->L1 messages, etc.). A call is considered static if it was invoked as a static call or if any of its ancestor calls were.

#### Returns

- `bool` - `true` if this call (or an ancestor call) is a static call.

```rust
pub fn get_args_hash(self) -> Field
```

Returns the hash of the arguments passed to the current function.

Very low-level function: You shouldn't need to call this. The #\[external("private")] macro calls this, and it makes the arguments neatly available to the body of your private function.

#### Returns

- `Field` - Hash of the function arguments

#### Advanced

- Arguments are hashed to reduce proof size and verification time
- Enables efficient argument passing in recursive function calls
- The hash can be used to retrieve the original arguments from the PXE.

```rust
pub fn get_side_effect_counter(self) -> u32
```

Returns the current value of the side-effect counter, i.e. the counter that will be assigned to the next side-effect emitted by this function.

Low-level function: Ordinarily, smart contract developers will not need to access this. See `next_counter` for details on how side-effect counters are assigned and why they exist.

#### Returns

- `u32` - The current side-effect counter.

```rust
pub fn push_note_hash(&mut self, note_hash: Field)
```

Pushes a new note_hash to the Aztec blockchain's global Note Hash Tree (a state tree).

A note_hash is a commitment to a piece of private state.

Low-level function: Ordinarily, smart contract developers will not need to manually call this. Aztec-nr's state variables (see `../state_vars/`) are designed to understand when to create and push new note hashes.

#### Arguments

- `note_hash` - The new note_hash.

#### Advanced

From here, the protocol's kernel circuits will take over and insert the note_hash into the protocol's "note hash tree" (in the Base Rollup circuit). Before insertion, the protocol will:

- "Silo" the `note_hash` with the contract address of this function, to yield a `siloed_note_hash`. This prevents state collisions between different smart contracts.
- Ensure uniqueness of the `siloed_note_hash`, to prevent Faerie-Gold attacks, by hashing the `siloed_note_hash` with a unique value, to yield a `unique_siloed_note_hash` (see the protocol spec for more).

In addition to calling this function, aztec-nr provides the contents of the newly-created note to the PXE, via the `notify_created_note` oracle.

> Advanced users might occasionally wish to push data to the context > directly for lower-level control. If you find yourself doing this, > please open an issue on GitHub to describe your use case: it might be > that new functionality should be added to aztec-nr.

```rust
pub fn push_nullifier_unsafe(&mut self, nullifier: Field)
```

Creates a new [nullifier](/aztec-nr-api/mainnet/noir_aztec/nullifier/index.md).

#### Safety

This is a low-level function that must be used with great care to avoid subtle corruption of contract state. Instead of calling this function, consider using the higher-level [`crate::state_vars::SingleUseClaim`](/aztec-nr-api/mainnet/noir_aztec/state_vars/struct.SingleUseClaim.md).

In particular, callers must ensure all nullifiers created by a contract are properly domain-separated, so that unrelated components don't interfere with one another (e.g. a transaction nullifier accidentally marking a variable as initialized). Only [`PrivateContext::push_nullifier_for_note_hash`](/aztec-nr-api/mainnet/noir_aztec/context/struct.PrivateContext.md#push_nullifier_for_note_hash) should be used for note nullifiers, never this one.

#### Advanced

The raw `nullifier` is not what is inserted into the Aztec state tree: it will be first siloed by contract address via [`crate::protocol::hash::compute_siloed_nullifier`](/aztec-nr-api/mainnet/protocol_types/hash/fn.compute_siloed_nullifier.md) in order to prevent accidental or malicious interference of nullifiers from different contracts.

```rust
pub fn push_nullifier_for_note_hash(
    &mut self,
    nullifier: Field,
    nullification_note_hash: Field,
)
```

Creates a new [nullifier](/aztec-nr-api/mainnet/noir_aztec/nullifier/index.md) associated with a note.

This is a variant of [`PrivateContext::push_nullifier_unsafe`](/aztec-nr-api/mainnet/noir_aztec/context/struct.PrivateContext.md#push_nullifier_unsafe) that is used for note nullifiers, i.e. nullifiers that correspond to a note. If a note and its nullifier are created in the same transaction, then the private kernels will 'squash' these values, deleting them both as if they never existed and reducing transaction fees.

The `nullification_note_hash` must be the result of calling [`crate::note::utils::compute_confirmed_note_hash_for_nullification`](/aztec-nr-api/mainnet/noir_aztec/note/utils/fn.compute_confirmed_note_hash_for_nullification.md) for pending notes, and `0` for settled notes (which cannot be squashed).

#### Safety

This is a low-level function that must be used with great care to avoid subtle corruption of contract state. Instead of calling this function, consider using the higher-level [`crate::note::lifecycle::destroy_note`](/aztec-nr-api/mainnet/noir_aztec/note/lifecycle/fn.destroy_note.md).

The precautions listed for [`PrivateContext::push_nullifier_unsafe`](/aztec-nr-api/mainnet/noir_aztec/context/struct.PrivateContext.md#push_nullifier_unsafe) apply here as well, and callers should additionally ensure `nullification_note_hash` corresponds to a note emitted by this contract, with its hash computed in the same transaction execution phase as the call to this function. Finally, only this function should be used for note nullifiers, never [`PrivateContext::push_nullifier_unsafe`](/aztec-nr-api/mainnet/noir_aztec/context/struct.PrivateContext.md#push_nullifier_unsafe).

Failure to do these things can result in unprovable contexts, accidental deletion of notes, or double-spend attacks.

```rust
pub fn get_anchor_block_header(self) -> BlockHeader
```

Returns the anchor block header - the historical block header that this private function is reading from.

A private function CANNOT read from the "current" block header, but must read from some older block header, because as soon as private function execution begins (asynchronously, on a user's device), the public state of the chain (the "current state") will have progressed forward.

#### Returns

- `BlockHeader` - The anchor block header.

#### Advanced

- All private functions of a tx read from the same anchor block header.
- The protocol asserts that the `expiration_timestamp` of every tx is at most 24 hours beyond the timestamp of the tx's chosen anchor block header. This enables the network's nodes to safely prune old txs from the mempool. Therefore, the chosen block header *must* be one from within the last 24 hours.

```rust
pub fn get_block_header_at(self, block_number: u32) -> BlockHeader
```

Returns the header of any historical block at or before the anchor block.

This enables private contracts to access information from even older blocks than the anchor block header.

Useful for time-based contract logic that needs to compare against multiple historical points.

#### Arguments

- `block_number` - The block number to retrieve (must be <= anchor block number)

#### Returns

- `BlockHeader` - The header of the requested historical block

#### Advanced

This function uses an oracle to fetch block header data from the user's PXE. Depending on how much blockchain data the user's PXE has been set up to store, this might require a query from the PXE to another Aztec node to get the data. > This is generally true of all oracle getters (see `../oracle`).

Each block header gets hashed and stored as a leaf in the protocol's Archive Tree. In fact, the i-th block header gets stored at the i-th leaf index of the Archive Tree. Behind the scenes, this `get_block_header_at` function will add Archive Tree merkle-membership constraints (\~3k) to your smart contract function's circuit, to prove existence of the block header in the Archive Tree.

Note: we don't do any caching, so avoid making duplicate calls for the same block header, because each call will add duplicate constraints.

Calling this function is more expensive (constraint-wise) than getting the anchor block header (via `get_block_header`). This is because the anchor block's merkle membership proof is handled by Aztec's protocol circuits, and is only performed once for the entire tx because all private functions of a tx share a common anchor block header. Therefore, the cost (constraint-wise) of calling `get_block_header` is effectively free.

```rust
pub fn set_return_hash<let N: u32>(&mut self, serialized_return_values: [Field; N])
```

Sets the hash of the return values for this private function.

Very low-level function: this is called by the #\[external("private")] macro.

#### Arguments

- `serialized_return_values` - The serialized return values as a field array

```rust
pub fn finish(self) -> PrivateCircuitPublicInputs
```

Builds the PrivateCircuitPublicInputs for this private function, to ensure compatibility with the protocol's kernel circuits.

Very low-level function: This function is automatically called by the #\[external("private")] macro.

```rust
pub fn set_as_fee_payer(&mut self)
```

Designates this contract as the fee payer for the transaction.

Unlike Ethereum, where the transaction sender always pays fees, Aztec allows any contract to voluntarily pay transaction fees. This enables patterns like sponsored transactions or fee abstraction where users don't need to hold fee-juice themselves. (Fee juice is a fee-paying asset for Aztec).

Only one contract per transaction can declare itself as the fee payer, and it must have sufficient fee-juice balance (>= the gas limits specified in the TxContext) by the time we reach the public setup phase of the tx.

The fee payer must be elected during the setup (non-revertible) phase, i.e. before [`end_setup`](/aztec-nr-api/mainnet/noir_aztec/context/struct.PrivateContext.md#end_setup) is called - this function asserts so. This is because any compensation collected by the fee payer during the revertible phase can be discarded if a public call later reverts, while the protocol still debits the fee payer's fee-juice balance. Note that `end_setup` does not need to be called by the electing function itself: it can be called later in the transaction (e.g. by the fee-juice contract when claiming fee juice that pays for the very same transaction).

```rust
pub fn in_revertible_phase(&mut self) -> bool
```

Returns whether execution is currently in the revertible (app) phase of the transaction.

A transaction is in the revertible phase if [`end_setup`](/aztec-nr-api/mainnet/noir_aztec/context/struct.PrivateContext.md#end_setup) has already been called - potentially by a different function of the same transaction.

```rust
pub fn end_setup(&mut self)
```

Declares the end of the "setup phase" of this tx.

Only one function per tx can declare the end of the setup phase.

Niche function: Only wallet developers and paymaster contract developers (aka Fee-payment contracts) will need to make use of this function.

Aztec supports a three-phase execution model: setup, app logic, teardown. The phases exist to enable a fee payer to take on the risk of paying a transaction fee, safe in the knowledge that their payment (in whatever token or method the user chooses) will succeed, regardless of whether the app logic will succeed. The "setup" phase enables such a payment to be made, because the setup phase *cannot revert*: a reverting function within the setup phase would result in an invalid block which cannot be proven. Any side-effects generated during that phase are guaranteed to be inserted into Aztec's state trees (except for squashed notes & nullifiers, of course).

Even though the end of the setup phase is declared within a private function, you might have noticed that *public* functions can also execute within the setup phase. This is because any public function calls which were enqueued *within the setup phase* by a private function are considered part of the setup phase.

#### Advanced

- Sets the minimum revertible side effect counter of this tx to be the PrivateContext's *current* side effect counter.

```rust
pub fn set_expiration_timestamp(&mut self, expiration_timestamp: u64)
```

Sets a deadline (an "include-by timestamp") for when this transaction must be included in a block.

Other functions in this tx might call this setter with differing values for the include-by timestamp. To ensure that all functions' deadlines are met, the *minimum* of all these include-by timestamps will be exposed when this tx is submitted to the network.

If the transaction is not included in a block by its include-by timestamp, it becomes invalid and it will never be included.

This expiry timestamp is publicly visible. See the "Advanced" section for privacy concerns.

#### Arguments

- `expiration_timestamp` - Unix timestamp (seconds) deadline for inclusion. The include-by timestamp of this tx will be *at most* the timestamp specified.

#### Advanced

- If multiple functions set differing `expiration_timestamp`s, the kernel circuits will set it to be the *minimum* of the two. This ensures the tx expiry requirements of all functions in the tx are met.
- Rollup circuits will reject expired txs.
- The protocol enforces that all transactions must be included within 24 hours of their chosen anchor block's timestamp, to enable safe mempool pruning.
- The DelayedPublicMutable design makes heavy use of this functionality, to enable private functions to read public state.
- A sophisticated Wallet should cleverly set an include-by timestamp to improve the privacy of the user and the network as a whole. For example, if a contract interaction sets include-by to some publicly-known value (e.g. the time when a contract upgrades), then the wallet might wish to set an even lower one to avoid revealing that this tx is interacting with said contract. Ideally, all wallets should standardize on an approach in order to provide users with a large privacy set -- although the exact approach will need to be discussed. Wallets that deviate from a standard might accidentally reveal which wallet each transaction originates from.

```rust
pub fn assert_note_exists(&mut self, note_existence_request: NoteExistenceRequest)
```

Asserts that a note has been created.

This function will cause the transaction to fail unless the requested note exists. This is the preferred mechanism for performing this check, and the only one that works for pending notes.

#### Pending Notes

Both settled notes (created in prior transactions) and pending notes (created in the current transaction) will be considered by this function. Pending notes must have been created **before** this call is made for the check to pass.

#### Historical Notes

If you need to assert that a note existed *by some specific block in the past*, instead of simply proving that it exists by the current anchor block, use [`crate::history::note::assert_note_existed_by`](/aztec-nr-api/mainnet/noir_aztec/history/note/fn.assert_note_existed_by.md) instead.

#### Cost

This uses up one of the call's kernel note hash read requests, which are limited. Like all kernel requests, proving time costs are only incurred when the total number of requests exceeds the kernel's capacity, requiring an additional invocation of the kernel reset circuit.

```rust
pub fn assert_nullifier_exists(
    &mut self,
    nullifier_existence_request: NullifierExistenceRequest,
)
```

Asserts that a nullifier has been emitted.

This function will cause the transaction to fail unless the requested nullifier exists. This is the preferred mechanism for performing this check, and the only one that works for pending nullifiers.

#### Pending Nullifiers

Both settled nullifiers (emitted in prior transactions) and pending nullifiers (emitted in the current transaction) will be considered by this function. Pending nullifiers must have been emitted **before** this call is made for the check to pass.

#### Historical Nullifiers

If you need to assert that a nullifier existed *by some specific block in the past*, instead of simply proving that it exists by the current anchor block, use [`crate::history::nullifier::assert_nullifier_existed_by`](/aztec-nr-api/mainnet/noir_aztec/history/nullifier/fn.assert_nullifier_existed_by.md) instead.

#### Public vs Private

In general, it is unsafe to check for nullifier non-existence in private, as that will not consider the possibility of the nullifier having been emitted in any transaction between the anchor block and the inclusion block. Private functions instead prove existence via this function and 'prove' non-existence by *emitting* the nullifer, which would cause the transaction to fail if the nullifier existed.

This is not the case in public functions, which do have access to the tip of the blockchain and so can reliably prove whether a nullifier exists or not via [`crate::context::public_context::PublicContext::nullifier_exists_unsafe`](/aztec-nr-api/mainnet/noir_aztec/context/struct.PublicContext.md#nullifier_exists_unsafe).

#### Cost

This uses up one of the call's kernel nullifier read requests, which are limited. Like all kernel requests, proving time costs are only incurred when the total number of requests exceeds the kernel's capacity, requiring an additional invocation of the kernel reset circuit.

```rust
pub fn request_nhk_app(&mut self, npk_m_hash: Field) -> Field
```

Requests the app-siloed nullifier hiding key (nhk_app) for the given (hashed) master nullifier public key (npk_m), from the user's PXE.

Advanced function: Only needed if you're designing your own notes and/or nullifiers.

Contracts are not allowed to compute nullifiers for other contracts, as that would let them read parts of their private state. Because of this, a contract is only given an "app-siloed key", which is constructed by hashing the user's master nullifier hiding key with the contract's address. However, because contracts cannot be trusted with a user's master nullifier hiding key (because we don't know which contracts are honest or malicious), the PXE refuses to provide any master secret keys to any app smart contract function. This means app functions are unable to prove that the derivation of an app-siloed nullifier hiding key has been computed correctly. Instead, an app function can request to the kernel (via `request_nhk_app`) that it validates the siloed derivation, since the kernel has been vetted to not leak any master secret keys.

A common nullification scheme is to inject a nullifier hiding key into the preimage of a nullifier, to make the nullifier deterministic but random-looking. This function enables that flow.

#### Arguments

- `npk_m_hash` - A hash of the master nullifier public key of the user whose PXE is executing this function.

#### Returns

- The app-siloed nullifier hiding key that corresponds to the given `npk_m_hash`.

```rust
pub fn request_ovsk_app(&mut self, ovpk_m_hash: Field) -> Field
```

Requests the app-siloed outgoing viewing secret key (ovsk_app) for the given (hashed) master outgoing viewing public key (ovpk_m), from the user's PXE.

See `request_nhk_app` and `request_sk_app` for more info.

The intention of the "outgoing" keypair is to provide a second secret key for all of a user's outgoing activity (i.e. for notes that a user creates, as opposed to notes that a user receives from others). The separation of incoming and outgoing data was a distinction made by zcash, with the intention of enabling a user to optionally share with a 3rd party a controlled view of only incoming or outgoing notes. Similar functionality of sharing select data can be achieved with offchain zero-knowledge proofs. It is up to an app developer whether they choose to make use of a user's outgoing keypair within their application logic, or instead simply use the same keypair (the address keypair (which is effectively the same as the "incoming" keypair)) for all incoming & outgoing messages to a user.

Currently, all of the exposed encryption functions in aztec-nr ignore the outgoing viewing keys, and instead encrypt all note logs and event logs to a user's address public key.

#### Arguments

- `ovpk_m_hash` - Hash of the outgoing viewing public key master

#### Returns

- The application-specific outgoing viewing secret key

```rust
pub fn message_portal(&mut self, recipient: EthAddress, content: Field)
```

Sends an "L2 -> L1 message" from this function (Aztec, L2) to a smart contract on Ethereum (L1). L1 contracts which are designed to send/receive messages to/from Aztec are called "Portal Contracts".

Common use cases include withdrawals, cross-chain asset transfers, and triggering L1 actions based on L2 state changes.

The message will be inserted into an Aztec "Outbox" contract on L1, when this transaction's block is proposed to L1. Sending the message will not result in any immediate state changes in the target portal contract. The message will need to be manually consumed from the Outbox through a separate Ethereum transaction: a user will need to call a function of the portal contract -- a function specifically designed to make a call to the Outbox to consume the message. The message will only be available for consumption once the *epoch* proof has been submitted. Given that there are multiple Aztec blocks within an epoch, it might take some time for this epoch proof to be submitted -- especially if the block was near the start of an epoch.

#### Arguments

- `recipient` - Ethereum address that will receive the message
- `content` - Message content (32 bytes as a Field element). This content has a very specific layout. docs:start:context_message_portal

```rust
pub fn consume_l1_to_l2_message<let N: u32>(
    &mut self,
    content: Field,
    secret: [Field; N],
    sender: EthAddress,
    leaf_index: Field,
)
```

Consumes a message sent from Ethereum (L1) to Aztec (L2).

Common use cases include token bridging, cross-chain governance, and triggering L2 actions based on L1 events.

Use this function if you only want the message to ever be "referred to" once. Once consumed using this method, the message cannot be consumed again, because a nullifier is emitted. If your use case wants for the message to be read unlimited times, then you can always read any historic message from the L1-to-L2 messages tree; messages never technically get deleted from that tree.

The message will first be inserted into an Aztec "Inbox" smart contract on L1. Sending the message will not result in any immediate state changes in the target L2 contract. The message will need to be manually consumed by the target contract through a separate Aztec transaction. The message will not be available for consumption immediately. Messages get copied over from the L1 Inbox to L2 by the next Proposer in batches. So you will need to wait until the messages are copied before you can consume them.

#### Arguments

- `content` - The message content that was sent from L1
- `secret` - Secret fields used for message privacy (if needed)
- `sender` - Ethereum address that sent the message
- `leaf_index` - Index of the message in the L1-to-L2 message tree

#### Advanced

Validates message existence in the L1-to-L2 message tree and nullifies the message to prevent double-consumption.

```rust
pub fn emit_private_log_unsafe(&mut self, tag: Field, log: BoundedVec<Field, 15>)
```

Emits a private log (an array of Fields) that will be published to an Ethereum blob.

Private logs are intended for the broadcasting of ciphertexts: that is, encrypted events or encrypted note contents. Since the data in the logs is meant to be *encrypted*, private_logs are broadcast to publicly-visible Ethereum blobs. The intended recipients of such encrypted messages can then discover and decrypt these encrypted logs using their viewing secret key. (See `../messages/discovery` for more details).

Important note: This function DOES NOT *do* any encryption of the input `log` fields. This function blindly publishes whatever input `log` data is fed into it, so the caller of this function should have already performed the encryption, and the `log` should be the result of that encryption.

The protocol does not dictate what encryption scheme should be used: a smart contract developer can choose whatever encryption scheme they like. Aztec-nr includes some off-the-shelf encryption libraries that developers might wish to use, for convenience. These libraries not only encrypt a plaintext (to produce a ciphertext); they also prepend the ciphertext with a `tag` and `ephemeral public key` for easier message discovery. This is a very dense topic, and we will be writing more libraries and docs soon.

> Currently, AES128 CBC encryption is the main scheme included in > aztec.nr. > We are currently making significant changes to the interfaces of the > encryption library.

In some niche use cases, an app might be tempted to publish *un-encrypted* data via a private log, because *public logs* are not available to private functions. Be warned that emitting public data via private logs is strongly discouraged, and is considered a "privacy anti-pattern", because it reveals identifiable information about *which* function has been executed. A tx which leaks such information does not contribute to the privacy set of the network.

- Unlike `emit_raw_note_log_unsafe`, this log is not tied to any specific note

#### Arguments

- `tag` - A tag placed at `fields[0]` of the emitted log. Used by recipients and nodes to identify and filter for relevant logs without scanning all of them.
- `log` - The log data that will be publicly broadcast (so make sure it's already been encrypted before you call this function). Private logs are bounded in size (`PRIVATE_LOG_CIPHERTEXT_LEN`), to encourage all logs from all smart contracts look identical. Every field of the emitted log beyond its length must be zero: the base rollup rejects a private log with non-zero fields past its length, so padding can never be appended inside a log. What the kernel circuits can add is whole padding logs, which hide how many logs a tx actually emitted. It's up to wallets how much padding to apply, so ideally all wallets should agree on standards for this.

#### Safety

The `tag` should be domain-separated (e.g. via [`crate::protocol::hash::compute_log_tag`](/aztec-nr-api/mainnet/protocol_types/hash/fn.compute_log_tag.md)) to prevent collisions between logs from different sources. Without domain separation, two unrelated log types that happen to share a raw tag value become indistinguishable. Prefer the higher-level APIs ([`crate::messages::delivery::MessageDelivery`](/aztec-nr-api/mainnet/noir_aztec/messages/delivery/struct.MessageDelivery.md) for messages, `self.emit(event)` for events) which handle tagging automatically.

```rust
pub fn emit_raw_note_log_unsafe(
    &mut self,
    tag: Field,
    log: BoundedVec<Field, 15>,
    note_hash_counter: u32,
)
```

Emits a private log that is explicitly tied to a newly-emitted note_hash, to convey to the kernel: "this log relates to this note".

This linkage is important in case the note gets squashed (due to being read later in this same tx), since we can then squash the log as well.

See [`emit_private_log_unsafe`](/aztec-nr-api/mainnet/noir_aztec/context/struct.PrivateContext.md#emit_private_log_unsafe) for more info about private log emission.

#### Arguments

- `tag` - A tag placed at `fields[0]`. See [`emit_private_log_unsafe`](/aztec-nr-api/mainnet/noir_aztec/context/struct.PrivateContext.md#emit_private_log_unsafe).
- `log` - The log data as a `BoundedVec` of Field elements.
- `note_hash_counter` - The side-effect counter that was assigned to the new note_hash when it was pushed to this `PrivateContext`.

Important: If your application logic requires the log to always be emitted regardless of note squashing, consider using [`emit_private_log_unsafe`](/aztec-nr-api/mainnet/noir_aztec/context/struct.PrivateContext.md#emit_private_log_unsafe) instead, or emitting additional events.

#### Safety

Same as [`PrivateContext::emit_private_log_unsafe`](/aztec-nr-api/mainnet/noir_aztec/context/struct.PrivateContext.md#emit_private_log_unsafe): the `tag` should be domain-separated.

```rust
pub fn emit_contract_class_log<let N: u32>(&mut self, log: [Field; N])
```

Emits large data blobs.

This reuses the Contract Class Log channel to emit blobs of up to [`CONTRACT_CLASS_LOG_SIZE_IN_FIELDS`](/aztec-nr-api/mainnet/protocol_types/constants/global.CONTRACT_CLASS_LOG_SIZE_IN_FIELDS.md).

#### Privacy

The address of the contract emitting these blobs is revelead.

```rust
pub fn call_private_function<let ArgsCount: u32>(
    &mut self,
    contract_address: AztecAddress,
    function_selector: FunctionSelector,
    args: [Field; ArgsCount],
) -> ReturnsHash
```

Calls a private function on another contract (or the same contract).

Very low-level function.

#### Arguments

- `contract_address` - Address of the contract containing the function
- `function_selector` - 4-byte identifier of the function to call
- `args` - Array of arguments to pass to the called function

#### Returns

- `ReturnsHash` - Hash of the called function's return values. Use `.get_preimage()` to extract the actual return values.

This enables contracts to interact with each other while maintaining privacy. This "composability" of private contract functions is a key feature of the Aztec network.

If a user's transaction includes multiple private function calls, then by the design of Aztec, the following information will remain private\[1]:

- The function selectors and contract addresses of all private function calls will remain private, so an observer of the public mempool will not be able to look at a tx and deduce which private functions have been executed.
- The arguments and return values of all private function calls will remain private.
- The person who initiated the tx will remain private.
- The notes and nullifiers and private logs that are emitted by all private function calls will (if designed well) not leak any user secrets, nor leak which functions have been executed.

\[1] Caveats: Some of these privacy guarantees depend on how app developers design their smart contracts. Some actions *can* leak information, such as:

- Calling an internal public function.
- Calling a public function and not setting msg_sender to Option::none (feature not built yet - see github).
- Calling any public function will always leak details about the nature of the transaction, so devs should be careful in their contract designs. If it can be done in a private function, then that will give the best privacy.
- Not padding the side-effects of a tx to some standardized, uniform size. The kernel circuits can take hints to pad side-effects, so a wallet should be able to request for a particular amount of padding. Wallets should ideally agree on some standard.
- Padding should include:
- Padding the lengths of note & nullifier arrays
- Padding private logs with random fields, up to some standardized size. See also: <https://docs.aztec.network/developers/resources/considerations/privacy_considerations>

#### Advanced

- The call is added to the private call stack and executed by kernel circuits after this function completes
- The called function can modify its own contract's private state
- Side effects from the called function are included in this transaction
- The call inherits the current transaction's context and gas limits

```rust
pub fn static_call_private_function<let ArgsCount: u32>(
    &mut self,
    contract_address: AztecAddress,
    function_selector: FunctionSelector,
    args: [Field; ArgsCount],
) -> ReturnsHash
```

Makes a read-only call to a private function on another contract.

This is similar to Solidity's `staticcall`. The called function cannot modify state, emit L2->L2 messages, nor emit events. Any nested calls are constrained to also be staticcalls.

See `call_private_function` for more general info on private function calls.

#### Arguments

- `contract_address` - Address of the contract to call
- `function_selector` - 4-byte identifier of the function to call
- `args` - Array of arguments to pass to the called function

#### Returns

- `ReturnsHash` - Hash of the called function's return values. Use `.get_preimage()` to extract the actual return values.

```rust
pub fn call_private_function_no_args(
    &mut self,
    contract_address: AztecAddress,
    function_selector: FunctionSelector,
) -> ReturnsHash
```

Calls a private function that takes no arguments.

This is a convenience function for calling private functions that don't require any input parameters. It's equivalent to `call_private_function` but slightly more efficient to use when no arguments are needed.

#### Arguments

- `contract_address` - Address of the contract containing the function
- `function_selector` - 4-byte identifier of the function to call

#### Returns

- `ReturnsHash` - Hash of the called function's return values. Use `.get_preimage()` to extract the actual return values.

```rust
pub fn static_call_private_function_no_args(
    &mut self,
    contract_address: AztecAddress,
    function_selector: FunctionSelector,
) -> ReturnsHash
```

Makes a read-only call to a private function which takes no arguments.

This combines the optimisation of `call_private_function_no_args` with the safety of `static_call_private_function`.

#### Arguments

- `contract_address` - Address of the contract containing the function
- `function_selector` - 4-byte identifier of the function to call

#### Returns

- `ReturnsHash` - Hash of the called function's return values. Use `.get_preimage()` to extract the actual return values.

```rust
pub fn call_private_function_with_args_hash(
    &mut self,
    contract_address: AztecAddress,
    function_selector: FunctionSelector,
    args_hash: Field,
    is_static_call: bool,
) -> ReturnsHash
```

Low-level private function call.

This is the underlying implementation used by all other private function call methods. Instead of taking raw arguments, it accepts a hash of the arguments.

#### Arguments

- `contract_address` - Address of the contract containing the function
- `function_selector` - 4-byte identifier of the function to call
- `args_hash` - Pre-computed hash of the function arguments
- `is_static_call` - Whether this should be a read-only call

#### Returns

- `ReturnsHash` - Hash of the called function's return values

```rust
pub fn call_public_function<let ArgsCount: u32>(
    &mut self,
    contract_address: AztecAddress,
    function_selector: FunctionSelector,
    args: [Field; ArgsCount],
    hide_msg_sender: bool,
)
```

Enqueues a call to a public function to be executed later.

Unlike private functions which execute immediately on the user's device, public function calls are "enqueued" and executed some time later by a block proposer.

This means a public function cannot return any values back to a private function, because by the time the public function is being executed, the private function which called it has already completed execution. (In fact, the private function has been executed and proven, along with all other private function calls of the user's tx. A single proof of the tx has been submitted to the Aztec network, and some time later a proposer has picked the tx up from the mempool and begun executing all of the enqueued public functions).

#### Privacy warning Enqueueing a public function call is an inherently leaky action. Many interesting applications

will require some interaction with public state, but smart contract developers should try to use public function calls sparingly, and carefully. *Internal* public function calls are especially leaky, because they completely leak which private contract made the call. See also: <https://docs.aztec.network/developers/resources/considerations/privacy_considerations>

#### Arguments

- `contract_address` - Address of the contract containing the function
- `function_selector` - 4-byte identifier of the function to call
- `args` - Array of arguments to pass to the public function
- `hide_msg_sender` - the called function will see a "null" value for `msg_sender` if set to `true`

```rust
pub fn static_call_public_function<let ArgsCount: u32>(
    &mut self,
    contract_address: AztecAddress,
    function_selector: FunctionSelector,
    args: [Field; ArgsCount],
    hide_msg_sender: bool,
)
```

Enqueues a read-only call to a public function.

This is similar to Solidity's `staticcall`. The called function cannot modify state or emit events. Any nested calls are constrained to also be staticcalls.

See also `call_public_function` for more important information about making private -> public function calls.

#### Arguments

- `contract_address` - Address of the contract containing the function
- `function_selector` - 4-byte identifier of the function to call
- `args` - Array of arguments to pass to the public function
- `hide_msg_sender` - the called function will see a "null" value for `msg_sender` if set to `true`

```rust
pub fn call_public_function_no_args(
    &mut self,
    contract_address: AztecAddress,
    function_selector: FunctionSelector,
    hide_msg_sender: bool,
)
```

Enqueues a call to a public function that takes no arguments.

This is an optimisation for calling public functions that don't take any input parameters. It's otherwise equivalent to `call_public_function`.

#### Arguments

- `contract_address` - Address of the contract containing the function
- `function_selector` - 4-byte identifier of the function to call
- `hide_msg_sender` - the called function will see a "null" value for `msg_sender` if set to `true`

```rust
pub fn static_call_public_function_no_args(
    &mut self,
    contract_address: AztecAddress,
    function_selector: FunctionSelector,
    hide_msg_sender: bool,
)
```

Enqueues a read-only call to a public function with no arguments.

This combines the optimisation of `call_public_function_no_args` with the safety of `static_call_public_function`.

#### Arguments

- `contract_address` - Address of the contract containing the function
- `function_selector` - 4-byte identifier of the function to call
- `hide_msg_sender` - the called function will see a "null" value for `msg_sender` if set to `true`

```rust
pub fn call_public_function_with_calldata_hash(
    &mut self,
    contract_address: AztecAddress,
    calldata_hash: Field,
    is_static_call: bool,
    hide_msg_sender: bool,
)
```

Low-level public function call.

This is the underlying implementation used by all other public function call methods. Instead of taking raw arguments, it accepts a hash of the arguments.

Advanced function: Most developers should use `call_public_function` or `static_call_public_function` instead. This function is exposed for performance optimization and advanced use cases.

#### Arguments

- `contract_address` - Address of the contract containing the function
- `calldata_hash` - Hash of the function calldata
- `is_static_call` - Whether this should be a read-only call
- `hide_msg_sender` - the called function will see a "null" value for `msg_sender` if set to `true`

```rust
pub fn set_public_teardown_function<let ArgsCount: u32>(
    &mut self,
    contract_address: AztecAddress,
    function_selector: FunctionSelector,
    args: [Field; ArgsCount],
    hide_msg_sender: bool,
)
```

Enqueues a public function call, and designates it to be the teardown function for this tx. Only one teardown function call can be made by a tx.

Niche function: Only wallet developers and paymaster contract developers (aka Fee-payment contracts) will need to make use of this function.

Aztec supports a three-phase execution model: setup, app logic, teardown. The phases exist to enable a fee payer to take on the risk of paying a transaction fee, safe in the knowledge that their payment (in whatever token or method the user chooses) will succeed, regardless of whether the app logic will succeed. The "setup" phase ensures the fee payer has sufficient balance to pay the proposer their fees. The teardown phase is primarily intended to: calculate exactly how much the user owes, based on gas consumption, and refund the user any change.

Note: in some cases, the cost of refunding the user (i.e. DA costs of tx side-effects) might exceed the refund amount. For app logic with fairly stable and predictable gas consumption, a material refund amount is unlikely. For app logic with unpredictable gas consumption, a refund might be important to the user (e.g. if a hefty function reverts very early). Wallet/FPC/Paymaster developers should be mindful of this.

#### Arguments

- `contract_address` - Address of the contract containing the teardown function
- `function_selector` - 4-byte identifier of the function to call
- `args` - An array of fields to pass to the function.
- `hide_msg_sender` - the called function will see a "null" value for `msg_sender` if set to `true`

```rust
pub fn set_public_teardown_function_with_calldata_hash(
    &mut self,
    contract_address: AztecAddress,
    calldata_hash: Field,
    is_static_call: bool,
    hide_msg_sender: bool,
)
```

Low-level function to set the public teardown function.

This is the underlying implementation for setting the teardown function call that will execute at the end of the transaction. Instead of taking raw arguments, it accepts a hash of the arguments.

Advanced function: Most developers should use `set_public_teardown_function` instead.

#### Arguments

- `contract_address` - Address of the contract containing the teardown function
- `calldata_hash` - Hash of the function calldata
- `is_static_call` - Whether this should be a read-only call
- `hide_msg_sender` - the called function will see a "null" value for `msg_sender` if set to `true`

## Trait implementations

```rust
impl Empty for PrivateContext
```

```rust
pub fn empty() -> Self
```

```rust
pub fn is_empty(self: Self) -> bool
where
    Self: Eq
```

```rust
pub fn assert_empty<let S: u32>(self: Self, msg: str<S>)
where
    Self: Eq
```

```rust
impl Eq for PrivateContext
```

```rust
pub fn eq(_self: Self, _other: Self) -> bool
```
