diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index c51c946c2036..a451dabc2811 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -63,7 +63,7 @@ const config = { }, routeBasePath: "/", include: ["**/*.{md,mdx}"], - exclude: !process.env.PROTOCOL_SPECS ? ['protocol-specs/**'] : [], + exclude: !process.env.PROTOCOL_SPECS ? ["protocol-specs/**"] : [], remarkPlugins: [math], rehypePlugins: [ @@ -76,6 +76,7 @@ const config = { }, ], ], + includeCurrentVersion: false, versions: (() => { const versionObject = {}; if (process.env.ENV === "dev") { diff --git a/docs/versioned_docs/version-Latest/aztec/concepts/_category_.json b/docs/versioned_docs/version-Latest/aztec/concepts/_category_.json index d105325f1163..88de50877b40 100644 --- a/docs/versioned_docs/version-Latest/aztec/concepts/_category_.json +++ b/docs/versioned_docs/version-Latest/aztec/concepts/_category_.json @@ -1,6 +1,6 @@ { - "label": "Uniswap Bridge", - "position": 7, + "label": "Concepts", + "position": 1, "collapsible": true, "collapsed": true } diff --git a/docs/versioned_docs/version-Latest/aztec/concepts/accounts/keys.md b/docs/versioned_docs/version-Latest/aztec/concepts/accounts/keys.md index 7c8d2635e9cd..6e8b8b291210 100644 --- a/docs/versioned_docs/version-Latest/aztec/concepts/accounts/keys.md +++ b/docs/versioned_docs/version-Latest/aztec/concepts/accounts/keys.md @@ -80,7 +80,7 @@ However if one wants to implement authorization logic containing signatures (e.g This is a snippet of our Schnorr Account contract implementation, which uses Schnorr signatures for authentication: -```rust title="is_valid_impl" showLineNumbers +```rust title="is_valid_impl" showLineNumbers // Load public key from storage let storage = Storage::init(context); let public_key = storage.signing_public_key.get_note(); @@ -102,7 +102,7 @@ let pub_key = std::embedded_curve_ops::EmbeddedCurvePoint { // Verify signature of the payload bytes schnorr::verify_signature(pub_key, signature, outer_hash.to_be_bytes::<32>()) ``` -> Source code: noir-projects/noir-contracts/contracts/account/schnorr_account_contract/src/main.nr#L65-L86 +> Source code: noir-projects/noir-contracts/contracts/account/schnorr_account_contract/src/main.nr#L65-L86 ### Storing signing keys @@ -117,10 +117,10 @@ Storing the signing public key in a private note makes it accessible from the `e Using an immutable private note removes the need to nullify the note on every read. This generates no nullifiers or new commitments per transaction. However, it does not allow the user to rotate their key. -```rust title="public_key" showLineNumbers +```rust title="public_key" showLineNumbers signing_public_key: PrivateImmutable, ``` -> Source code: noir-projects/noir-contracts/contracts/account/schnorr_account_contract/src/main.nr#L28-L30 +> Source code: noir-projects/noir-contracts/contracts/account/schnorr_account_contract/src/main.nr#L28-L30 :::note diff --git a/docs/versioned_docs/version-Latest/aztec/concepts/advanced/storage/partial_notes.md b/docs/versioned_docs/version-Latest/aztec/concepts/advanced/storage/partial_notes.md index c48a5a3d879d..3e94967b8e2c 100644 --- a/docs/versioned_docs/version-Latest/aztec/concepts/advanced/storage/partial_notes.md +++ b/docs/versioned_docs/version-Latest/aztec/concepts/advanced/storage/partial_notes.md @@ -113,7 +113,7 @@ We also need to create a point for the owner of the FPC (whom we call Bob) to re So in the contract we compute $\text{rand}_b := h(\text{rand}_a, \text{msg sender})$. :::warning -We need to use different randomness for Bob's note here to avoid potential privacy leak (see [description](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L491) of `setup_refund` function) +We need to use different randomness for Bob's note here to avoid potential privacy leak (see [description](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L491) of `setup_refund` function) ::: $$ @@ -144,7 +144,7 @@ We can see the complete implementation of creating and completing partial notes #### `fee_entrypoint_private` -```rust title="fee_entrypoint_private" showLineNumbers +```rust title="fee_entrypoint_private" showLineNumbers #[private] fn fee_entrypoint_private(max_fee: u128, nonce: Field) { let accepted_asset = storage.config.read().accepted_asset; @@ -170,7 +170,7 @@ fn fee_entrypoint_private(max_fee: u128, nonce: Field) { context.set_as_fee_payer(); } ``` -> Source code: noir-projects/noir-contracts/contracts/fees/fpc_contract/src/main.nr#L78-L103 +> Source code: noir-projects/noir-contracts/contracts/fees/fpc_contract/src/main.nr#L78-L103 The `fee_entrypoint_private` function sets the `complete_refund` function to be called at the end of the public function execution (`set_public_teardown_function`). @@ -178,7 +178,7 @@ This ensures that the refund partial note will be completed for the user. #### `complete_refund` -```rust title="complete_refund" showLineNumbers +```rust title="complete_refund" showLineNumbers #[public] #[internal] fn _complete_refund( @@ -201,7 +201,7 @@ fn _complete_refund( ); } ``` -> Source code: noir-projects/noir-contracts/contracts/fees/fpc_contract/src/main.nr#L107-L129 +> Source code: noir-projects/noir-contracts/contracts/fees/fpc_contract/src/main.nr#L107-L129 ## Note discovery diff --git a/docs/versioned_docs/version-Latest/aztec/concepts/call_types.md b/docs/versioned_docs/version-Latest/aztec/concepts/call_types.md index a78c843bcf49..41bec74f1c21 100644 --- a/docs/versioned_docs/version-Latest/aztec/concepts/call_types.md +++ b/docs/versioned_docs/version-Latest/aztec/concepts/call_types.md @@ -102,10 +102,10 @@ Contract functions marked with `#[private]` can only be called privately, and as Private functions from other contracts can be called either regularly or statically by using the `.call()` and `.static_call` functions. They will also be 'executed' (i.e. proved) in the user's device, and `static_call` will fail if any state changes are attempted (like the EVM's `STATICCALL`). -```rust title="private_call" showLineNumbers +```rust title="private_call" showLineNumbers let _ = Token::at(stable_coin).burn_private(from, amount, nonce).call(&mut context); ``` -> Source code: noir-projects/noir-contracts/contracts/app/lending_contract/src/main.nr#L254-L256 +> Source code: noir-projects/noir-contracts/contracts/app/lending_contract/src/main.nr#L254-L256 Unlike the EVM however, private execution doesn't revert in the traditional way: in case of error (e.g. a failed assertion, a state changing operation in a static context, etc.) the proof generation simply fails and no transaction request is generated, spending no network gas or user funds. @@ -116,22 +116,22 @@ Since public execution can only be performed by the sequencer, public functions Since the public call is made asynchronously, any return values or side effects are not available during private execution. If the public function fails once executed, the entire transaction is reverted including state changes caused by the private part, such as new notes or nullifiers. Note that this does result in gas being spent, like in the case of the EVM. -```rust title="enqueue_public" showLineNumbers +```rust title="enqueue_public" showLineNumbers Lending::at(context.this_address()) ._deposit(AztecAddress::from_field(on_behalf_of), amount, collateral_asset) .enqueue(&mut context); ``` -> Source code: noir-projects/noir-contracts/contracts/app/lending_contract/src/main.nr#L119-L123 +> Source code: noir-projects/noir-contracts/contracts/app/lending_contract/src/main.nr#L119-L123 It is also possible to create public functions that can _only_ be invoked by privately enqueueing a call from the same contract, which can be very useful to update public state after private execution (e.g. update a token's supply after privately minting). This is achieved by annotating functions with `#[internal]`. A common pattern is to enqueue public calls to check some validity condition on public state, e.g. that a deadline has not expired or that some public value is set. -```rust title="enqueueing" showLineNumbers +```rust title="enqueueing" showLineNumbers Router::at(ROUTER_ADDRESS).check_block_number(operation, value).call(context); ``` -> Source code: noir-projects/noir-contracts/contracts/protocol/router_contract/src/utils.nr#L17-L19 +> Source code: noir-projects/noir-contracts/contracts/protocol/router_contract/src/utils.nr#L17-L19 Note that this reveals what public function is being called on what contract, and perhaps more importantly which contract enqueued the call during private execution. @@ -139,15 +139,15 @@ For this reason we've created a canonical router contract which implements some An example of how a deadline can be checked using the router contract follows: -```rust title="call-check-deadline" showLineNumbers +```rust title="call-check-deadline" showLineNumbers privately_check_timestamp(Comparator.LT, config.deadline, &mut context); ``` -> Source code: noir-projects/noir-contracts/contracts/app/crowdfunding_contract/src/main.nr#L68-L70 +> Source code: noir-projects/noir-contracts/contracts/app/crowdfunding_contract/src/main.nr#L68-L70 `privately_check_timestamp` and `privately_check_block_number` are helper functions around the call to the router contract: -```rust title="helper_router_functions" showLineNumbers +```rust title="helper_router_functions" showLineNumbers /// Asserts that the current timestamp in the enqueued public call enqueued by `check_timestamp` satisfies /// the `operation` with respect to the `value. Preserves privacy by performing the check via the router contract. /// This conceals an address of the calling contract by setting `context.msg_sender` to the router contract address. @@ -162,12 +162,12 @@ pub fn privately_check_block_number(operation: u8, value: Field, context: &mut P Router::at(ROUTER_ADDRESS).check_block_number(operation, value).call(context); } ``` -> Source code: noir-projects/noir-contracts/contracts/protocol/router_contract/src/utils.nr#L5-L21 +> Source code: noir-projects/noir-contracts/contracts/protocol/router_contract/src/utils.nr#L5-L21 This is what the implementation of the check timestamp functionality looks like: -```rust title="check_timestamp" showLineNumbers +```rust title="check_timestamp" showLineNumbers /// Asserts that the current timestamp in the enqueued public call satisfies the `operation` with respect /// to the `value. #[private] @@ -186,7 +186,7 @@ fn _check_timestamp(operation: u8, value: u64) { assert(compare(lhs_field, operation, rhs_field), "Timestamp mismatch."); } ``` -> Source code: noir-projects/noir-contracts/contracts/protocol/router_contract/src/main.nr#L13-L31 +> Source code: noir-projects/noir-contracts/contracts/protocol/router_contract/src/main.nr#L13-L31 :::note @@ -195,7 +195,7 @@ To add it as a dependency point to the aztec-packages repository instead: ```toml [dependencies] -aztec = { git = "https://github.com/AztecProtocol/aztec-packages/", tag = "v0.87.3", directory = "noir-projects/noir-contracts/contracts/protocol/router_contract/src" } +aztec = { git = "https://github.com/AztecProtocol/aztec-packages/", tag = "v0.87.4", directory = "noir-projects/noir-contracts/contracts/protocol/router_contract/src" } ``` ::: @@ -212,12 +212,12 @@ Since private calls are always run in a user's device, it is not possible to per Public functions in other contracts can be called both regularly and statically, just like on the EVM. -```rust title="public_call" showLineNumbers +```rust title="public_call" showLineNumbers Token::at(config.accepted_asset) .transfer_in_public(context.msg_sender(), context.this_address(), max_fee, nonce) .enqueue(&mut context); ``` -> Source code: noir-projects/noir-contracts/contracts/fees/fpc_contract/src/main.nr#L156-L160 +> Source code: noir-projects/noir-contracts/contracts/fees/fpc_contract/src/main.nr#L156-L160 :::note @@ -236,21 +236,21 @@ There are three different ways to execute an Aztec contract function using the ` This is used to get a result out of an execution, either private or public. It creates no transaction and spends no gas. The mental model is fairly close to that of [`eth_call`](#eth_call), in that it can be used to call any type of function, simulate its execution and get a result out of it. `simulate` is also the only way to run [utility functions](#utility). -```rust title="public_getter" showLineNumbers +```rust title="public_getter" showLineNumbers #[public] #[view] fn get_authorized() -> AztecAddress { storage.authorized.get_current_value() } ``` -> Source code: noir-projects/noir-contracts/contracts/app/auth_contract/src/main.nr#L42-L50 +> Source code: noir-projects/noir-contracts/contracts/app/auth_contract/src/main.nr#L42-L50 -```typescript title="simulate_function" showLineNumbers +```typescript title="simulate_function" showLineNumbers const balance = await contract.methods.balance_of_public(newWallet.getAddress()).simulate(); expect(balance).toEqual(1n); ``` -> Source code: yarn-project/end-to-end/src/composed/docs_examples.test.ts#L54-L57 +> Source code: yarn-project/end-to-end/src/composed/docs_examples.test.ts#L54-L57 :::warning @@ -261,19 +261,19 @@ No correctness is guaranteed on the result of `simulate`! Correct execution is e This creates and returns a transaction request, which includes proof of correct private execution and side-effects. The request is not broadcast however, and no gas is spent. It is typically used in testing contexts to inspect transaction parameters or to check for execution failure. -```typescript title="local-tx-fails" showLineNumbers +```typescript title="local-tx-fails" showLineNumbers const call = token.methods.transfer(recipient.getAddress(), 200n); await expect(call.simulate()).rejects.toThrow(/Balance too low/); ``` -> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L123-L126 +> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L123-L126 #### `send` This is the same as [`prove`](#prove) except it also broadcasts the transaction and returns a receipt. This is how transactions are sent, getting them to be included in blocks and spending gas. It is similar to [`eth_sendTransaction`](#eth_sendtransaction), except it also performs some work on the user's device, namely the production of the proof for the private part of the transaction. -```typescript title="send_tx" showLineNumbers +```typescript title="send_tx" showLineNumbers await contract.methods.buy_pack(seed).send().wait(); ``` -> Source code: yarn-project/end-to-end/src/e2e_card_game.test.ts#L129-L131 +> Source code: yarn-project/end-to-end/src/e2e_card_game.test.ts#L129-L131 diff --git a/docs/versioned_docs/version-Latest/aztec/concepts/fees.md b/docs/versioned_docs/version-Latest/aztec/concepts/fees.md index 5dbff7e6e910..dc18c536cfdb 100644 --- a/docs/versioned_docs/version-Latest/aztec/concepts/fees.md +++ b/docs/versioned_docs/version-Latest/aztec/concepts/fees.md @@ -52,7 +52,7 @@ import { Gas_Settings_Components, Gas_Settings, Tx_Teardown_Phase } from '@site/ These are: -```javascript title="gas_settings_vars" showLineNumbers +```javascript title="gas_settings_vars" showLineNumbers /** Gas usage and fees limits set by the transaction sender for different dimensions and phases. */ export class GasSettings { constructor( @@ -62,7 +62,7 @@ export class GasSettings { public readonly maxPriorityFeesPerGas: GasFees, ) {} ``` -> Source code: yarn-project/stdlib/src/gas/gas_settings.ts#L11-L20 +> Source code: yarn-project/stdlib/src/gas/gas_settings.ts#L11-L20 diff --git a/docs/versioned_docs/version-Latest/aztec/concepts/transactions.md b/docs/versioned_docs/version-Latest/aztec/concepts/transactions.md index 148bde0d2139..46f938ab787a 100644 --- a/docs/versioned_docs/version-Latest/aztec/concepts/transactions.md +++ b/docs/versioned_docs/version-Latest/aztec/concepts/transactions.md @@ -57,7 +57,7 @@ Transaction requests are how transactions are constructed and sent to the networ In Aztec.js: -```javascript title="constructor" showLineNumbers +```javascript title="constructor" showLineNumbers constructor( /** Sender. */ public origin: AztecAddress, @@ -71,21 +71,21 @@ constructor( public salt: Fr, ) {} ``` -> Source code: yarn-project/stdlib/src/tx/tx_request.ts#L15-L28 +> Source code: yarn-project/stdlib/src/tx/tx_request.ts#L15-L28 Where: - `origin` is the account contract where the transaction is initiated from. - `functionData` contains the function selector and indicates whether the function is private or public. -- `argsHash` is the hash of the arguments of all of the calls to be executed. The complete set of arguments is passed to the PXE as part of the [TxExecutionRequest](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/yarn-project/stdlib/src/tx/tx_execution_request.ts) and checked against this hash. +- `argsHash` is the hash of the arguments of all of the calls to be executed. The complete set of arguments is passed to the PXE as part of the [TxExecutionRequest](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/yarn-project/stdlib/src/tx/tx_execution_request.ts) and checked against this hash. - `txContext` contains the chain id, version, and gas settings. The `functionData` includes an `AppPayload`, which includes information about the application functions and arguments, and a `FeePayload`, which includes info about how to pay for the transaction. -An account contract validates that the transaction request has been authorized via its specified authorization mechanism, via the `is_valid_impl` function (e.g. [an ECDSA signature](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/noir-projects/noir-contracts/contracts/account/ecdsa_k_account_contract/src/main.nr#L56-L57), generated [in JS](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/yarn-project/accounts/src/ecdsa/ecdsa_k/account_contract.ts#L30)). +An account contract validates that the transaction request has been authorized via its specified authorization mechanism, via the `is_valid_impl` function (e.g. [an ECDSA signature](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/noir-projects/noir-contracts/contracts/account/ecdsa_k_account_contract/src/main.nr#L56-L57), generated [in JS](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/yarn-project/accounts/src/ecdsa/ecdsa_k/account_contract.ts#L30)). -Transaction requests are simulated in the PXE in order to generate the necessary inputs for generating proofs. Once transactions are proven, a [transaction object](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/yarn-project/stdlib/src/tx/tx.ts#L26) is created and can be sent to the network to be included in a block. +Transaction requests are simulated in the PXE in order to generate the necessary inputs for generating proofs. Once transactions are proven, a [transaction object](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/yarn-project/stdlib/src/tx/tx.ts#L26) is created and can be sent to the network to be included in a block. #### Contract Interaction Methods @@ -103,7 +103,7 @@ And fee utilities: ##### `create` -```javascript title="create" showLineNumbers +```javascript title="create" showLineNumbers /** * Create a transaction execution request that represents this call, encoded and authenticated by the * user's wallet, ready to be simulated. @@ -112,12 +112,12 @@ And fee utilities: */ public override async create(options: SendMethodOptions = {}): Promise { ``` -> Source code: yarn-project/aztec.js/src/contract/contract_function_interaction.ts#L60-L68 +> Source code: yarn-project/aztec.js/src/contract/contract_function_interaction.ts#L60-L68 ##### `simulate` -```javascript title="simulate" showLineNumbers +```javascript title="simulate" showLineNumbers /** * Simulate a transaction and get its return values * Differs from prove in a few important ways: @@ -133,12 +133,12 @@ public async simulate( options: SimulateMethodOptions = {}, ): Promise> { ``` -> Source code: yarn-project/aztec.js/src/contract/contract_function_interaction.ts#L110-L125 +> Source code: yarn-project/aztec.js/src/contract/contract_function_interaction.ts#L110-L125 ##### `prove` -```javascript title="prove" showLineNumbers +```javascript title="prove" showLineNumbers /** * Proves a transaction execution request and returns a tx object ready to be sent. * @param options - optional arguments to be used in the creation of the transaction @@ -146,12 +146,12 @@ public async simulate( */ public async prove(options: SendMethodOptions = {}): Promise { ``` -> Source code: yarn-project/aztec.js/src/contract/base_contract_interaction.ts#L55-L62 +> Source code: yarn-project/aztec.js/src/contract/base_contract_interaction.ts#L55-L62 ##### `send` -```javascript title="send" showLineNumbers +```javascript title="send" showLineNumbers /** * Sends a transaction to the contract function with the specified options. * This function throws an error if called on a utility function. @@ -163,12 +163,12 @@ public async prove(options: SendMethodOptions = {}): Promise { */ public send(options: SendMethodOptions = {}): SentTx { ``` -> Source code: yarn-project/aztec.js/src/contract/base_contract_interaction.ts#L67-L78 +> Source code: yarn-project/aztec.js/src/contract/base_contract_interaction.ts#L67-L78 ##### `estimateGas` -```javascript title="estimateGas" showLineNumbers +```javascript title="estimateGas" showLineNumbers /** * Estimates gas for a given tx request and returns gas limits for it. * @param opts - Options. @@ -179,12 +179,12 @@ public async estimateGas( opts?: Omit, ): Promise> { ``` -> Source code: yarn-project/aztec.js/src/contract/base_contract_interaction.ts#L86-L96 +> Source code: yarn-project/aztec.js/src/contract/base_contract_interaction.ts#L86-L96 ##### `getFeeOptions` -```javascript title="getFeeOptions" showLineNumbers +```javascript title="getFeeOptions" showLineNumbers /** * Return fee options based on the user opts, estimating tx gas if needed. * @param executionPayload - Execution payload to get the fee for @@ -198,12 +198,12 @@ protected async getFeeOptions( options: TxExecutionOptions, ): Promise { ``` -> Source code: yarn-project/aztec.js/src/contract/base_contract_interaction.ts#L125-L138 +> Source code: yarn-project/aztec.js/src/contract/base_contract_interaction.ts#L125-L138 ### Batch Transactions -Batched transactions are a way to send multiple transactions in a single call. They are created by the [`BatchCall` class in Aztec.js](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/yarn-project/aztec.js/src/contract/batch_call.ts). This allows a batch of function calls from a single wallet to be sent as a single transaction through a wallet. +Batched transactions are a way to send multiple transactions in a single call. They are created by the [`BatchCall` class in Aztec.js](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/yarn-project/aztec.js/src/contract/batch_call.ts). This allows a batch of function calls from a single wallet to be sent as a single transaction through a wallet. ### Enabling Transaction Semantics diff --git a/docs/versioned_docs/version-Latest/aztec/concepts/wallets/architecture.md b/docs/versioned_docs/version-Latest/aztec/concepts/wallets/architecture.md index 56cf184f5c85..6b334e821ac0 100644 --- a/docs/versioned_docs/version-Latest/aztec/concepts/wallets/architecture.md +++ b/docs/versioned_docs/version-Latest/aztec/concepts/wallets/architecture.md @@ -19,7 +19,7 @@ In code, this translates to a wallet implementing an **AccountInterface** interf The account interface is used for creating an _execution request_ out of one or more _function calls_ requested by a dapp, as well as creating an _auth witness_ for a given message hash. Account contracts are expected to handle multiple function calls per transaction, since dapps may choose to batch multiple actions into a single request to the wallet. -```typescript title="account-interface" showLineNumbers +```typescript title="account-interface" showLineNumbers /** * Handler for interfacing with an account. Knows how to create transaction execution @@ -39,14 +39,14 @@ export interface AccountInterface extends EntrypointInterface, AuthWitnessProvid getVersion(): Fr; } ``` -> Source code: yarn-project/aztec.js/src/account/interface.ts#L6-L25 +> Source code: yarn-project/aztec.js/src/account/interface.ts#L6-L25 ## PXE interface A wallet exposes the PXE interface to dapps by running a PXE instance. The PXE requires a keystore and a database implementation for storing keys, private state, and recipient encryption public keys. -```typescript title="pxe-interface" showLineNumbers +```typescript title="pxe-interface" showLineNumbers /** * Private eXecution Environment (PXE) runs locally for each user, providing functionality for all the operations * needed to interact with the Aztec network, including account management, private data management, @@ -386,5 +386,5 @@ export interface PXE { getPublicEvents(eventMetadata: EventMetadataDefinition, from: number, limit: number): Promise; } ``` -> Source code: yarn-project/stdlib/src/interfaces/pxe.ts#L49-L388 +> Source code: yarn-project/stdlib/src/interfaces/pxe.ts#L49-L388 diff --git a/docs/versioned_docs/version-Latest/aztec/concepts/wallets/index.md b/docs/versioned_docs/version-Latest/aztec/concepts/wallets/index.md index 9eb4a19356aa..33725b427f0c 100644 --- a/docs/versioned_docs/version-Latest/aztec/concepts/wallets/index.md +++ b/docs/versioned_docs/version-Latest/aztec/concepts/wallets/index.md @@ -20,7 +20,7 @@ In addition to these usual responsibilities, wallets in Aztec also need to track The first step for any wallet is to let the user set up their [accounts](../accounts/index.md). An account in Aztec is represented on-chain by its corresponding account contract that the user must deploy to begin interacting with the network. This account contract dictates how transactions are authenticated and executed. -A wallet must support at least one specific account contract implementation, which means being able to deploy such a contract, as well as interacting with it when sending transactions. Code-wise, this requires [implementing the `AccountContract` interface](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/yarn-project/aztec.js/src/account/interface.ts). +A wallet must support at least one specific account contract implementation, which means being able to deploy such a contract, as well as interacting with it when sending transactions. Code-wise, this requires [implementing the `AccountContract` interface](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/yarn-project/aztec.js/src/account/interface.ts). Note that users must be able to receive funds in Aztec before deploying their account. A wallet should let a user generate a [deterministic complete address](../accounts/keys.md#address-keys) without having to interact with the network, so they can share it with others to receive funds. This requires that the wallet pins a specific contract implementation, its initialization arguments, a deployment salt, and a privacy key. These values yield a deterministic address, so when the account contract is actually deployed, it is available at the precalculated address. Once the account contract is deployed, the user can start sending transactions using it as the transaction origin. diff --git a/docs/versioned_docs/version-Latest/aztec/smart_contracts/functions/attributes.md b/docs/versioned_docs/version-Latest/aztec/smart_contracts/functions/attributes.md index 6ca29bd4ff7c..8a185648b64a 100644 --- a/docs/versioned_docs/version-Latest/aztec/smart_contracts/functions/attributes.md +++ b/docs/versioned_docs/version-Latest/aztec/smart_contracts/functions/attributes.md @@ -18,18 +18,18 @@ To help illustrate how this interacts with the internals of Aztec and its kernel #### Before expansion -```rust title="simple_macro_example" showLineNumbers +```rust title="simple_macro_example" showLineNumbers #[private] fn simple_macro_example(a: Field, b: Field) -> Field { a + b } ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L156-L161 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L156-L161 #### After expansion -```rust title="simple_macro_example_expanded" showLineNumbers +```rust title="simple_macro_example_expanded" showLineNumbers fn simple_macro_example_expanded( // ************************************************************ // The private context inputs are made available to the circuit by the kernel @@ -61,7 +61,7 @@ fn simple_macro_example_expanded( // ************************************************************ } ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L167-L212 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L167-L212 #### The expansion broken down @@ -69,10 +69,10 @@ fn simple_macro_example_expanded( Viewing the expanded Aztec contract uncovers a lot about how Aztec contracts interact with the kernel. To aid with developing intuition, we will break down each inserted line. **Receiving context from the kernel.** -```rust title="context-example-inputs" showLineNumbers +```rust title="context-example-inputs" showLineNumbers inputs: PrivateContextInputs, ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L171-L173 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L171-L173 Private function calls are able to interact with each other through orchestration from within the kernel circuits. The kernel circuit forwards information to each contract function (recall each contract function is a circuit). This information then becomes part of the private context. @@ -81,10 +81,10 @@ For example, within each private function we can access some global variables. T The kernel checks that all of the values passed to each circuit in a function call are the same. **Returning the context to the kernel.** -```rust title="context-example-return" showLineNumbers +```rust title="context-example-return" showLineNumbers ) -> PrivateCircuitPublicInputs { ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L179-L181 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L179-L181 The contract function must return information about the execution back to the kernel. This is done through a rigid structure we call the `PrivateCircuitPublicInputs`. @@ -95,12 +95,12 @@ The contract function must return information about the execution back to the ke This structure contains a host of information about the executed program. It will contain any newly created nullifiers, any messages to be sent to l2 and most importantly it will contain the return values of the function. **Hashing the function inputs.** -```rust title="context-example-hasher" showLineNumbers +```rust title="context-example-hasher" showLineNumbers let mut args_hasher = dep::aztec::hash::ArgsHasher::new(); args_hasher.add(a); args_hasher.add(b); ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L184-L188 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L184-L188 _What is the hasher and why is it needed?_ @@ -108,30 +108,30 @@ _What is the hasher and why is it needed?_ Inside the kernel circuits, the inputs to functions are reduced to a single value; the inputs hash. This prevents the need for multiple different kernel circuits; each supporting differing numbers of inputs. The hasher abstraction that allows us to create an array of all of the inputs that can be reduced to a single value. **Creating the function's context.** -```rust title="context-example-context" showLineNumbers +```rust title="context-example-context" showLineNumbers let mut context = PrivateContext::new(inputs, args_hasher.hash()); ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L190-L192 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L190-L192 Each Aztec function has access to a [context](context) object. This object, although labelled a global variable, is created locally on a users' device. It is initialized from the inputs provided by the kernel, and a hash of the function's inputs. -```rust title="context-example-context-return" showLineNumbers +```rust title="context-example-context-return" showLineNumbers let mut return_hasher = dep::aztec::hash::ArgsHasher::new(); return_hasher.add(result); context.set_return_hash(return_hasher); ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L201-L205 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L201-L205 We use the kernel to pass information between circuits. This means that the return values of functions must also be passed to the kernel (where they can be later passed on to another function). We achieve this by pushing return values to the execution context, which we then pass to the kernel. **Making the contract's storage available** -```rust title="storage-example-context" showLineNumbers +```rust title="storage-example-context" showLineNumbers let mut storage = Storage::init(&mut context); ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L193-L195 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L193-L195 When a `Storage` struct is declared within a contract, the `storage` keyword is made available. As shown in the macro expansion above, this calls the init function on the storage struct with the current function's context. @@ -139,10 +139,10 @@ When a `Storage` struct is declared within a contract, the `storage` keyword is Any state variables declared in the `Storage` struct can now be accessed as normal struct members. **Returning the function context to the kernel.** -```rust title="context-example-finish" showLineNumbers +```rust title="context-example-finish" showLineNumbers context.finish() ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L207-L209 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L207-L209 This function takes the application context, and converts it into the `PrivateCircuitPublicInputs` structure. This structure is then passed to the kernel circuit. @@ -164,7 +164,7 @@ To generate the environment, the simulator gets the block header from the [PXE d Once the execution environment is created, `runUtility` function is invoked on the simulator: -```typescript title="execute_utility_function" showLineNumbers +```typescript title="execute_utility_function" showLineNumbers /** * Runs a utility function. * @param call - The function call to execute. @@ -213,7 +213,7 @@ public async runUtility(call: FunctionCall, authwits: AuthWitness[], scopes?: Az } } ``` -> Source code: yarn-project/simulator/src/private/simulator.ts#L121-L169 +> Source code: yarn-project/simulator/src/private/simulator.ts#L121-L169 This: @@ -225,13 +225,13 @@ This: Beyond using them inside your other functions, they are convenient for providing an interface that reads storage, applies logic and returns values to a UI or test. Below is a snippet from exposing the `balance_of_private` function from a token implementation, which allows a user to easily read their balance, similar to the `balanceOf` function in the ERC20 standard. -```rust title="balance_of_private" showLineNumbers +```rust title="balance_of_private" showLineNumbers #[utility] pub(crate) unconstrained fn balance_of_private(owner: AztecAddress) -> u128 { storage.balances.at(owner).balance_of() } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L676-L681 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L639-L644 :::info @@ -248,14 +248,14 @@ All data inserted into private storage from a public function will be publicly v To create a public function you can annotate it with the `#[public]` attribute. This will make the public context available within the function's execution scope. -```rust title="set_minter" showLineNumbers +```rust title="set_minter" showLineNumbers #[public] fn set_minter(minter: AztecAddress, approve: bool) { assert(storage.admin.read().eq(context.msg_sender()), "caller is not admin"); storage.minters.at(minter).write(approve); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L183-L193 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L183-L193 Under the hood: diff --git a/docs/versioned_docs/version-Latest/aztec/smart_contracts/functions/context.md b/docs/versioned_docs/version-Latest/aztec/smart_contracts/functions/context.md index 3b8014c38a23..27bae6ad2e56 100644 --- a/docs/versioned_docs/version-Latest/aztec/smart_contracts/functions/context.md +++ b/docs/versioned_docs/version-Latest/aztec/smart_contracts/functions/context.md @@ -34,7 +34,7 @@ The following section will cover both contexts. ## The Private Context The code snippet below shows what is contained within the private context. -```rust title="private-context" showLineNumbers +```rust title="private-context" showLineNumbers pub inputs: PrivateContextInputs, pub side_effect_counter: u32, @@ -58,7 +58,7 @@ pub public_call_requests: BoundedVec, MAX_ENQUEUED_CA pub public_teardown_call_request: PublicCallRequest, pub l2_to_l1_msgs: BoundedVec, ``` -> Source code: noir-projects/aztec-nr/aztec/src/context/private_context.nr#L52-L75 +> Source code: noir-projects/aztec-nr/aztec/src/context/private_context.nr#L52-L75 ### Private Context Broken Down @@ -67,7 +67,7 @@ pub l2_to_l1_msgs: BoundedVec, The context inputs includes all of the information that is passed from the kernel circuit into the application circuit. It contains the following values. -```rust title="private-context-inputs" showLineNumbers +```rust title="private-context-inputs" showLineNumbers pub struct PrivateContextInputs { pub call_context: CallContext, pub historical_header: BlockHeader, @@ -75,14 +75,14 @@ pub struct PrivateContextInputs { pub start_side_effect_counter: u32, } ``` -> Source code: noir-projects/aztec-nr/aztec/src/context/inputs/private_context_inputs.nr#L7-L14 +> Source code: noir-projects/aztec-nr/aztec/src/context/inputs/private_context_inputs.nr#L7-L14 As shown in the snippet, the application context is made up of 4 main structures. The call context, the block header, and the private global variables. First of all, the call context. -```rust title="call-context" showLineNumbers +```rust title="call-context" showLineNumbers pub struct CallContext { pub msg_sender: AztecAddress, pub contract_address: AztecAddress, @@ -90,7 +90,7 @@ pub struct CallContext { pub is_static_call: bool, } ``` -> Source code: noir-projects/noir-protocol-circuits/crates/types/src/abis/call_context.nr#L9-L16 +> Source code: noir-projects/noir-protocol-circuits/crates/types/src/abis/call_context.nr#L9-L16 The call context contains information about the current call being made: @@ -115,7 +115,7 @@ The call context contains information about the current call being made: Another structure that is contained within the context is the `BlockHeader` object, which is the header of the block used to generate proofs against. -```rust title="block-header" showLineNumbers +```rust title="block-header" showLineNumbers pub struct BlockHeader { pub last_archive: AppendOnlyTreeSnapshot, pub content_commitment: ContentCommitment, @@ -125,21 +125,21 @@ pub struct BlockHeader { pub total_mana_used: Field, } ``` -> Source code: noir-projects/noir-protocol-circuits/crates/types/src/block_header.nr#L11-L20 +> Source code: noir-projects/noir-protocol-circuits/crates/types/src/block_header.nr#L11-L20 ### Transaction Context The private context provides access to the transaction context as well, which are user-defined values for the transaction in general that stay constant throughout its execution. -```rust title="tx-context" showLineNumbers +```rust title="tx-context" showLineNumbers pub struct TxContext { pub chain_id: Field, pub version: Field, pub gas_settings: GasSettings, } ``` -> Source code: noir-projects/noir-protocol-circuits/crates/types/src/transaction/tx_context.nr#L8-L14 +> Source code: noir-projects/noir-protocol-circuits/crates/types/src/transaction/tx_context.nr#L8-L14 ### Args Hash @@ -159,10 +159,10 @@ return_values : BoundedVec\, Some data structures impose time constraints, e.g. they may make it so that a value can only be changed after a certain delay. Interacting with these in private involves creating proofs that are only valid as long as they are included before a certain future point in time. To achieve this, the `set_tx_max_block_number` function can be used to set this property: -```rust title="max-block-number" showLineNumbers +```rust title="max-block-number" showLineNumbers pub fn set_tx_max_block_number(&mut self, max_block_number: u32) { ``` -> Source code: noir-projects/aztec-nr/aztec/src/context/private_context.nr#L228-L230 +> Source code: noir-projects/aztec-nr/aztec/src/context/private_context.nr#L228-L230 A transaction that requests a maximum block number will never be included in a block with a block number larger than the requested value, since it would be considered invalid. This can also be used to make transactions automatically expire after some time if not included. @@ -205,7 +205,7 @@ The Public Context includes all of the information passed from the `Public VM` i The public global variables are provided by the rollup sequencer and consequently contain some more values than the private global variables. -```rust title="global-variables" showLineNumbers +```rust title="global-variables" showLineNumbers pub struct GlobalVariables { pub chain_id: Field, pub version: Field, @@ -217,5 +217,5 @@ pub struct GlobalVariables { pub gas_fees: GasFees, } ``` -> Source code: noir-projects/noir-protocol-circuits/crates/types/src/abis/global_variables.nr#L9-L20 +> Source code: noir-projects/noir-protocol-circuits/crates/types/src/abis/global_variables.nr#L9-L20 diff --git a/docs/versioned_docs/version-Latest/aztec/smart_contracts/oracles/index.md b/docs/versioned_docs/version-Latest/aztec/smart_contracts/oracles/index.md index 075674c200ab..e9871247b618 100644 --- a/docs/versioned_docs/version-Latest/aztec/smart_contracts/oracles/index.md +++ b/docs/versioned_docs/version-Latest/aztec/smart_contracts/oracles/index.md @@ -20,10 +20,10 @@ If we fetch the notes using an oracle call, we can keep the function signature i Oracles introduce **non-determinism** into a circuit, and thus are `unconstrained`. It is important that any information that is injected into a circuit through an oracle is later constrained for correctness. Otherwise, the circuit will be **under-constrained** and potentially insecure! `Aztec.nr` has a module dedicated to its oracles. If you are interested, you can view them by following the link below: -```rust title="oracles-module" showLineNumbers +```rust title="oracles-module" showLineNumbers /// Oracles module ``` -> Source code: noir-projects/aztec-nr/aztec/src/oracle/mod.nr#L1-L3 +> Source code: noir-projects/aztec-nr/aztec/src/oracle/mod.nr#L1-L3 ## Inbuilt oracles diff --git a/docs/versioned_docs/version-Latest/developers/guides/js_apps/authwit.md b/docs/versioned_docs/version-Latest/developers/guides/js_apps/authwit.md index 76e0ba5fee87..eebbdfcf2e6a 100644 --- a/docs/versioned_docs/version-Latest/developers/guides/js_apps/authwit.md +++ b/docs/versioned_docs/version-Latest/developers/guides/js_apps/authwit.md @@ -34,7 +34,7 @@ If you are using public authwit (ie using `assert_current_call_valid_authwit_pub Here is an example implementation: -```typescript title="public_deploy_accounts" showLineNumbers +```typescript title="public_deploy_accounts" showLineNumbers export async function ensureAccountsPubliclyDeployed(sender: Wallet, accountsToDeploy: Wallet[]) { // We have to check whether the accounts are already deployed. This can happen if the test runs against // the sandbox and the test accounts exist @@ -63,15 +63,15 @@ export async function ensureAccountsPubliclyDeployed(sender: Wallet, accountsToD await batch.send().wait(); } ``` -> Source code: yarn-project/end-to-end/src/fixtures/utils.ts#L631-L659 +> Source code: yarn-project/end-to-end/src/fixtures/utils.ts#L634-L662 You would then call this like so: -```typescript title="public_deploy_accounts" showLineNumbers +```typescript title="public_deploy_accounts" showLineNumbers await ensureAccountsPubliclyDeployed(wallets[0], wallets.slice(0, 2)); ``` -> Source code: yarn-project/end-to-end/src/e2e_authwit.test.ts#L24-L26 +> Source code: yarn-project/end-to-end/src/e2e_authwit.test.ts#L24-L26 ## Define the action @@ -82,12 +82,12 @@ When creating an authwit, you will need to pass the authwit giver, the authwit r You can define the action like this: -```typescript title="authwit_computeAuthWitMessageHash" showLineNumbers +```typescript title="authwit_computeAuthWitMessageHash" showLineNumbers const action = asset .withWallet(wallets[1]) .methods.transfer(wallets[0].getAddress(), wallets[1].getAddress(), amount, nonce); ``` -> Source code: yarn-project/end-to-end/src/e2e_blacklist_token_contract/transfer_private.test.ts#L57-L61 +> Source code: yarn-project/end-to-end/src/e2e_blacklist_token_contract/transfer_private.test.ts#L55-L59 In this example, @@ -101,19 +101,19 @@ In this example, You can hash your own authwit message by creating an inner hash with the data, like this: -```typescript title="compute_inner_authwit_hash" showLineNumbers +```typescript title="compute_inner_authwit_hash" showLineNumbers const innerHash = await computeInnerAuthWitHash([Fr.fromHexString('0xdead')]); ``` -> Source code: yarn-project/end-to-end/src/e2e_authwit.test.ts#L45-L47 +> Source code: yarn-project/end-to-end/src/e2e_authwit.test.ts#L45-L47 Then create the message hash by hashing the inner hash with the authwit receiver address, chainId, and version: -```typescript title="compute_arbitrary_authwit_hash" showLineNumbers +```typescript title="compute_arbitrary_authwit_hash" showLineNumbers const intent = { consumer: auth.address, innerHash }; ``` -> Source code: yarn-project/end-to-end/src/e2e_authwit.test.ts#L48-L51 +> Source code: yarn-project/end-to-end/src/e2e_authwit.test.ts#L48-L51 ## Create the authwit @@ -130,10 +130,10 @@ This is expected to be used alongside [private authwits in Aztec.nr contract](.. Create a private authwit like this: -```typescript title="create_authwit" showLineNumbers +```typescript title="create_authwit" showLineNumbers const witness = await wallets[0].createAuthWit({ caller: wallets[1].getAddress(), action }); ``` -> Source code: yarn-project/end-to-end/src/e2e_blacklist_token_contract/transfer_private.test.ts#L62-L64 +> Source code: yarn-project/end-to-end/src/e2e_blacklist_token_contract/transfer_private.test.ts#L60-L62 In this example, @@ -144,19 +144,19 @@ In this example, If you created an arbitrary message, you can create the authwit by replacing these params with the outer hash: -```typescript title="compute_arbitrary_authwit_hash" showLineNumbers +```typescript title="compute_arbitrary_authwit_hash" showLineNumbers const intent = { consumer: auth.address, innerHash }; ``` -> Source code: yarn-project/end-to-end/src/e2e_authwit.test.ts#L48-L51 +> Source code: yarn-project/end-to-end/src/e2e_authwit.test.ts#L48-L51 Then add it to the wallet of the authwit receiver (the caller of the function): -```typescript title="add_authwit" showLineNumbers +```typescript title="add_authwit" showLineNumbers await action.send({ authWitnesses: [witness] }).wait(); ``` -> Source code: yarn-project/end-to-end/src/e2e_blacklist_token_contract/transfer_private.test.ts#L68-L70 +> Source code: yarn-project/end-to-end/src/e2e_blacklist_token_contract/transfer_private.test.ts#L66-L68 ### Public @@ -165,14 +165,14 @@ This is expected to be used alongside [public authwits in Aztec.nr contract](../ Set a public authwit like this: -```typescript title="set_public_authwit" showLineNumbers +```typescript title="set_public_authwit" showLineNumbers const validateActionInteraction = await wallets[0].setPublicAuthWit( { caller: wallets[1].getAddress(), action }, true, ); await validateActionInteraction.send().wait(); ``` -> Source code: yarn-project/end-to-end/src/e2e_blacklist_token_contract/transfer_public.test.ts#L119-L125 +> Source code: yarn-project/end-to-end/src/e2e_blacklist_token_contract/transfer_public.test.ts#L119-L125 Remember it is a transaction and calls a method in the account contract. In this example, @@ -184,11 +184,11 @@ Remember it is a transaction and calls a method in the account contract. In this If you created an arbitrary message, you would replace the first param struct with the outer hash: -```typescript title="set_public_authwit" showLineNumbers +```typescript title="set_public_authwit" showLineNumbers const validateActionInteraction = await wallets[0].setPublicAuthWit(intent, true); await validateActionInteraction.send().wait(); ``` -> Source code: yarn-project/end-to-end/src/e2e_authwit.test.ts#L155-L158 +> Source code: yarn-project/end-to-end/src/e2e_authwit.test.ts#L155-L158 ## Further reading diff --git a/docs/versioned_docs/version-Latest/developers/guides/js_apps/call_view_function.md b/docs/versioned_docs/version-Latest/developers/guides/js_apps/call_view_function.md index bba5c3c22cd7..dbb76b86d94d 100644 --- a/docs/versioned_docs/version-Latest/developers/guides/js_apps/call_view_function.md +++ b/docs/versioned_docs/version-Latest/developers/guides/js_apps/call_view_function.md @@ -18,31 +18,31 @@ You can learn how to deploy a contract [here](./deploy_contract.md). You will need to import this from Aztec.js: -```typescript title="import_contract" showLineNumbers +```typescript title="import_contract" showLineNumbers import { Contract } from '@aztec/aztec.js'; ``` -> Source code: yarn-project/end-to-end/src/composed/docs_examples.test.ts#L7-L9 +> Source code: yarn-project/end-to-end/src/composed/docs_examples.test.ts#L7-L9 ## Define contract Get a previously deployed contract like this: -```typescript title="get_contract" showLineNumbers +```typescript title="get_contract" showLineNumbers const contract = await Contract.at(deployedContract.address, TokenContractArtifact, wallet); ``` -> Source code: yarn-project/end-to-end/src/composed/docs_examples.test.ts#L45-L47 +> Source code: yarn-project/end-to-end/src/composed/docs_examples.test.ts#L45-L47 ## Simulating function calls Call the `simulate` function on the typescript contract wrapper like this: -```typescript title="simulate_function" showLineNumbers +```typescript title="simulate_function" showLineNumbers const balance = await contract.methods.balance_of_public(newWallet.getAddress()).simulate(); expect(balance).toEqual(1n); ``` -> Source code: yarn-project/end-to-end/src/composed/docs_examples.test.ts#L54-L57 +> Source code: yarn-project/end-to-end/src/composed/docs_examples.test.ts#L54-L57 :::info Note diff --git a/docs/versioned_docs/version-Latest/developers/guides/js_apps/create_account.md b/docs/versioned_docs/version-Latest/developers/guides/js_apps/create_account.md index aff68d17e52e..0650927fc110 100644 --- a/docs/versioned_docs/version-Latest/developers/guides/js_apps/create_account.md +++ b/docs/versioned_docs/version-Latest/developers/guides/js_apps/create_account.md @@ -10,35 +10,35 @@ This guide explains how to create a new account using Aztec.js. You will need to import these libraries: -```typescript title="create_account_imports" showLineNumbers +```typescript title="create_account_imports" showLineNumbers import { getSchnorrAccount } from '@aztec/accounts/schnorr'; import { getDeployedTestAccountsWallets } from '@aztec/accounts/testing'; import { Fr, GrumpkinScalar, createPXEClient } from '@aztec/aztec.js'; ``` -> Source code: yarn-project/end-to-end/src/composed/docs_examples.test.ts#L2-L6 +> Source code: yarn-project/end-to-end/src/composed/docs_examples.test.ts#L2-L6 ## Define arguments needed -```typescript title="define_account_vars" showLineNumbers +```typescript title="define_account_vars" showLineNumbers const PXE_URL = process.env.PXE_URL || 'http://localhost:8080'; const pxe = createPXEClient(PXE_URL); const secretKey = Fr.random(); const signingPrivateKey = GrumpkinScalar.random(); ``` -> Source code: yarn-project/end-to-end/src/composed/docs_examples.test.ts#L18-L23 +> Source code: yarn-project/end-to-end/src/composed/docs_examples.test.ts#L18-L23 ## Create the wallet with these args -```typescript title="create_wallet" showLineNumbers +```typescript title="create_wallet" showLineNumbers // Use a pre-funded wallet to pay for the fees for the deployments. const wallet = (await getDeployedTestAccountsWallets(pxe))[0]; const newAccount = await getSchnorrAccount(pxe, secretKey, signingPrivateKey); await newAccount.deploy({ deployWallet: wallet }).wait(); const newWallet = await newAccount.getWallet(); ``` -> Source code: yarn-project/end-to-end/src/composed/docs_examples.test.ts#L25-L31 +> Source code: yarn-project/end-to-end/src/composed/docs_examples.test.ts#L25-L31 Now you have a new wallet in your PXE! To learn how to use this wallet to deploy a contract, read [this guide](./deploy_contract.md). diff --git a/docs/versioned_docs/version-Latest/developers/guides/js_apps/deploy_contract.md b/docs/versioned_docs/version-Latest/developers/guides/js_apps/deploy_contract.md index 14cfaab6de54..33b9138cb24d 100644 --- a/docs/versioned_docs/version-Latest/developers/guides/js_apps/deploy_contract.md +++ b/docs/versioned_docs/version-Latest/developers/guides/js_apps/deploy_contract.md @@ -37,17 +37,17 @@ This would create a typescript file like `Example.ts` in `./src/artifacts`. Import the typescript artifact into your file. -```typescript title="import_artifact" showLineNumbers +```typescript title="import_artifact" showLineNumbers import { TokenContractArtifact } from '@aztec/noir-contracts.js/Token'; ``` -> Source code: yarn-project/end-to-end/src/sample-dapp/deploy.mjs#L5-L7 +> Source code: yarn-project/end-to-end/src/sample-dapp/deploy.mjs#L5-L7 Then you can use the `Contract` class **or** the [generated contract class](#using-generated-contract-class) to deploy the contract. To use the `Contract` class to deploy a contract: -```typescript title="dapp-deploy" showLineNumbers +```typescript title="dapp-deploy" showLineNumbers const { PXE_URL = 'http://localhost:8080' } = process.env; async function main() { @@ -67,7 +67,7 @@ async function main() { writeFileSync('addresses.json', JSON.stringify(addresses, null, 2)); } ``` -> Source code: yarn-project/end-to-end/src/sample-dapp/deploy.mjs#L13-L32 +> Source code: yarn-project/end-to-end/src/sample-dapp/deploy.mjs#L13-L32 #### Deploy Arguments @@ -78,7 +78,7 @@ The `deploy(...)` method is generated automatically with the typescript class re Additionally the `.send()` method can have a few optional arguments too, which are specified in an optional object: -```typescript title="deploy_options" showLineNumbers +```typescript title="deploy_options" showLineNumbers export type DeployOptions = { /** An optional salt value used to deterministically calculate the contract address. */ contractAddressSalt?: Fr; @@ -92,7 +92,7 @@ export type DeployOptions = { skipInitialization?: boolean; } & SendMethodOptions; ``` -> Source code: yarn-project/aztec.js/src/contract/deploy_method.ts#L32-L45 +> Source code: yarn-project/aztec.js/src/contract/deploy_method.ts#L32-L45 ### Using generated contract class @@ -136,4 +136,4 @@ const contract = await Contract.at(deployedContract.address, TokenContractArtifa :::note You can try running the deployment with the same salt the second time in which case the transaction will fail because the address has been already deployed to. -::: +::: \ No newline at end of file diff --git a/docs/versioned_docs/version-Latest/developers/guides/js_apps/index.md b/docs/versioned_docs/version-Latest/developers/guides/js_apps/index.md index 9fa380c29373..7a122dac22cb 100644 --- a/docs/versioned_docs/version-Latest/developers/guides/js_apps/index.md +++ b/docs/versioned_docs/version-Latest/developers/guides/js_apps/index.md @@ -17,11 +17,11 @@ npm install @aztec/aztec.js At the top of your JavaScript file, you can import what you need, eg: -```typescript title="import_aztecjs" showLineNumbers +```typescript title="import_aztecjs" showLineNumbers import { type AztecAddress, type AztecNode, Fr, type Logger, type PXE, type Wallet, sleep } from '@aztec/aztec.js'; import { TokenContract } from '@aztec/noir-contracts.js/Token'; ``` -> Source code: yarn-project/end-to-end/src/e2e_2_pxes.test.ts#L3-L6 +> Source code: yarn-project/end-to-end/src/e2e_2_pxes.test.ts#L3-L6 ## Flow diff --git a/docs/versioned_docs/version-Latest/developers/guides/js_apps/pay_fees.md b/docs/versioned_docs/version-Latest/developers/guides/js_apps/pay_fees.md index 220dab2c5d24..dad9b27449bc 100644 --- a/docs/versioned_docs/version-Latest/developers/guides/js_apps/pay_fees.md +++ b/docs/versioned_docs/version-Latest/developers/guides/js_apps/pay_fees.md @@ -51,14 +51,14 @@ One way of bridging of tokens is described fully [here](../../../developers/tuto First get the node info and create a public client pointing to the sandbox's anvil L1 node (from foundry): -```javascript title="get_node_info_pub_client" showLineNumbers +```javascript title="get_node_info_pub_client" showLineNumbers const info = await pxe.getNodeInfo(); const publicClient = getPublicClient({ l1RpcUrls: ['http://localhost:8545'], l1ChainId: foundry.id, }); ``` -> Source code: yarn-project/end-to-end/src/spartan/smoke.test.ts#L52-L58 +> Source code: yarn-project/end-to-end/src/spartan/smoke.test.ts#L52-L58 After importing: @@ -69,11 +69,11 @@ import { L1FeeJuicePortalManager } from "@aztec/aztec.js"; Create a new fee juice portal manager and bridge fee juice publicly to Aztec: -```javascript title="bridge_fee_juice" showLineNumbers +```javascript title="bridge_fee_juice" showLineNumbers const portal = await L1FeeJuicePortalManager.new(pxe, l1Client, log); const claim = await portal.bridgeTokensPublic(recipient, amount, true /* mint */); ``` -> Source code: yarn-project/end-to-end/src/spartan/setup_test_wallets.ts#L110-L113 +> Source code: yarn-project/end-to-end/src/spartan/setup_test_wallets.ts#L110-L113 For the mechanisms to complete bridging between L1 and Aztec, we have to wait for 2 Aztec blocks to progress. This can be triggered manually by sending 2 transactions in the sandbox, or by waiting for 2 blocks on a public network. After this, an account should have its fee juice ready to use in transactions. @@ -102,14 +102,14 @@ Note: this example is a public token transfer call, but can equally be a private import { FeeJuicePaymentMethod } from "@aztec/aztec.js"; ``` -```javascript title="pay_fee_juice_send" showLineNumbers +```javascript title="pay_fee_juice_send" showLineNumbers const paymentMethod = new FeeJuicePaymentMethod(aliceAddress); const { transactionFee } = await bananaCoin.methods .transfer_in_public(aliceAddress, bobAddress, 1n, 0n) .send({ fee: { gasSettings, paymentMethod } }) .wait(); ``` -> Source code: yarn-project/end-to-end/src/e2e_fees/fee_juice_payments.test.ts#L96-L102 +> Source code: yarn-project/end-to-end/src/e2e_fees/fee_juice_payments.test.ts#L96-L102 **The equivalent to specify fees via CLI...** @@ -126,13 +126,13 @@ Here we will use the `claim` object previously from the bridging section, and th import { FeeJuicePaymentMethodWithClaim } from "@aztec/aztec.js"; ``` -```javascript title="claim_and_deploy" showLineNumbers +```javascript title="claim_and_deploy" showLineNumbers const wallet = await account.getWallet(); const paymentMethod = new FeeJuicePaymentMethodWithClaim(wallet, claim); const sentTx = account.deploy({ fee: { paymentMethod } }); const txHash = await sentTx.getTxHash(); ``` -> Source code: yarn-project/bot/src/factory.ts#L124-L129 +> Source code: yarn-project/bot/src/factory.ts#L124-L129 **The equivalent to specify fees via CLI...** @@ -145,7 +145,7 @@ Claiming bridged fee juice and using it to pay for transaction fees results in f Calling a function, in this case checking the balance of the fee juice contract: -```javascript title="claim_and_pay" showLineNumbers +```javascript title="claim_and_pay" showLineNumbers const paymentMethod = new FeeJuicePaymentMethodWithClaim(bobWallet, claim); const receipt = await feeJuiceContract .withWallet(bobWallet) @@ -153,7 +153,7 @@ const receipt = await feeJuiceContract .send({ fee: { gasSettings, paymentMethod } }) .wait(); ``` -> Source code: yarn-project/end-to-end/src/e2e_fees/fee_juice_payments.test.ts#L77-L84 +> Source code: yarn-project/end-to-end/src/e2e_fees/fee_juice_payments.test.ts#L77-L84 ### Fee Paying Contract @@ -191,7 +191,7 @@ await pxe.registerContract({ The fee payment method is created and used as follows, with similar syntax for private or public fee payments: -```javascript title="fpc" showLineNumbers +```javascript title="fpc" showLineNumbers const tx = await bananaCoin.methods .transfer_in_public(aliceAddress, bobAddress, bananasToSendToBob, 0) .send({ @@ -202,12 +202,12 @@ const tx = await bananaCoin.methods }) .wait(); ``` -> Source code: yarn-project/end-to-end/src/e2e_fees/public_payments.test.ts#L58-L68 +> Source code: yarn-project/end-to-end/src/e2e_fees/public_payments.test.ts#L58-L68 In this example, thanks to this FPC's `accepted_asset` being banana tokens, Alice only needs to hold this token and not fee juice. The asset that a FPC accepts for paying fees is determined when the FPC is deployed. The function being called happens to also be a transfer of banana tokens to Bob. -More on FPCs [here](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.3/noir-projects/noir-contracts/contracts/fees/fpc_contract/src/main.nr) +More on FPCs [here](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.4/noir-projects/noir-contracts/contracts/fees/fpc_contract/src/main.nr) See this [section](../../reference/environment_reference/cli_wallet_reference.md#fee-paying-contract) for paying fees via an FPC using the CLI wallet. @@ -249,7 +249,7 @@ const paymentMethod = new SponsoredFeePaymentMethod(sponseredFPC.address); You can see an example implementation for `getSponsoredFPCInstance()` [here](https://github.com/AztecProtocol/aztec-packages/blob/360a5f628b4edaf1ea9b328d9e9231f60fdc81a0/yarn-project/aztec/src/sandbox/sponsored_fpc.ts#L5). Once this is set up, a transaction can specify this as the `paymentMethod` in the fee object. -You can see an example of how to get a deployed instance of a sponsored FPC in the sandbox [here](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/yarn-project/aztec/src/sandbox/sponsored_fpc.ts#L15). +You can see an example of how to get a deployed instance of a sponsored FPC in the sandbox [here](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/yarn-project/aztec/src/sandbox/sponsored_fpc.ts#L15). For example, a contract can be deployed with an fpc as follows: ```ts @@ -263,7 +263,7 @@ You can find the corresponding CLI command info [here](../../reference/environme Functions pertaining to sending a transaction, such as `deploy` and `send`, each include a `fee` variable defined with the following (optional) parameters: -```javascript title="user_fee_options" showLineNumbers +```javascript title="user_fee_options" showLineNumbers /** Fee options as set by a user. */ export type UserFeeOptions = { /** The fee payment method to use */ @@ -278,25 +278,25 @@ export type UserFeeOptions = { estimatedGasPadding?: number; }; ``` -> Source code: yarn-project/entrypoints/src/interfaces.ts#L79-L93 +> Source code: yarn-project/entrypoints/src/interfaces.ts#L79-L93 ### Fee Payment Method -The `paymentMethod` is an object for the type of payment. Each of the implementations can be found [here](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/yarn-project/aztec.js/src/fee). For example: +The `paymentMethod` is an object for the type of payment. Each of the implementations can be found [here](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/yarn-project/aztec.js/src/fee). For example: -```javascript title="fee_juice_method" showLineNumbers +```javascript title="fee_juice_method" showLineNumbers /** * Pay fee directly in the Fee Juice. */ export class FeeJuicePaymentMethod implements FeePaymentMethod { ``` -> Source code: yarn-project/aztec.js/src/fee/fee_juice_payment_method.ts#L6-L11 +> Source code: yarn-project/aztec.js/src/fee/fee_juice_payment_method.ts#L6-L11 ### Gas Settings -```javascript title="gas_settings_vars" showLineNumbers +```javascript title="gas_settings_vars" showLineNumbers /** Gas usage and fees limits set by the transaction sender for different dimensions and phases. */ export class GasSettings { constructor( @@ -306,7 +306,7 @@ export class GasSettings { public readonly maxPriorityFeesPerGas: GasFees, ) {} ``` -> Source code: yarn-project/stdlib/src/gas/gas_settings.ts#L11-L20 +> Source code: yarn-project/stdlib/src/gas/gas_settings.ts#L11-L20 import { Gas_Settings_Components, Gas_Settings } from '@site/src/components/Snippets/general_snippets'; diff --git a/docs/versioned_docs/version-Latest/developers/guides/js_apps/send_transaction.md b/docs/versioned_docs/version-Latest/developers/guides/js_apps/send_transaction.md index b499b0a98764..4c78a2e4842b 100644 --- a/docs/versioned_docs/version-Latest/developers/guides/js_apps/send_transaction.md +++ b/docs/versioned_docs/version-Latest/developers/guides/js_apps/send_transaction.md @@ -19,26 +19,26 @@ You can learn how to use fee juice [here](./pay_fees.md). You will need to import this library: -```typescript title="import_contract" showLineNumbers +```typescript title="import_contract" showLineNumbers import { Contract } from '@aztec/aztec.js'; ``` -> Source code: yarn-project/end-to-end/src/composed/docs_examples.test.ts#L7-L9 +> Source code: yarn-project/end-to-end/src/composed/docs_examples.test.ts#L7-L9 ## Define contract Get a previously deployed contract like this: -```typescript title="get_contract" showLineNumbers +```typescript title="get_contract" showLineNumbers const contract = await Contract.at(deployedContract.address, TokenContractArtifact, wallet); ``` -> Source code: yarn-project/end-to-end/src/composed/docs_examples.test.ts#L45-L47 +> Source code: yarn-project/end-to-end/src/composed/docs_examples.test.ts#L45-L47 ## Call method -```typescript title="send_transaction" showLineNumbers +```typescript title="send_transaction" showLineNumbers const _tx = await contract.methods.mint_to_public(newWallet.getAddress(), 1).send().wait(); ``` -> Source code: yarn-project/end-to-end/src/composed/docs_examples.test.ts#L50-L52 +> Source code: yarn-project/end-to-end/src/composed/docs_examples.test.ts#L50-L52 diff --git a/docs/versioned_docs/version-Latest/developers/guides/js_apps/test.md b/docs/versioned_docs/version-Latest/developers/guides/js_apps/test.md index bb8a821e2e7f..8ea521aac5b2 100644 --- a/docs/versioned_docs/version-Latest/developers/guides/js_apps/test.md +++ b/docs/versioned_docs/version-Latest/developers/guides/js_apps/test.md @@ -27,44 +27,44 @@ You can use `aztec.js` to write assertions about transaction statuses, about cha Import `aztecjs`. This is an example of some functions and types you might need in your test: -```typescript title="imports" showLineNumbers +```typescript title="imports" showLineNumbers import { getDeployedTestAccountsWallets } from '@aztec/accounts/testing'; import { type AccountWallet, Fr, type PXE, TxStatus, createPXEClient, waitForPXE } from '@aztec/aztec.js'; import { CheatCodes } from '@aztec/aztec.js/testing'; import { TokenContract } from '@aztec/noir-contracts.js/Token'; ``` -> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L1-L6 +> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L1-L6 You should also import the [Typescript class you generated](../smart_contracts/how_to_compile_contract.md#typescript-interfaces): -```typescript title="import_contract" showLineNumbers +```typescript title="import_contract" showLineNumbers import { TestContract } from '@aztec/noir-test-contracts.js/Test'; ``` -> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L7-L10 +> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L7-L10 ## Create a PXE client Currently, testing Aztec.nr smart contracts means testing them against the PXE that runs in the local sandbox. Create a PXE client: -```typescript title="create_pxe_client" showLineNumbers +```typescript title="create_pxe_client" showLineNumbers const pxe = createPXEClient(PXE_URL); await waitForPXE(pxe); ``` -> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L19-L22 +> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L19-L22 and use the accounts that are initialized with it: -```typescript title="use-existing-wallets" showLineNumbers +```typescript title="use-existing-wallets" showLineNumbers pxe = createPXEClient(PXE_URL); [owner, recipient] = await getDeployedTestAccountsWallets(pxe); token = await TokenContract.deploy(owner, owner.getCompleteAddress(), 'TokenName', 'TokenSymbol', 18) .send() .deployed(); ``` -> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L32-L38 +> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L32-L38 Alternatively, you can [create a new account.](./create_account.md). @@ -84,11 +84,11 @@ You can use the `debug` option in the `wait` method to get more information abou This debug information will be populated in the transaction receipt. You can log it to the console or use it to make assertions about the transaction. -```typescript title="debug" showLineNumbers +```typescript title="debug" showLineNumbers const tx = await asset.methods.transfer(accounts[1].address, totalBalance).send().wait(); const txEffects = await node.getTxEffect(tx.txHash); ``` -> Source code: yarn-project/end-to-end/src/e2e_token_contract/private_transfer_recursion.test.ts#L25-L28 +> Source code: yarn-project/end-to-end/src/e2e_token_contract/private_transfer_recursion.test.ts#L25-L28 You can also log directly from Aztec contracts. Read [this guide](../../reference/debugging/index.md#logging-in-aztecnr) for some more information. @@ -99,27 +99,27 @@ You can also log directly from Aztec contracts. Read [this guide](../../referenc We can check that a call to a private function would fail by simulating it locally and expecting a rejection. Remember that all private function calls are only executed locally in order to preserve privacy. As an example, we can try transferring more tokens than we have, which will fail an assertion with the `Balance too low` error message. -```typescript title="local-tx-fails" showLineNumbers +```typescript title="local-tx-fails" showLineNumbers const call = token.methods.transfer(recipient.getAddress(), 200n); await expect(call.simulate()).rejects.toThrow(/Balance too low/); ``` -> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L123-L126 +> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L123-L126 Under the hood, the `send()` method executes a simulation, so we can just call the usual `send().wait()` to catch the same failure. -```typescript title="local-tx-fails" showLineNumbers +```typescript title="local-tx-fails" showLineNumbers const call = token.methods.transfer(recipient.getAddress(), 200n); await expect(call.simulate()).rejects.toThrow(/Balance too low/); ``` -> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L123-L126 +> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L123-L126 #### A transaction is dropped We can have private transactions that work fine locally, but are dropped by the sequencer when tried to be included due to a double-spend. In this example, we simulate two different transfers that would succeed individually, but not when both are tried to be mined. Here we need to `send()` the transaction and `wait()` for it to be mined. -```typescript title="tx-dropped" showLineNumbers +```typescript title="tx-dropped" showLineNumbers const call1 = token.methods.transfer(recipient.getAddress(), 80n); const call2 = token.methods.transfer(recipient.getAddress(), 50n); @@ -129,25 +129,25 @@ const provenCall2 = await call2.prove(); await provenCall1.send().wait(); await expect(provenCall2.send().wait()).rejects.toThrow(/dropped|nullifier/i); ``` -> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L130-L139 +> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L130-L139 #### A public call fails locally Public function calls can be caught failing locally similar to how we catch private function calls. For this example, we use a [`TokenContract` (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/master/noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr) instead of a private one. -```typescript title="local-pub-fails" showLineNumbers +```typescript title="local-pub-fails" showLineNumbers const call = token.methods.transfer_in_public(owner.getAddress(), recipient.getAddress(), 1000n, 0); await expect(call.simulate()).rejects.toThrow(U128_UNDERFLOW_ERROR); ``` -> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L143-L146 +> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L143-L146 #### A public call fails on the sequencer This will submit a failing call to the sequencer, who will include the transaction, but without any side effects from our application logic. Requesting the receipt for the transaction will also show it has a reverted status. -```typescript title="pub-reverted" showLineNumbers +```typescript title="pub-reverted" showLineNumbers const call = token.methods.transfer_in_public(owner.getAddress(), recipient.getAddress(), 1000n, 0); const receipt = await call.send().wait({ dontThrowOnRevert: true }); expect(receipt.status).toEqual(TxStatus.APP_LOGIC_REVERTED); @@ -158,7 +158,7 @@ const ownerPublicBalanceSlot = await cheats.aztec.computeSlotInMap( const balance = await pxe.getPublicStorageAt(token.address, ownerPublicBalanceSlot); expect(balance.value).toEqual(100n); ``` -> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L150-L160 +> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L150-L160 ``` @@ -171,19 +171,19 @@ We can check private or public state directly rather than going through view-onl To query storage directly, you'll need to know the slot you want to access. This can be checked in the [contract's `Storage` definition](../../reference/smart_contract_reference/storage/index.md) directly for most data types. However, when it comes to mapping types, as in most EVM languages, we'll need to calculate the slot for a given key. To do this, we'll use the [`CheatCodes`](../../reference/environment_reference/cheat_codes.md) utility class: -```typescript title="calc-slot" showLineNumbers +```typescript title="calc-slot" showLineNumbers cheats = await CheatCodes.create(ETHEREUM_HOSTS.split(','), pxe); // The balances mapping is indexed by user address ownerSlot = await cheats.aztec.computeSlotInMap(TokenContract.storage.balances.slot, ownerAddress); ``` -> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L74-L78 +> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L74-L78 #### Querying private state Private state in the Aztec is represented via sets of [private notes](../../../aztec/concepts/storage/state_model.md#private-state). We can query the Private Execution Environment (PXE) for all notes encrypted for a given user in a contract slot. For example, this gets all notes encrypted for the `owner` user that are stored on the token contract address and on the slot that was calculated earlier. To calculate the actual balance, it extracts the `value` of each note, which is the third element, and sums them up. -```typescript title="private-storage" showLineNumbers +```typescript title="private-storage" showLineNumbers await token.methods.sync_private_state().simulate(); const notes = await pxe.getNotes({ recipient: owner.getAddress(), @@ -196,14 +196,14 @@ const values = notes.map(note => note.note.items[2]); const balance = values.reduce((sum, current) => sum + current.toBigInt(), 0n); expect(balance).toEqual(100n); ``` -> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L82-L94 +> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L82-L94 #### Querying public state Public state behaves as a key-value store, much like in the EVM. We can directly query the target slot and get the result back as a buffer. Note that we use the [`TokenContract` (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/master/noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr) in this example, which defines a mapping of public balances on slot 6. -```typescript title="public-storage" showLineNumbers +```typescript title="public-storage" showLineNumbers await token.methods.mint_to_public(owner.getAddress(), 100n).send().wait(); const ownerPublicBalanceSlot = await cheats.aztec.computeSlotInMap( TokenContract.storage.public_balances.slot, @@ -212,7 +212,7 @@ const ownerPublicBalanceSlot = await cheats.aztec.computeSlotInMap( const balance = await pxe.getPublicStorageAt(token.address, ownerPublicBalanceSlot); expect(balance.value).toEqual(100n); ``` -> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L98-L106 +> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L98-L106 ### Logs @@ -223,7 +223,7 @@ You can check the logs of events emitted by contracts. Contracts in Aztec can em We can query the PXE for the public logs emitted in the block where our transaction is mined. -```typescript title="public-logs" showLineNumbers +```typescript title="public-logs" showLineNumbers const value = Fr.fromHexString('ef'); // Only 1 bytes will make its way in there :( so no larger stuff const tx = await testContract.methods.emit_public(value).send().wait(); const filter = { @@ -233,7 +233,7 @@ const filter = { const logs = (await pxe.getPublicLogs(filter)).logs; expect(logs[0].log.getEmittedFields()).toEqual([value]); ``` -> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L110-L119 +> Source code: yarn-project/end-to-end/src/guides/dapp_testing.test.ts#L110-L119 ## Cheats diff --git a/docs/versioned_docs/version-Latest/developers/guides/local_env/creating_schnorr_accounts.md b/docs/versioned_docs/version-Latest/developers/guides/local_env/creating_schnorr_accounts.md index 4965e065faa0..20faca51a189 100644 --- a/docs/versioned_docs/version-Latest/developers/guides/local_env/creating_schnorr_accounts.md +++ b/docs/versioned_docs/version-Latest/developers/guides/local_env/creating_schnorr_accounts.md @@ -26,16 +26,16 @@ Let's assume you have a file `src/index.ts` from the example used in the Sandbox 1. Import relevant modules: -```typescript title="imports1" showLineNumbers +```typescript title="imports1" showLineNumbers import { getSchnorrAccount } from '@aztec/accounts/schnorr'; import { getDeployedTestAccountsWallets } from '@aztec/accounts/testing'; ``` -> Source code: yarn-project/end-to-end/src/composed/e2e_sandbox_example.test.ts#L54-L57 +> Source code: yarn-project/end-to-end/src/composed/e2e_sandbox_example.test.ts#L54-L57 2. Code to create an account. You must run this inside of a function: -```typescript title="create_accounts" showLineNumbers +```typescript title="create_accounts" showLineNumbers ////////////// CREATE SOME ACCOUNTS WITH SCHNORR SIGNERS ////////////// // Use one of the pre-funded accounts to pay for the deployments. @@ -79,7 +79,7 @@ for (const [account, name] of [ logger.info(`Failed to create account for ${name}!`); } ``` -> Source code: yarn-project/end-to-end/src/composed/e2e_sandbox_example.test.ts#L201-L244 +> Source code: yarn-project/end-to-end/src/composed/e2e_sandbox_example.test.ts#L201-L244 3. Running `yarn start` should now output: diff --git a/docs/versioned_docs/version-Latest/developers/guides/local_env/versions-updating.md b/docs/versioned_docs/version-Latest/developers/guides/local_env/versions-updating.md index d26cb36e5e8b..eced5938c95e 100644 --- a/docs/versioned_docs/version-Latest/developers/guides/local_env/versions-updating.md +++ b/docs/versioned_docs/version-Latest/developers/guides/local_env/versions-updating.md @@ -4,7 +4,7 @@ sidebar_position: 0 tags: [sandbox] --- -- Current version: `v0.87.3` +- Current version: `v0.87.4` - Update with `aztec-up` On this page you will find @@ -36,7 +36,7 @@ Check the `git=` github url, tag, and directory. Example contracts serve as a helpful reference between versions of the Aztec.nr framework since they are strictly maintained with each release. -Code referenced in the documentation is sourced from contracts within [this directory (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.3/noir-projects/noir-contracts/contracts). +Code referenced in the documentation is sourced from contracts within [this directory (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.4/noir-projects/noir-contracts/contracts). As in the previous section, the location of the noir contracts moved at version `0.24.0`, from `yarn-project/noir-contracts` before, to `noir-projects/noir-contracts`. @@ -130,9 +130,9 @@ To update the aztec.nr packages manually, update the tags of the `aztec.nr` depe ```diff [dependencies] -aztec = { git="https://github.com/AztecProtocol/aztec-packages", tag="v0.7.5", directory="noir-projects/aztec-nr/aztec" } -+aztec = { git="https://github.com/AztecProtocol/aztec-packages", tag="v0.87.3", directory="noir-projects/aztec-nr/aztec" } ++aztec = { git="https://github.com/AztecProtocol/aztec-packages", tag="v0.87.4", directory="noir-projects/aztec-nr/aztec" } -value_note = { git="https://github.com/AztecProtocol/aztec-packages", tag="v0.7.5", directory="noir-projects/aztec-nr/value-note" } -+value_note = { git="https://github.com/AztecProtocol/aztec-packages", tag="v0.87.3", directory="noir-projects/aztec-nr/value-note" } ++value_note = { git="https://github.com/AztecProtocol/aztec-packages", tag="v0.87.4", directory="noir-projects/aztec-nr/value-note" } ``` Go to the contract directory and try compiling it with `aztec-nargo compile` to verify that the update was successful: @@ -151,7 +151,7 @@ To update Aztec.js packages, go to your `package.json` and replace the versions ```diff [dependencies] -"@aztec/accounts": "0.7.5", -+"@aztec/accounts": "v0.87.3", ++"@aztec/accounts": "v0.87.4", -"@aztec/noir-contracts.js": "0.35.1", -+"@aztec/accounts": "v0.87.3", ++"@aztec/accounts": "v0.87.4", ``` diff --git a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/index.md b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/index.md index 57cbff4258b9..6df38c10ff3b 100644 --- a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/index.md +++ b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/index.md @@ -23,7 +23,7 @@ help you write Noir programs to deploy on the Aztec network. ```toml # Nargo.toml [dependencies] -aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/aztec" } +aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/aztec" } ``` 2. [Write your contracts](./writing_contracts/index.mdx). diff --git a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/testing.md b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/testing.md index 4881b7c2b5c6..529ae14c0109 100644 --- a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/testing.md +++ b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/testing.md @@ -14,7 +14,7 @@ To test individual contract functions, you can use the Testing eXecution Environ Noir supports the `#[test]` annotation which can be used to write simple logic tests on isolated utility functions. These tests only make assertions on algorithms and cannot interact with protocol-specific constructs such as `storage` or `context`, but are extremely fast and can be useful in certain scenarios. -```rust title="pure_noir_testing" showLineNumbers +```rust title="pure_noir_testing" showLineNumbers #[test] fn test_to_from_field() { let field = 1234567890; @@ -22,7 +22,7 @@ fn test_to_from_field() { assert(card.to_field() == field); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/card_game_contract/src/cards.nr#L40-L47 +> Source code: noir-projects/noir-contracts/contracts/app/card_game_contract/src/cards.nr#L40-L47 To learn more about Noir testing, please refer to [the Noir docs](https://Noir-lang.org/docs/tooling/testing/). @@ -69,10 +69,10 @@ Since TXE tests are written in Noir and executed with `aztec-nargo`, they all ru `aztec-nr` provides an utility class called `TestEnvironment`, that should take care of the most common operations needed to setup contract testing. Setting up a new test environment with `TestEnvironment::new()` **will reset the current test's TXE state**. :::tip -You can find all of the methods available in the `TestEnvironment` [here (Github link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/noir-projects/aztec-nr/aztec/src/test/helpers/test_environment.nr). +You can find all of the methods available in the `TestEnvironment` [here (Github link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/noir-projects/aztec-nr/aztec/src/test/helpers/test_environment.nr). ::: -```rust title="txe_test_increment" showLineNumbers +```rust title="txe_test_increment" showLineNumbers #[test] unconstrained fn test_increment() { // Setup env, generate keys @@ -107,7 +107,7 @@ unconstrained fn test_increment() { ); } ``` -> Source code: noir-projects/noir-contracts/contracts/test/counter_contract/src/main.nr#L132-L168 +> Source code: noir-projects/noir-contracts/contracts/test/counter_contract/src/main.nr#L132-L168 :::warning @@ -118,14 +118,14 @@ Tests run significantly faster as `unconstrained` functions. This means we gener Writing tests in contracts requires importing additional modules from Aztec.nr. Here are the modules that are needed for testing the increment function in the counter contract. -```rust title="test_imports" showLineNumbers +```rust title="test_imports" showLineNumbers use crate::test; use dep::aztec::note::note_getter::{MAX_NOTES_PER_PAGE, view_notes}; use dep::aztec::note::note_viewer_options::NoteViewerOptions; use dep::aztec::protocol_types::storage::map::derive_storage_slot_in_map; use dep::aztec::test::helpers::test_environment::TestEnvironment; ``` -> Source code: noir-projects/noir-contracts/contracts/test/counter_contract/src/main.nr#L124-L131 +> Source code: noir-projects/noir-contracts/contracts/test/counter_contract/src/main.nr#L124-L131 ### Deploying contracts @@ -172,31 +172,31 @@ Our test environment is capable of utilizing the autogenerated contract interfac For example, to call the private `transfer` function on the token contract: -```rust title="txe_test_transfer_private" showLineNumbers +```rust title="txe_test_transfer_private" showLineNumbers // Transfer tokens let transfer_amount = 1000 as u128; Token::at(token_contract_address).transfer(recipient, transfer_amount).call(&mut env.private()); ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/test/transfer.nr#L11-L15 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/test/transfer.nr#L11-L15 #### Public To call the public `transfer_in_public` function: -```rust title="call_public" showLineNumbers +```rust title="call_public" showLineNumbers Token::at(token_contract_address).transfer_in_public(owner, owner, transfer_amount, 0).call( &mut env.public(), ); ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/test/transfer_in_public.nr#L29-L33 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/test/transfer_in_public.nr#L29-L33 #### Utility Utility functions can be directly called from the contract interface. Notice that we need to set the contract address to the specific token contract that we are calling before making the call. This is to ensure that `view_notes` works properly. -```rust title="txe_test_call_utility" showLineNumbers +```rust title="txe_test_call_utility" showLineNumbers pub unconstrained fn check_private_balance( token_contract_address: AztecAddress, address: AztecAddress, @@ -210,7 +210,7 @@ pub unconstrained fn check_private_balance( cheatcodes::set_contract_address(current_contract_address); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/test/utils.nr#L135-L148 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/test/utils.nr#L135-L148 ### Creating accounts @@ -248,7 +248,7 @@ Remember to switch to the current contract's address in order to be able to read ::: Reading public state: -```rust title="txe_test_read_public" showLineNumbers +```rust title="txe_test_read_public" showLineNumbers pub unconstrained fn check_public_balance( token_contract_address: AztecAddress, address: AztecAddress, @@ -265,11 +265,11 @@ pub unconstrained fn check_public_balance( cheatcodes::set_contract_address(current_contract_address); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/test/utils.nr#L88-L104 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/test/utils.nr#L88-L104 Reading notes: -```rust title="txe_test_read_notes" showLineNumbers +```rust title="txe_test_read_notes" showLineNumbers // Read the stored value in the note let initial_counter = env.simulate_utility(Counter::at(contract_address)._experimental_get_counter(owner)); @@ -278,7 +278,7 @@ assert( f"Expected {initial_value} but got {initial_counter}", ); ``` -> Source code: noir-projects/noir-contracts/contracts/test/counter_contract/src/main.nr#L146-L154 +> Source code: noir-projects/noir-contracts/contracts/test/counter_contract/src/main.nr#L146-L154 ### Authwits @@ -287,7 +287,7 @@ assert( You can add [authwits](writing_contracts/authwit.md) to the TXE. Here is an example of testing a private token transfer using authwits: -```rust title="private_authwit" showLineNumbers +```rust title="private_authwit" showLineNumbers let transfer_amount = 1000 as u128; let transfer_private_from_call_interface = Token::at(token_contract_address).transfer_in_private(owner, recipient, transfer_amount, 1); @@ -301,12 +301,12 @@ env.impersonate(recipient); // Transfer tokens transfer_private_from_call_interface.call(&mut env.private()); ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/test/transfer_in_private.nr#L11-L24 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/test/transfer_in_private.nr#L11-L24 #### Public -```rust title="public_authwit" showLineNumbers +```rust title="public_authwit" showLineNumbers let public_transfer_in_private_call_interface = Token::at(token_contract_address).transfer_in_public(owner, recipient, transfer_amount, 1); authwit_cheatcodes::add_public_authwit_from_call_interface( @@ -315,14 +315,14 @@ authwit_cheatcodes::add_public_authwit_from_call_interface( public_transfer_in_private_call_interface, ); ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/test/transfer_in_public.nr#L115-L123 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/test/transfer_in_public.nr#L115-L123 ### Storing notes in cache Sometimes we have to tell TXE about notes that are not generated by ourselves, but someone else. This allows us to check if we are able to decrypt them: -```rust title="txe_test_add_note" showLineNumbers +```rust title="txe_test_add_note" showLineNumbers let balances_owner_slot = derive_storage_slot_in_map(Token::storage_layout().balances.slot, owner); @@ -332,7 +332,7 @@ env.add_note( token_contract_address, ); ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/test/utils.nr#L169-L178 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/test/utils.nr#L169-L178 ### Time traveling @@ -351,7 +351,7 @@ You can test functions that you expect to fail generically, with the `#[test(sho For example: -```rust title="fail_with_message" showLineNumbers +```rust title="fail_with_message" showLineNumbers #[test(should_fail_with = "invalid nonce")] unconstrained fn transfer_private_failure_on_behalf_of_self_non_zero_nonce() { // Setup without account contracts. We are not using authwits here, so dummy accounts are enough @@ -370,17 +370,17 @@ unconstrained fn transfer_private_failure_on_behalf_of_self_non_zero_nonce() { transfer_private_from_call_interface.call(&mut env.private()); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/test/transfer_in_private.nr#L30-L48 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/test/transfer_in_private.nr#L30-L48 You can also use the `assert_public_call_fails` or `assert_private_call_fails` methods on the `TestEnvironment` to check that a call fails. -```rust title="assert_public_fail" showLineNumbers +```rust title="assert_public_fail" showLineNumbers // Try to set ourselves as admin, fail miserably let set_admin_call_interface = Token::at(token_contract_address).set_admin(recipient); env.assert_public_call_fails(set_admin_call_interface); ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/test/access_control.nr#L34-L38 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/test/access_control.nr#L34-L38 ### Logging @@ -399,4 +399,4 @@ export LOG_LEVEL="debug" ### All Cheatcodes -You can find the full list of cheatcodes available in the TXE [here](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/noir-projects/aztec-nr/aztec/src/test/helpers/cheatcodes.nr) +You can find the full list of cheatcodes available in the TXE [here](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/noir-projects/aztec-nr/aztec/src/test/helpers/cheatcodes.nr) diff --git a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/authwit.md b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/authwit.md index 4eb6672fe8f2..9c9dcf1679f5 100644 --- a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/authwit.md +++ b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/authwit.md @@ -107,14 +107,14 @@ The `on_behalf_of` should assert that we are indeed authenticated and then retur #### Example -```rust title="assert_current_call_valid_authwit" showLineNumbers +```rust title="assert_current_call_valid_authwit" showLineNumbers if (!from.eq(context.msg_sender())) { assert_current_call_valid_authwit(&mut context, from); } else { assert(nonce == 0, "invalid nonce"); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L366-L372 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L366-L372 ### Utilities for public calls @@ -123,14 +123,14 @@ Very similar to the above, we have variations that work in the public domain (`a #### Example -```rust title="assert_current_call_valid_authwit_public" showLineNumbers +```rust title="assert_current_call_valid_authwit_public" showLineNumbers if (!from.eq(context.msg_sender())) { assert_current_call_valid_authwit_public(&mut context, from); } else { assert(nonce == 0, "invalid nonce"); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L226-L232 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L226-L232 ## Usage @@ -143,19 +143,19 @@ To add it to your project, add the `authwit` library to your `Nargo.toml` file. ```toml [dependencies] -aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/aztec" } -authwit = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/authwit"} +aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/aztec" } +authwit = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/authwit"} ``` Then you will be able to import it into your contracts as follows. -```rust title="import_authwit" showLineNumbers +```rust title="import_authwit" showLineNumbers use dep::authwit::auth::{ assert_current_call_valid_authwit, assert_current_call_valid_authwit_public, compute_authwit_nullifier, }; ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L40-L45 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L40-L45 ### Private Functions @@ -164,7 +164,7 @@ use dep::authwit::auth::{ Based on the diagram earlier on this page let's take a look at how we can implement the `transfer` function such that it checks if the tokens are to be transferred `from` the caller or needs to be authenticated with an authentication witness. -```rust title="transfer_in_private" showLineNumbers +```rust title="transfer_in_private" showLineNumbers #[private] fn transfer_in_private(from: AztecAddress, to: AztecAddress, amount: u128, nonce: Field) { if (!from.eq(context.msg_sender())) { @@ -181,7 +181,7 @@ fn transfer_in_private(from: AztecAddress, to: AztecAddress, amount: u128, nonce storage.balances.at(to).add(to, amount).emit(encode_and_encrypt_note(&mut context, to, from)); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L363-L383 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L363-L383 The first thing we see in the snippet above, is that if `from` is not the call we are calling the `assert_current_call_valid_authwit` function from [earlier](#private-functions). If the call is not throwing, we are all good and can continue with the transfer. @@ -192,7 +192,7 @@ In the snippet we are constraining the `else` case such that only `nonce = 0` is Cool, so we have a function that checks if the current call is authenticated, but how do we actually authenticate it? Well, assuming that we use a wallet that is following the spec, we import `computeAuthWitMessageHash` from `aztec.js` to help us compute the hash, and then we simply `addAuthWitness` to the wallet. Behind the scenes this will make the witness available to the oracle. -```typescript title="authwit_transfer_example" showLineNumbers +```typescript title="authwit_transfer_example" showLineNumbers const action = asset .withWallet(wallets[1]) .methods.transfer_in_private(accounts[0].address, accounts[1].address, amount, nonce); @@ -205,7 +205,7 @@ expect( isValidInPublic: false, }); ``` -> Source code: yarn-project/end-to-end/src/e2e_token_contract/transfer_in_private.test.ts#L32-L44 +> Source code: yarn-project/end-to-end/src/e2e_token_contract/transfer_in_private.test.ts#L32-L44 Learn more about authwits in Aztec.js by [following this guide](../../js_apps/authwit.md). @@ -216,7 +216,7 @@ With private functions covered, how can we use this in a public function? Well, #### Checking if the current call is authenticated -```rust title="transfer_in_public" showLineNumbers +```rust title="transfer_in_public" showLineNumbers #[public] fn transfer_in_public(from: AztecAddress, to: AztecAddress, amount: u128, nonce: Field) { if (!from.eq(context.msg_sender())) { @@ -230,7 +230,7 @@ fn transfer_in_public(from: AztecAddress, to: AztecAddress, amount: u128, nonce: storage.public_balances.at(to).write(to_balance); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L208-L221 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L208-L221 #### Authenticating an action in TypeScript @@ -239,7 +239,7 @@ Authenticating an action in the public domain is slightly different from the pri In the snippet below, this is done as a separate contract call, but can also be done as part of a batch as mentioned in the [Accounts concepts](../../../../aztec/concepts/advanced/authwit.md#what-about-public). -```typescript title="authwit_public_transfer_example" showLineNumbers +```typescript title="authwit_public_transfer_example" showLineNumbers const action = asset .withWallet(wallets[1]) .methods.transfer_in_public(accounts[0].address, accounts[1].address, amount, nonce); @@ -247,7 +247,7 @@ const action = asset const validateActionInteraction = await wallets[0].setPublicAuthWit({ caller: accounts[1].address, action }, true); await validateActionInteraction.send().wait(); ``` -> Source code: yarn-project/end-to-end/src/e2e_token_contract/transfer_in_public.test.ts#L69-L76 +> Source code: yarn-project/end-to-end/src/e2e_token_contract/transfer_in_public.test.ts#L69-L76 #### Updating approval state in Noir @@ -260,7 +260,7 @@ When another contract later is consuming the authwit using `assert_current_call_ An example of this would be our Uniswap example which performs a cross chain swap on L1. In here, we both do private and public auth witnesses, where the public is set by the uniswap L2 contract itself. In the below snippet, you can see that we compute the action hash and update the value in the registry. When we then call the `token_bridge` to execute afterwards, it reads this value, burns the tokens, and consumes the authentication. -```rust title="authwit_uniswap_set" showLineNumbers +```rust title="authwit_uniswap_set" showLineNumbers // This helper method approves the bridge to burn this contract's funds and exits the input asset to L1 // Assumes contract already has funds. // Assume `token` relates to `token_bridge` (ie token_bridge.token == token) @@ -297,7 +297,7 @@ fn _approve_bridge_and_exit_input_asset_to_L1( .call(&mut context) } ``` -> Source code: noir-projects/noir-contracts/contracts/app/uniswap_contract/src/main.nr#L185-L221 +> Source code: noir-projects/noir-contracts/contracts/app/uniswap_contract/src/main.nr#L185-L221 Outlining more of the `swap` flow: this simplified diagram shows how it will look for contracts that are not wallets but also need to support authentication witnesses. diff --git a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/call_contracts.md b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/call_contracts.md index c7db0ababa01..56fe68eb875a 100644 --- a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/call_contracts.md +++ b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/call_contracts.md @@ -15,7 +15,7 @@ If a contract wishes to access or modify another contract's state, it must make Import the contract that you want to call into your `Nargo.toml` under `dependencies` like this: ```toml -token = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/noir-contracts/contracts/app/token_contract" } +token = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/noir-contracts/contracts/app/token_contract" } ``` ### Import into your contract @@ -39,34 +39,34 @@ To call the function, you need to To call a private function, you can just use `call()` like this: -```rust title="call_function" showLineNumbers +```rust title="call_function" showLineNumbers Token::at(token).transfer(recipient, amount).call(&mut context); ``` -> Source code: noir-projects/noir-contracts/contracts/app/escrow_contract/src/main.nr#L45-L47 +> Source code: noir-projects/noir-contracts/contracts/app/escrow_contract/src/main.nr#L45-L47 #### Public -> Public calls To call a public function from a public function, it is the same as above. You can just use `call()` like this: -```rust title="public_to_public_call" showLineNumbers +```rust title="public_to_public_call" showLineNumbers let _ = Token::at(collateral_asset) .transfer_in_public(context.msg_sender(), context.this_address(), amount, nonce) .call(&mut context); ``` -> Source code: noir-projects/noir-contracts/contracts/app/lending_contract/src/main.nr#L133-L137 +> Source code: noir-projects/noir-contracts/contracts/app/lending_contract/src/main.nr#L133-L137 #### Private -> Public calls To call a public function from private, you will need to enqueue it like this: -```rust title="enqueue_public" showLineNumbers +```rust title="enqueue_public" showLineNumbers Lending::at(context.this_address()) ._deposit(AztecAddress::from_field(on_behalf_of), amount, collateral_asset) .enqueue(&mut context); ``` -> Source code: noir-projects/noir-contracts/contracts/app/lending_contract/src/main.nr#L119-L123 +> Source code: noir-projects/noir-contracts/contracts/app/lending_contract/src/main.nr#L119-L123 Public functions are always executed after private execution. To learn why, read the [concepts overview](../../../../aztec/index.md). diff --git a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/call_functions.md b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/call_functions.md index c7db0ababa01..56fe68eb875a 100644 --- a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/call_functions.md +++ b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/call_functions.md @@ -15,7 +15,7 @@ If a contract wishes to access or modify another contract's state, it must make Import the contract that you want to call into your `Nargo.toml` under `dependencies` like this: ```toml -token = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/noir-contracts/contracts/app/token_contract" } +token = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/noir-contracts/contracts/app/token_contract" } ``` ### Import into your contract @@ -39,34 +39,34 @@ To call the function, you need to To call a private function, you can just use `call()` like this: -```rust title="call_function" showLineNumbers +```rust title="call_function" showLineNumbers Token::at(token).transfer(recipient, amount).call(&mut context); ``` -> Source code: noir-projects/noir-contracts/contracts/app/escrow_contract/src/main.nr#L45-L47 +> Source code: noir-projects/noir-contracts/contracts/app/escrow_contract/src/main.nr#L45-L47 #### Public -> Public calls To call a public function from a public function, it is the same as above. You can just use `call()` like this: -```rust title="public_to_public_call" showLineNumbers +```rust title="public_to_public_call" showLineNumbers let _ = Token::at(collateral_asset) .transfer_in_public(context.msg_sender(), context.this_address(), amount, nonce) .call(&mut context); ``` -> Source code: noir-projects/noir-contracts/contracts/app/lending_contract/src/main.nr#L133-L137 +> Source code: noir-projects/noir-contracts/contracts/app/lending_contract/src/main.nr#L133-L137 #### Private -> Public calls To call a public function from private, you will need to enqueue it like this: -```rust title="enqueue_public" showLineNumbers +```rust title="enqueue_public" showLineNumbers Lending::at(context.this_address()) ._deposit(AztecAddress::from_field(on_behalf_of), amount, collateral_asset) .enqueue(&mut context); ``` -> Source code: noir-projects/noir-contracts/contracts/app/lending_contract/src/main.nr#L119-L123 +> Source code: noir-projects/noir-contracts/contracts/app/lending_contract/src/main.nr#L119-L123 Public functions are always executed after private execution. To learn why, read the [concepts overview](../../../../aztec/index.md). diff --git a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/common_patterns/index.md b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/common_patterns/index.md index 22d8a312bca8..11ac5f90e993 100644 --- a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/common_patterns/index.md +++ b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/common_patterns/index.md @@ -16,7 +16,7 @@ Similarly we have discovered some anti-patterns too (like privacy leakage) that We call this the "authentication witness" pattern or authwit for short. - Approve someone in private domain: -```typescript title="authwit_to_another_sc" showLineNumbers +```typescript title="authwit_to_another_sc" showLineNumbers // 4. Give approval to bridge to burn owner's funds: const withdrawAmount = 9n; const nonce = Fr.random(); @@ -25,13 +25,13 @@ const burnAuthwit = await user1Wallet.createAuthWit({ action: l2Token.methods.burn_private(ownerAddress, withdrawAmount, nonce), }); ``` -> Source code: yarn-project/end-to-end/src/e2e_cross_chain_messaging/token_bridge_private.test.ts#L70-L78 +> Source code: yarn-project/end-to-end/src/e2e_cross_chain_messaging/token_bridge_private.test.ts#L70-L78 Here you approve a contract to burn funds on your behalf. - Approve in public domain: -```typescript title="authwit_public_transfer_example" showLineNumbers +```typescript title="authwit_public_transfer_example" showLineNumbers const action = asset .withWallet(wallets[1]) .methods.transfer_in_public(accounts[0].address, accounts[1].address, amount, nonce); @@ -39,7 +39,7 @@ const action = asset const validateActionInteraction = await wallets[0].setPublicAuthWit({ caller: accounts[1].address, action }, true); await validateActionInteraction.send().wait(); ``` -> Source code: yarn-project/end-to-end/src/e2e_token_contract/transfer_in_public.test.ts#L69-L76 +> Source code: yarn-project/end-to-end/src/e2e_token_contract/transfer_in_public.test.ts#L69-L76 Here you approve someone to transfer funds publicly on your behalf @@ -50,7 +50,7 @@ E.g. you don't want a user to subscribe once they have subscribed already. Or yo Emit a nullifier in your function. By adding this nullifier into the tree, you prevent another nullifier from being added again. This is also why in authwit, we emit a nullifier, to prevent someone from reusing their approval. -```rust title="verify_private_authwit" showLineNumbers +```rust title="verify_private_authwit" showLineNumbers pub fn verify_private_authwit(self, inner_hash: Field) -> Field { // The `inner_hash` is "siloed" with the `msg_sender` to ensure that only it can // consume the message. @@ -66,7 +66,7 @@ pub fn verify_private_authwit(self, inner_hash: Field) -> Field { IS_VALID_SELECTOR } ``` -> Source code: noir-projects/aztec-nr/authwit/src/account.nr#L71-L86 +> Source code: noir-projects/aztec-nr/authwit/src/account.nr#L71-L86 Note be careful to ensure that the nullifier is not deterministic and that no one could do a preimage analysis attack. More in [the anti pattern section on deterministic nullifiers](#deterministic-nullifiers) @@ -123,7 +123,7 @@ When you send someone a note, the note hash gets added to the note hash tree. To 1. When sending someone a note, emit the note log to the recipient (the function encrypts the log in such a way that only a recipient can decrypt it). PXE then tries to decrypt all the encrypted logs, and stores the successfully decrypted one. [More info here](../how_to_emit_event.md) 2. Manually delivering it via a custom contract method, if you choose to not emit logs to save gas or when creating a note in the public domain and want to consume it in private domain (`encrypt_and_emit_note` shouldn't be called in the public domain because everything is public), like in the previous section where we created a note in public that doesn't have a designated owner. -```typescript title="offchain_delivery" showLineNumbers +```typescript title="offchain_delivery" showLineNumbers const txEffects = await pxe.getTxEffect(txHash); await contract.methods .deliver_transparent_note( @@ -137,12 +137,12 @@ await contract.methods ) .simulate(); ``` -> Source code: yarn-project/end-to-end/src/composed/e2e_persistence.test.ts#L364-L377 +> Source code: yarn-project/end-to-end/src/composed/e2e_persistence.test.ts#L364-L377 Note that this requires your contract to have a utility function that processes these notes and adds them to PXE. -```rust title="deliver_note_contract_method" showLineNumbers +```rust title="deliver_note_contract_method" showLineNumbers #[utility] unconstrained fn deliver_transparent_note( contract_address: AztecAddress, @@ -154,7 +154,7 @@ unconstrained fn deliver_transparent_note( recipient: AztecAddress, ) { ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_blacklist_contract/src/main.nr#L304-L315 +> Source code: noir-projects/noir-contracts/contracts/app/token_blacklist_contract/src/main.nr#L304-L315 ### Revealing encrypted logs conditionally @@ -173,7 +173,7 @@ Notes are hashed and stored in the merkle tree. While notes do have a header wit Hence, it's necessary to add a "randomness" field to your note to prevent such attacks. -```rust title="address_note_def" showLineNumbers +```rust title="address_note_def" showLineNumbers #[note] #[derive(Eq)] pub struct AddressNote { @@ -193,7 +193,7 @@ impl AddressNote { } } ``` -> Source code: noir-projects/aztec-nr/address-note/src/address_note.nr#L5-L24 +> Source code: noir-projects/aztec-nr/address-note/src/address_note.nr#L5-L24 ### L1 -- L2 interactions @@ -238,7 +238,7 @@ E.g. for a voting contract, if your nullifier simply emits just the `user_addres Here is an example from the voting contract: -```rust title="cast_vote" showLineNumbers +```rust title="cast_vote" showLineNumbers #[private] // annotation to mark function as private and expose private context fn cast_vote(candidate: Field) { @@ -252,5 +252,5 @@ fn cast_vote(candidate: Field) { ); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/easy_private_voting_contract/src/main.nr#L38-L51 +> Source code: noir-projects/noir-contracts/contracts/app/easy_private_voting_contract/src/main.nr#L38-L51 diff --git a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/how_to_emit_event.md b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/how_to_emit_event.md index 969dc3268a1a..8a07ea839148 100644 --- a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/how_to_emit_event.md +++ b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/how_to_emit_event.md @@ -14,14 +14,14 @@ There are also public logs, which are similar to events, but are unstructured da To emit encrypted logs you can import the `encode_and_encrypt_event` or `encode_and_encrypt_event_unconstrained` functions and pass them into the `emit` function. An example can be seen in the reference token contract's transfer function: -```rust title="encrypted_unconstrained" showLineNumbers +```rust title="encrypted_unconstrained" showLineNumbers Transfer { from, to, amount }.emit(encode_and_encrypt_event_unconstrained( &mut context, to, from, )); ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L291-L297 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L291-L297 - `encode_and_encrypt_event` Sends an encrypted message to `recipient` with the content of the event, which they will discover when processing private logs. @@ -31,7 +31,7 @@ Transfer { from, to, amount }.emit(encode_and_encrypt_event_unconstrained( Developer can choose whether to emit encrypted events or not. Emitting the events means that they will be posted to Ethereum, in blobs, and will inherit the availability guarantees of Ethereum. Developers may choose not to emit events and to share information with recipients off-chain, or through alternative mechanisms that are to be developed (e.g. alternative, cheaper data availability solutions). ::: -You can find the implementation of event logging [here](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/noir-projects/aztec-nr/aztec/src/messages/logs/event.nr) +You can find the implementation of event logging [here](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/noir-projects/aztec-nr/aztec/src/messages/logs/event.nr) ### Processing encrypted events @@ -41,12 +41,12 @@ Contracts created using aztec-nr will try to discover newly created events by se You can emit public events by calling the `emit` function on the event type that you would like to emit. For example: -```rust title="emit_public" showLineNumbers +```rust title="emit_public" showLineNumbers let event0 = ExampleEvent0 { value0: preimages[0], value1: preimages[1] }; event0.emit(encode_event(&mut context)); ``` -> Source code: noir-projects/noir-contracts/contracts/test/test_log_contract/src/main.nr#L53-L57 +> Source code: noir-projects/noir-contracts/contracts/test/test_log_contract/src/main.nr#L53-L57 ## Public Logs @@ -57,19 +57,19 @@ Public logs are unstructured data which can be read by anyone. They can be emitt To emit public logs you don't need to import any library. You call the context method `emit_public_log`: -```rust title="emit_public" showLineNumbers +```rust title="emit_public" showLineNumbers context.emit_public_log(/*message=*/ value); context.emit_public_log(/*message=*/ [10, 20, 30]); context.emit_public_log(/*message=*/ "Hello, world!"); ``` -> Source code: noir-projects/noir-contracts/contracts/test/test_contract/src/main.nr#L359-L363 +> Source code: noir-projects/noir-contracts/contracts/test/test_contract/src/main.nr#L359-L363 ### Querying the unencrypted event Once emitted, unencrypted events are stored in AztecNode and can be queried by anyone: -```typescript title="get_logs" showLineNumbers +```typescript title="get_logs" showLineNumbers const fromBlock = await pxe.getBlockNumber(); const logFilter = { fromBlock, @@ -77,7 +77,7 @@ const logFilter = { }; const publicLogs = (await pxe.getPublicLogs(logFilter)).logs; ``` -> Source code: yarn-project/end-to-end/src/e2e_ordering.test.ts#L23-L30 +> Source code: yarn-project/end-to-end/src/e2e_ordering.test.ts#L23-L30 ## Costs diff --git a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/how_to_prove_history.md b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/how_to_prove_history.md index 1a90de24d7ac..cc6cce985a9e 100644 --- a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/how_to_prove_history.md +++ b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/how_to_prove_history.md @@ -37,7 +37,7 @@ Using this library, you can check that specific notes or nullifiers were part of In general you will likely have the note you want to prove inclusion of. But if you are just experimenting you can create a note with a function like below: -```rust title="create_note" showLineNumbers +```rust title="create_note" showLineNumbers #[private] fn call_create_note( value: Field, @@ -53,18 +53,18 @@ fn call_create_note( )); } ``` -> Source code: noir-projects/noir-contracts/contracts/test/test_contract/src/main.nr#L139-L154 +> Source code: noir-projects/noir-contracts/contracts/test/test_contract/src/main.nr#L139-L154 ## Get the note from the PXE Retrieve the note from the user's PXE. -```rust title="get_note_from_pxe" showLineNumbers +```rust title="get_note_from_pxe" showLineNumbers let (retrieved_notes, _): (BoundedVec, MAX_NOTE_HASH_READ_REQUESTS_PER_CALL>, BoundedVec) = get_notes(&mut context, storage_slot, options); ``` -> Source code: noir-projects/noir-contracts/contracts/test/test_contract/src/main.nr#L163-L166 +> Source code: noir-projects/noir-contracts/contracts/test/test_contract/src/main.nr#L163-L166 In this example, we fetch notes located in the storage slot that we pass in from the function parameters. The notes also must match the criteria specified by the getter options that we declare and are able to customize. @@ -73,28 +73,28 @@ In this example, we fetch notes located in the storage slot that we pass in from To prove that a note existed in a specified block, call `prove_note_inclusion` on the `header` as shown in this example: -```rust title="prove_note_inclusion" showLineNumbers +```rust title="prove_note_inclusion" showLineNumbers context.historical_header.prove_note_inclusion(retrieved_note, test::NOTE_STORAGE_SLOT); ``` -> Source code: noir-projects/aztec-nr/aztec/src/history/note_inclusion/test.nr#L10-L12 +> Source code: noir-projects/aztec-nr/aztec/src/history/note_inclusion/test.nr#L10-L12 This will only prove the note existed at the specific block number, not whether or not the note has been nullified. You can prove that a note existed and had not been nullified in a specified block by using `prove_note_validity` on the block header which takes the following arguments: -```rust title="prove_note_validity" showLineNumbers +```rust title="prove_note_validity" showLineNumbers context.historical_header.prove_note_validity(retrieved_note, test::NOTE_STORAGE_SLOT, context); ``` -> Source code: noir-projects/aztec-nr/aztec/src/history/note_validity/test.nr#L25-L27 +> Source code: noir-projects/aztec-nr/aztec/src/history/note_validity/test.nr#L25-L27 ## Create a nullifier to prove inclusion of You can easily nullify a note like so: -```rust title="nullify_note" showLineNumbers +```rust title="nullify_note" showLineNumbers destroy_note_unsafe(&mut context, retrieved_note, note_hash); ``` -> Source code: noir-projects/noir-contracts/contracts/test/test_contract/src/main.nr#L220-L222 +> Source code: noir-projects/noir-contracts/contracts/test/test_contract/src/main.nr#L220-L222 This function gets a note from the PXE and nullifies it with `remove()`. @@ -105,10 +105,10 @@ You can then compute this nullifier with `note.compute_nullifier(&mut context)`. Call `prove_nullifier_inclusion` on a block header like so: -```rust title="prove_nullifier_inclusion" showLineNumbers +```rust title="prove_nullifier_inclusion" showLineNumbers context.historical_header.prove_nullifier_inclusion(siloed_nullifier); ``` -> Source code: noir-projects/aztec-nr/aztec/src/history/nullifier_inclusion/test.nr#L60-L62 +> Source code: noir-projects/aztec-nr/aztec/src/history/nullifier_inclusion/test.nr#L60-L62 It takes the nullifier as an argument. diff --git a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/how_to_use_capsules.md b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/how_to_use_capsules.md index 77fb689b7a32..7313ee27acda 100644 --- a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/how_to_use_capsules.md +++ b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/how_to_use_capsules.md @@ -20,17 +20,17 @@ The capsules module provides these main functions: Import the capsules module: -```rust title="import_capsules" showLineNumbers +```rust title="import_capsules" showLineNumbers use dep::aztec::oracle::capsules; ``` -> Source code: noir-projects/noir-contracts/contracts/protocol/contract_class_registerer_contract/src/main.nr#L37-L39 +> Source code: noir-projects/noir-contracts/contracts/protocol/contract_class_registerer_contract/src/main.nr#L37-L39 ### 2. Store and load data You can store any type that implements `Serialize` and `Deserialize`: -```rust title="load_capsule" showLineNumbers +```rust title="load_capsule" showLineNumbers let packed_public_bytecode: [Field; MAX_PACKED_PUBLIC_BYTECODE_SIZE_IN_FIELDS] = unsafe { capsules::load( context.this_address(), @@ -39,7 +39,7 @@ let packed_public_bytecode: [Field; MAX_PACKED_PUBLIC_BYTECODE_SIZE_IN_FIELDS] = .unwrap() }; ``` -> Source code: noir-projects/noir-contracts/contracts/protocol/contract_class_registerer_contract/src/main.nr#L49-L57 +> Source code: noir-projects/noir-contracts/contracts/protocol/contract_class_registerer_contract/src/main.nr#L49-L57 The data is stored per contract address and slot. When loading, you'll get back an `Option` - `None` if no data exists at that slot. diff --git a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/index.mdx b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/index.mdx index 8a24e8b488ff..045b4562bcb8 100644 --- a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/index.mdx +++ b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/index.mdx @@ -20,7 +20,7 @@ pub contract EasyPrivateVoting { 2. Define imports in your contract block -```rust title="imports" showLineNumbers +```rust title="imports" showLineNumbers use dep::aztec::{ keys::getters::get_public_keys, macros::{functions::{initializer, internal, private, public, utility}, storage::storage}, @@ -28,12 +28,12 @@ use dep::aztec::{ use dep::aztec::prelude::{AztecAddress, Map, PublicImmutable, PublicMutable}; use dep::aztec::protocol_types::traits::{Hash, ToField}; ``` -> Source code: noir-projects/noir-contracts/contracts/app/easy_private_voting_contract/src/main.nr#L8-L16 +> Source code: noir-projects/noir-contracts/contracts/app/easy_private_voting_contract/src/main.nr#L8-L16 3. Declare your contract storage below your imports -```rust title="storage_struct" showLineNumbers +```rust title="storage_struct" showLineNumbers #[storage] struct Storage { admin: PublicMutable, // admin can end vote @@ -42,12 +42,12 @@ struct Storage { active_at_block: PublicImmutable, // when people can start voting } ``` -> Source code: noir-projects/noir-contracts/contracts/app/easy_private_voting_contract/src/main.nr#L17-L25 +> Source code: noir-projects/noir-contracts/contracts/app/easy_private_voting_contract/src/main.nr#L17-L25 4. Declare a constructor with `#[initializer]`. Constructors can be private or public functions. -```rust title="constructor" showLineNumbers +```rust title="constructor" showLineNumbers #[public] #[initializer] // annotation to mark function as a constructor @@ -57,12 +57,12 @@ fn constructor(admin: AztecAddress) { storage.active_at_block.initialize(context.block_number() as u32); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/easy_private_voting_contract/src/main.nr#L27-L36 +> Source code: noir-projects/noir-contracts/contracts/app/easy_private_voting_contract/src/main.nr#L27-L36 5. Declare your contract functions -```rust title="cast_vote" showLineNumbers +```rust title="cast_vote" showLineNumbers #[private] // annotation to mark function as private and expose private context fn cast_vote(candidate: Field) { @@ -76,7 +76,7 @@ fn cast_vote(candidate: Field) { ); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/easy_private_voting_contract/src/main.nr#L38-L51 +> Source code: noir-projects/noir-contracts/contracts/app/easy_private_voting_contract/src/main.nr#L38-L51 There is a lot more detail and nuance to writing contracts, but this should give you a good starting point. diff --git a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/initializers.md b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/initializers.md index a45562ed84a7..da8abef90c5c 100644 --- a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/initializers.md +++ b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/initializers.md @@ -35,7 +35,7 @@ fn constructor(){ Initializers are commonly used to set an admin, such as this example: -```rust title="constructor" showLineNumbers +```rust title="constructor" showLineNumbers #[public] #[initializer] fn constructor(admin: AztecAddress, name: str<31>, symbol: str<31>, decimals: u8) { @@ -47,7 +47,7 @@ fn constructor(admin: AztecAddress, name: str<31>, symbol: str<31>, decimals: u8 storage.decimals.initialize(decimals); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L90-L103 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L90-L103 Here, the initializer is writing to storage. It can also call another function. Learn more about calling functions from functions [here](./call_contracts.md). diff --git a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/notes/address_note.md b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/notes/address_note.md index 5c8993834d0c..5f69765c5462 100644 --- a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/notes/address_note.md +++ b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/notes/address_note.md @@ -9,7 +9,7 @@ Address notes hold one main property of the type `AztecAddress`. It also holds ` This is the AddressNote: -```rust title="address_note_def" showLineNumbers +```rust title="address_note_def" showLineNumbers #[note] #[derive(Eq)] pub struct AddressNote { @@ -29,7 +29,7 @@ impl AddressNote { } } ``` -> Source code: noir-projects/aztec-nr/address-note/src/address_note.nr#L5-L24 +> Source code: noir-projects/aztec-nr/address-note/src/address_note.nr#L5-L24 ## Importing AddressNote @@ -37,15 +37,15 @@ impl AddressNote { ### In Nargo.toml ```toml -address_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/address-note" } +address_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/address-note" } ``` ### In your contract -```rust title="addressnote_import" showLineNumbers +```rust title="addressnote_import" showLineNumbers use dep::address_note::address_note::AddressNote; ``` -> Source code: noir-projects/noir-contracts/contracts/app/escrow_contract/src/main.nr#L14-L16 +> Source code: noir-projects/noir-contracts/contracts/app/escrow_contract/src/main.nr#L14-L16 ## Working with AddressNote @@ -57,10 +57,10 @@ Creating a new `AddressNote` takes the following args: - `address` (`AztecAddress`): the address to store in the AddressNote - `owner` (`AztecAddress`): owner is the party whose nullifying key can be used to spend the note -```rust title="addressnote_new" showLineNumbers +```rust title="addressnote_new" showLineNumbers let note = AddressNote::new(owner, owner); ``` -> Source code: noir-projects/noir-contracts/contracts/app/escrow_contract/src/main.nr#L28-L30 +> Source code: noir-projects/noir-contracts/contracts/app/escrow_contract/src/main.nr#L28-L30 In this example, `owner` is the `address` and the `npk_m_hash` of the donor was computed earlier. diff --git a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/notes/implementing_a_note.md b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/notes/implementing_a_note.md index eeeb0377e1ac..7905c758d6f5 100644 --- a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/notes/implementing_a_note.md +++ b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/notes/implementing_a_note.md @@ -16,7 +16,7 @@ You will likely want to define your note in a new file and import it into your c A note type can be defined with the macro `#[note]` used on a struct: -```rust title="state_vars-CardNote" showLineNumbers +```rust title="state_vars-CardNote" showLineNumbers // We derive the Serialize trait because this struct is returned from a contract function. When returned, // the struct is serialized using the Serialize trait and added to a hasher via the `add_to_hasher` utility. // We use a hash rather than the serialized struct itself to keep circuit inputs constant. @@ -28,7 +28,7 @@ pub struct CardNote { owner: AztecAddress, } ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/types/card_note.nr#L3-L14 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/types/card_note.nr#L3-L14 In this example, we are implementing a card note that holds a number of `points` as `u8`. diff --git a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/notes/value_note.md b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/notes/value_note.md index df6a52790b63..546791d495cb 100644 --- a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/notes/value_note.md +++ b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/notes/value_note.md @@ -9,7 +9,7 @@ ValueNotes hold one main property - a `value` - and have utils useful for manipu This is the ValueNote struct: -```rust title="value-note-def" showLineNumbers +```rust title="value-note-def" showLineNumbers #[note] #[derive(Eq)] pub struct ValueNote { @@ -18,7 +18,7 @@ pub struct ValueNote { randomness: Field, } ``` -> Source code: noir-projects/aztec-nr/value-note/src/value_note.nr#L3-L11 +> Source code: noir-projects/aztec-nr/value-note/src/value_note.nr#L3-L11 ## Importing ValueNote @@ -26,15 +26,15 @@ pub struct ValueNote { ### In Nargo.toml ```toml -value_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/value-note" } +value_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/value-note" } ``` ### In your contract -```rust title="import_valuenote" showLineNumbers +```rust title="import_valuenote" showLineNumbers use dep::value_note::value_note::ValueNote; ``` -> Source code: noir-projects/noir-contracts/contracts/test/child_contract/src/main.nr#L14-L16 +> Source code: noir-projects/noir-contracts/contracts/test/child_contract/src/main.nr#L14-L16 ## Working with ValueNote @@ -46,10 +46,10 @@ Creating a new `ValueNote` takes the following args: - `value` (`Field`): the value of the ValueNote - `owner` (`AztecAddress`): owner is the party whose nullifying key can be used to spend the note -```rust title="valuenote_new" showLineNumbers +```rust title="valuenote_new" showLineNumbers let note = ValueNote::new(new_value, owner); ``` -> Source code: noir-projects/noir-contracts/contracts/test/child_contract/src/main.nr#L60-L62 +> Source code: noir-projects/noir-contracts/contracts/test/child_contract/src/main.nr#L60-L62 ### Getting a balance @@ -58,11 +58,11 @@ A user may have multiple notes in a set that all refer to the same content (e.g. It takes one argument - the set of notes. -```rust title="get_balance" showLineNumbers +```rust title="get_balance" showLineNumbers // Return the sum of all notes in the set. balance_utils::get_balance(owner_balance) ``` -> Source code: noir-projects/noir-contracts/contracts/test/stateful_test_contract/src/main.nr#L105-L108 +> Source code: noir-projects/noir-contracts/contracts/test/stateful_test_contract/src/main.nr#L105-L108 This can only be used in an unconstrained function. @@ -71,19 +71,19 @@ This can only be used in an unconstrained function. Both `increment` and `decrement` functions take the same args: -```rust title="increment_args" showLineNumbers +```rust title="increment_args" showLineNumbers balance: PrivateSet, amount: Field, ``` -> Source code: noir-projects/aztec-nr/value-note/src/utils.nr#L27-L30 +> Source code: noir-projects/aztec-nr/value-note/src/utils.nr#L27-L30 Note that this will create a new note in the set of notes passed as the first argument. For example: -```rust title="increment_valuenote" showLineNumbers +```rust title="increment_valuenote" showLineNumbers increment(storage.notes.at(owner), value, owner, sender); ``` -> Source code: noir-projects/noir-contracts/contracts/test/benchmarking_contract/src/main.nr#L24-L26 +> Source code: noir-projects/noir-contracts/contracts/test/benchmarking_contract/src/main.nr#L24-L26 The `decrement` function works similarly except the `amount` is the number that the value will be decremented by, and it will fail if the sum of the selected notes is less than the amount. diff --git a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/portals/communicate_with_portal.md b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/portals/communicate_with_portal.md index 8232076febcc..3973c7938620 100644 --- a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/portals/communicate_with_portal.md +++ b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/portals/communicate_with_portal.md @@ -21,7 +21,7 @@ When sending messages, we need to specify quite a bit of information beyond just With all that information at hand, we can call the `sendL2Message` function on the Inbox. The function will return a `field` (inside `bytes32`) that is the hash of the message. This hash can be used as an identifier to spot when your message has been included in a rollup block. -```solidity title="send_l1_to_l2_message" showLineNumbers +```solidity title="send_l1_to_l2_message" showLineNumbers /** * @notice Inserts a new message into the Inbox * @dev Emits `MessageSent` with data for easy access by the sequencer @@ -36,7 +36,7 @@ function sendL2Message( bytes32 _secretHash ) external returns (bytes32, uint256); ``` -> Source code: l1-contracts/src/core/interfaces/messagebridge/IInbox.sol#L35-L49 +> Source code: l1-contracts/src/core/interfaces/messagebridge/IInbox.sol#L35-L49 A sequencer will consume the message batch your message was included in and include it in their block. @@ -53,7 +53,7 @@ To consume the message, we can use the `consume_l1_to_l2_message` function withi Note that while the `secret` and the `content` are both hashed, they are actually hashed with different hash functions! ::: -```rust title="context_consume_l1_to_l2_message" showLineNumbers +```rust title="context_consume_l1_to_l2_message" showLineNumbers pub fn consume_l1_to_l2_message( &mut self, content: Field, @@ -62,14 +62,14 @@ pub fn consume_l1_to_l2_message( leaf_index: Field, ) { ``` -> Source code: noir-projects/aztec-nr/aztec/src/context/private_context.nr#L292-L301 +> Source code: noir-projects/aztec-nr/aztec/src/context/private_context.nr#L292-L301 ### Token bridge example Computing the `content` must currently be done manually, as we are still adding a number of bytes utilities. A good example exists within the [Token bridge example (codealong tutorial)](../../../../../developers/tutorials/codealong/js_tutorials/token_bridge.md). -```rust title="claim_public" showLineNumbers +```rust title="claim_public" showLineNumbers // Consumes a L1->L2 message and calls the token contract to mint the appropriate amount publicly #[public] fn claim_public(to: AztecAddress, amount: u128, secret: Field, message_leaf_index: Field) { @@ -84,7 +84,7 @@ fn claim_public(to: AztecAddress, amount: u128, secret: Field, message_leaf_inde Token::at(config.token).mint_to_public(to, amount).call(&mut context); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_bridge_contract/src/main.nr#L57-L71 +> Source code: noir-projects/noir-contracts/contracts/app/token_bridge_contract/src/main.nr#L57-L71 :::info @@ -93,7 +93,7 @@ The `content_hash` is a sha256 truncated to a field element (~ 254 bits). In Azt ### Token portal hash library -```rust title="mint_to_public_content_hash_nr" showLineNumbers +```rust title="mint_to_public_content_hash_nr" showLineNumbers use dep::aztec::prelude::{AztecAddress, EthAddress}; use dep::aztec::protocol_types::{hash::sha256_to_field, traits::ToField}; @@ -122,20 +122,20 @@ pub fn get_mint_to_public_content_hash(owner: AztecAddress, amount: u128) -> Fie content_hash } ``` -> Source code: noir-projects/noir-contracts/contracts/libs/token_portal_content_hash_lib/src/lib.nr#L1-L29 +> Source code: noir-projects/noir-contracts/contracts/libs/token_portal_content_hash_lib/src/lib.nr#L1-L29 ### Token Portal contract In Solidity, you can use our `Hash.sha256ToField()` method: -```solidity title="content_hash_sol_import" showLineNumbers +```solidity title="content_hash_sol_import" showLineNumbers import {Hash} from "@aztec/core/libraries/crypto/Hash.sol"; ``` -> Source code: l1-contracts/test/portals/TokenPortal.sol#L12-L14 +> Source code: l1-contracts/test/portals/TokenPortal.sol#L12-L14 -```solidity title="deposit_public" showLineNumbers +```solidity title="deposit_public" showLineNumbers /** * @notice Deposit funds into the portal and adds an L2 message which can only be consumed publicly on Aztec * @param _to - The aztec address of the recipient @@ -147,7 +147,7 @@ function depositToAztecPublic(bytes32 _to, uint256 _amount, bytes32 _secretHash) external returns (bytes32, uint256) ``` -> Source code: l1-contracts/test/portals/TokenPortal.sol#L55-L66 +> Source code: l1-contracts/test/portals/TokenPortal.sol#L55-L66 The `secret_hash` uses the pederson hash which fits in a field element. You can use the utility method `computeSecretHash()`in `@aztec/aztec.js` npm package to generate a secret and its corresponding hash. @@ -170,10 +170,10 @@ The portal must ensure that the sender is as expected. One flexible solution is To send a message to L1 from your Aztec contract, you must use the `message_portal` function on the `context`. When messaging to L1, only the `content` is required (as a `Field`). -```rust title="context_message_portal" showLineNumbers +```rust title="context_message_portal" showLineNumbers pub fn message_portal(&mut self, recipient: EthAddress, content: Field) { ``` -> Source code: noir-projects/aztec-nr/aztec/src/context/private_context.nr#L285-L287 +> Source code: noir-projects/aztec-nr/aztec/src/context/private_context.nr#L285-L287 When sending a message from L2 to L1 we don't need to pass in a secret. @@ -186,7 +186,7 @@ Access control on the L1 portal contract is essential to prevent consumption of As earlier, we can use a token bridge as an example. In this case, we are burning tokens on L2 and sending a message to the portal to free them on L1. -```rust title="exit_to_l1_private" showLineNumbers +```rust title="exit_to_l1_private" showLineNumbers // Burns the appropriate amount of tokens and creates a L2 to L1 withdraw message privately // Requires `msg.sender` (caller of the method) to give approval to the bridge to burn tokens on their behalf using witness signatures #[private] @@ -210,12 +210,12 @@ fn exit_to_l1_private( Token::at(token).burn_private(context.msg_sender(), amount, nonce).call(&mut context); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_bridge_contract/src/main.nr#L125-L150 +> Source code: noir-projects/noir-contracts/contracts/app/token_bridge_contract/src/main.nr#L125-L150 When the transaction is included in a rollup block and published to Ethereum the message will be inserted into the `Outbox` on Ethereum, where the recipient portal can consume it from. When consuming, the `msg.sender` must match the `recipient` meaning that only portal can actually consume the message. -```solidity title="l2_to_l1_msg" showLineNumbers +```solidity title="l2_to_l1_msg" showLineNumbers /** * @notice Struct containing a message from L2 to L1 * @param sender - The sender of the message @@ -229,12 +229,12 @@ struct L2ToL1Msg { bytes32 content; } ``` -> Source code: l1-contracts/src/core/libraries/DataStructures.sol#L53-L66 +> Source code: l1-contracts/src/core/libraries/DataStructures.sol#L53-L66 #### Outbox `consume` -```solidity title="outbox_consume" showLineNumbers +```solidity title="outbox_consume" showLineNumbers /** * @notice Consumes an entry from the Outbox * @dev Only useable by portals / recipients of messages @@ -253,7 +253,7 @@ function consume( bytes32[] calldata _path ) external; ``` -> Source code: l1-contracts/src/core/interfaces/messagebridge/IOutbox.sol#L35-L53 +> Source code: l1-contracts/src/core/interfaces/messagebridge/IOutbox.sol#L35-L53 #### Withdraw @@ -262,7 +262,7 @@ As noted earlier, the portal contract should check that the sender is as expecte It is possible to support multiple senders from L2. You could use a have `mapping(address => bool) allowed` and check that `allowed[msg.sender]` is `true`. -```solidity title="token_portal_withdraw" showLineNumbers +```solidity title="token_portal_withdraw" showLineNumbers /** * @notice Withdraw funds from the portal * @dev Second part of withdraw, must be initiated from L2 first as it will consume a message from outbox @@ -302,7 +302,7 @@ function withdraw( underlying.transfer(_recipient, _amount); } ``` -> Source code: l1-contracts/test/portals/TokenPortal.sol#L122-L161 +> Source code: l1-contracts/test/portals/TokenPortal.sol#L122-L161 ## Considerations @@ -375,5 +375,5 @@ Designated callers are enforced at the contract level for contracts that are not ## Examples of portals - Token bridge (Portal contract built for L1 -> L2, i.e., a non-native L2 asset) - - [Portal contract (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/l1-contracts/test/portals/TokenPortal.sol) - - [Aztec contract (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/noir-projects/noir-contracts/contracts/app/token_bridge_contract/src/main.nr) + - [Portal contract (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/l1-contracts/test/portals/TokenPortal.sol) + - [Aztec contract (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/noir-projects/noir-contracts/contracts/app/token_bridge_contract/src/main.nr) diff --git a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/storage/notes.md b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/storage/notes.md index d2e343a6df9b..1329ce586359 100644 --- a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/storage/notes.md +++ b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/storage/notes.md @@ -26,7 +26,7 @@ A detailed explanation of the transaction lifecycle can be found [here](../../.. ## Private state variables in Aztec -State variables in an Aztec contract are defined inside a struct specifically named `Storage`, and must satisfy the [Note Interface (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.3/noir-projects/aztec-nr/aztec/src/note/note_interface.nr) and contain a [Note header (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.3/noir-projects/aztec-nr/aztec/src/note/note_header.nr). +State variables in an Aztec contract are defined inside a struct specifically named `Storage`, and must satisfy the [Note Interface (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.4/noir-projects/aztec-nr/aztec/src/note/note_interface.nr) and contain a [Note header (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.4/noir-projects/aztec-nr/aztec/src/note/note_header.nr). The Note header struct contains the contract address which the value is effectively siloed to, a nonce to ensure unique Note hashes, and a storage "slot" (or ID) to associate multiple notes. @@ -97,19 +97,19 @@ The way Aztec benefits from the Noir language is via three important components: - `noir contracts` - example Aztec contracts - `noir-protocol-circuits` - a crate containing essential circuits for the protocol (public circuits and private wrappers) -A lot of what we will look at will be in [aztec-nr/aztec/src/note (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.3/noir-projects/aztec-nr/aztec/src/note), specifically the lifecycle and note interface. +A lot of what we will look at will be in [aztec-nr/aztec/src/note (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.4/noir-projects/aztec-nr/aztec/src/note), specifically the lifecycle and note interface. Looking at the noir circuits in these components, you will see references to the distinction between public/private execution and state. ### Lifecycle functions -Inside the [lifecycle (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.3/noir-projects/aztec-nr/aztec/src/note/lifecycle.nr) circuits we see the functions to create and destroy a note, implemented as insertions of note hashes and nullifiers respectively. This is helpful for regular private variables. +Inside the [lifecycle (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.4/noir-projects/aztec-nr/aztec/src/note/lifecycle.nr) circuits we see the functions to create and destroy a note, implemented as insertions of note hashes and nullifiers respectively. This is helpful for regular private variables. We also see a function to create a note hash from the public context, a way of creating a private variable from a public call (run in the sequencer). This could be used in application contracts to give private digital assets to users. ### Note Interface functions -To see a [note_interface (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.3/noir-projects/aztec-nr/aztec/src/note/note_interface.nr) implementation, we will look at a simple [ValueNote GitHub link](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.3/noir-projects/aztec-nr/value-note/src/value_note.nr). +To see a [note_interface (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.4/noir-projects/aztec-nr/aztec/src/note/note_interface.nr) implementation, we will look at a simple [ValueNote GitHub link](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.4/noir-projects/aztec-nr/value-note/src/value_note.nr). The interface is required to work within an Aztec contract's storage, and a ValueNote is a specific type of note to hold a number (as a `Field`). @@ -119,7 +119,7 @@ A few key functions in the note interface are around computing the note hash and In the ValueNote implementation you'll notice that it uses the `pedersen_hash` function. This is currently required by the protocol, but may be updated to another hashing function, like poseidon. -As a convenience, the outer [note/utils.nr (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.3/noir-projects/aztec-nr/aztec/src/note/utils.nr) contains implementations of functions that may be needed in Aztec contracts, for example computing note hashes. +As a convenience, the outer [note/utils.nr (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.4/noir-projects/aztec-nr/aztec/src/note/utils.nr) contains implementations of functions that may be needed in Aztec contracts, for example computing note hashes. #### Serialization and deserialization @@ -140,7 +140,7 @@ A couple of things worth clarifying: ### Example - Notes in action -The Aztec.nr framework includes examples of high-level states [easy_private_uint (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.3/noir-projects/aztec-nr/easy-private-state/src/easy_private_uint.nr) for use in contracts. +The Aztec.nr framework includes examples of high-level states [easy_private_uint (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.4/noir-projects/aztec-nr/easy-private-state/src/easy_private_uint.nr) for use in contracts. The struct (`EasyPrivateUint`) contains a Context, Set of ValueNotes, and storage_slot (used when setting the Set). diff --git a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/storage/storage_slots.md b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/storage/storage_slots.md index 96a36febc941..aaa2632c388f 100644 --- a/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/storage/storage_slots.md +++ b/docs/versioned_docs/version-Latest/developers/guides/smart_contracts/writing_contracts/storage/storage_slots.md @@ -7,14 +7,14 @@ From the description of storage slots [in the Concepts](../../../../../aztec/con For the case of the example, we will look at what is inserted into the note hashes tree when adding a note in the Token contract. Specifically, we are looking at the last part of the `transfer` function: -```rust title="increase_private_balance" showLineNumbers +```rust title="increase_private_balance" showLineNumbers storage.balances.at(from).sub(from, amount).emit(encode_and_encrypt_note( &mut context, from, from, )); ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L374-L380 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L374-L380 This function is creating a new note and inserting it into the balance set of the recipient `to`. Recall that to ensure privacy, only the note hash is really inserted into the note hashes tree. To share the contents of the note with `to` the contract can emit an encrypted log (which this one does), or it can require an out-of-band data transfer sharing the information. Below, we will walk through the steps of how the note hash is computed and inserted into the tree. For this, we don't care about the encrypted log, so we are going to ignore that part of the function call for now. diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/_category_.yml b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/_category_.yml similarity index 100% rename from docs/versioned_docs/version-Latest/developers/reference/aztecjs/_category_.yml rename to docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/_category_.yml diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/accounts/_category_.yml b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/_category_.yml similarity index 100% rename from docs/versioned_docs/version-Latest/developers/reference/aztecjs/accounts/_category_.yml rename to docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/_category_.yml diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/accounts/classes/_category_.yml b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/classes/_category_.yml similarity index 100% rename from docs/versioned_docs/version-Latest/developers/reference/aztecjs/accounts/classes/_category_.yml rename to docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/classes/_category_.yml diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/classes/defaults.DefaultAccountContract.md b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/classes/defaults.DefaultAccountContract.md new file mode 100644 index 000000000000..11d775807e59 --- /dev/null +++ b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/classes/defaults.DefaultAccountContract.md @@ -0,0 +1,94 @@ +--- +id: "defaults.DefaultAccountContract" +title: "Class: DefaultAccountContract" +sidebar_label: "DefaultAccountContract" +custom_edit_url: null +--- + +[defaults](../modules/defaults.md).DefaultAccountContract + +Base class for implementing an account contract. Requires that the account uses the +default entrypoint method signature. + +## Implements + +- `AccountContract` + +## Constructors + +### constructor + +• **new DefaultAccountContract**(): [`DefaultAccountContract`](defaults.DefaultAccountContract.md) + +#### Returns + +[`DefaultAccountContract`](defaults.DefaultAccountContract.md) + +## Methods + +### getAuthWitnessProvider + +▸ **getAuthWitnessProvider**(`address`): `AuthWitnessProvider` + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `address` | `CompleteAddress` | + +#### Returns + +`AuthWitnessProvider` + +#### Implementation of + +AccountContract.getAuthWitnessProvider + +___ + +### getContractArtifact + +▸ **getContractArtifact**(): `Promise`\<`ContractArtifact`\> + +#### Returns + +`Promise`\<`ContractArtifact`\> + +#### Implementation of + +AccountContract.getContractArtifact + +___ + +### getDeploymentFunctionAndArgs + +▸ **getDeploymentFunctionAndArgs**(): `Promise`\<`undefined` \| \{ `constructorArgs`: `any`[] ; `constructorName`: `string` }\> + +#### Returns + +`Promise`\<`undefined` \| \{ `constructorArgs`: `any`[] ; `constructorName`: `string` }\> + +#### Implementation of + +AccountContract.getDeploymentFunctionAndArgs + +___ + +### getInterface + +▸ **getInterface**(`address`, `nodeInfo`): `AccountInterface` + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `address` | `CompleteAddress` | +| `nodeInfo` | `NodeInfo` | + +#### Returns + +`AccountInterface` + +#### Implementation of + +AccountContract.getInterface diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/classes/defaults.DefaultAccountInterface.md b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/classes/defaults.DefaultAccountInterface.md new file mode 100644 index 000000000000..b55ab89a094d --- /dev/null +++ b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/classes/defaults.DefaultAccountInterface.md @@ -0,0 +1,161 @@ +--- +id: "defaults.DefaultAccountInterface" +title: "Class: DefaultAccountInterface" +sidebar_label: "DefaultAccountInterface" +custom_edit_url: null +--- + +[defaults](../modules/defaults.md).DefaultAccountInterface + +Default implementation for an account interface. Requires that the account uses the default +entrypoint signature, which accept an AppPayload and a FeePayload as defined in noir-libs/aztec-noir/src/entrypoint module + +## Implements + +- `AccountInterface` + +## Constructors + +### constructor + +• **new DefaultAccountInterface**(`authWitnessProvider`, `address`, `nodeInfo`): [`DefaultAccountInterface`](defaults.DefaultAccountInterface.md) + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `authWitnessProvider` | `AuthWitnessProvider` | +| `address` | `CompleteAddress` | +| `nodeInfo` | `Pick`\<`NodeInfo`, ``"l1ChainId"`` \| ``"rollupVersion"``\> | + +#### Returns + +[`DefaultAccountInterface`](defaults.DefaultAccountInterface.md) + +## Properties + +### address + +• `Private` **address**: `CompleteAddress` + +___ + +### authWitnessProvider + +• `Private` **authWitnessProvider**: `AuthWitnessProvider` + +___ + +### chainId + +• `Private` **chainId**: `Fr` + +___ + +### entrypoint + +• `Protected` **entrypoint**: `EntrypointInterface` + +___ + +### version + +• `Private` **version**: `Fr` + +## Methods + +### createAuthWit + +▸ **createAuthWit**(`messageHash`): `Promise`\<`AuthWitness`\> + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `messageHash` | `Fr` | + +#### Returns + +`Promise`\<`AuthWitness`\> + +#### Implementation of + +AccountInterface.createAuthWit + +___ + +### createTxExecutionRequest + +▸ **createTxExecutionRequest**(`exec`, `fee`, `options`): `Promise`\<`TxExecutionRequest`\> + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `exec` | `ExecutionPayload` | +| `fee` | `FeeOptions` | +| `options` | `TxExecutionOptions` | + +#### Returns + +`Promise`\<`TxExecutionRequest`\> + +#### Implementation of + +AccountInterface.createTxExecutionRequest + +___ + +### getAddress + +▸ **getAddress**(): `AztecAddress` + +#### Returns + +`AztecAddress` + +#### Implementation of + +AccountInterface.getAddress + +___ + +### getChainId + +▸ **getChainId**(): `Fr` + +#### Returns + +`Fr` + +#### Implementation of + +AccountInterface.getChainId + +___ + +### getCompleteAddress + +▸ **getCompleteAddress**(): `CompleteAddress` + +#### Returns + +`CompleteAddress` + +#### Implementation of + +AccountInterface.getCompleteAddress + +___ + +### getVersion + +▸ **getVersion**(): `Fr` + +#### Returns + +`Fr` + +#### Implementation of + +AccountInterface.getVersion diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/classes/ecdsa.EcdsaKAccountContract.md b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/classes/ecdsa.EcdsaKAccountContract.md new file mode 100644 index 000000000000..d3b53c1f12a3 --- /dev/null +++ b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/classes/ecdsa.EcdsaKAccountContract.md @@ -0,0 +1,107 @@ +--- +id: "ecdsa.EcdsaKAccountContract" +title: "Class: EcdsaKAccountContract" +sidebar_label: "EcdsaKAccountContract" +custom_edit_url: null +--- + +[ecdsa](../modules/ecdsa.md).EcdsaKAccountContract + +Account contract that authenticates transactions using ECDSA signatures +verified against a secp256k1 public key stored in an immutable encrypted note. +Eagerly loads the contract artifact + +## Hierarchy + +- `EcdsaKBaseAccountContract` + + ↳ **`EcdsaKAccountContract`** + +## Constructors + +### constructor + +• **new EcdsaKAccountContract**(`signingPrivateKey`): [`EcdsaKAccountContract`](ecdsa.EcdsaKAccountContract.md) + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `signingPrivateKey` | `Buffer`\<`ArrayBufferLike`\> | + +#### Returns + +[`EcdsaKAccountContract`](ecdsa.EcdsaKAccountContract.md) + +#### Overrides + +EcdsaKBaseAccountContract.constructor + +## Methods + +### getAuthWitnessProvider + +▸ **getAuthWitnessProvider**(`_address`): `AuthWitnessProvider` + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `_address` | `CompleteAddress` | + +#### Returns + +`AuthWitnessProvider` + +#### Inherited from + +EcdsaKBaseAccountContract.getAuthWitnessProvider + +___ + +### getContractArtifact + +▸ **getContractArtifact**(): `Promise`\<`ContractArtifact`\> + +#### Returns + +`Promise`\<`ContractArtifact`\> + +#### Overrides + +EcdsaKBaseAccountContract.getContractArtifact + +___ + +### getDeploymentFunctionAndArgs + +▸ **getDeploymentFunctionAndArgs**(): `Promise`\<\{ `constructorArgs`: `Buffer`\<`ArrayBufferLike`\>[] ; `constructorName`: `string` = 'constructor' }\> + +#### Returns + +`Promise`\<\{ `constructorArgs`: `Buffer`\<`ArrayBufferLike`\>[] ; `constructorName`: `string` = 'constructor' }\> + +#### Inherited from + +EcdsaKBaseAccountContract.getDeploymentFunctionAndArgs + +___ + +### getInterface + +▸ **getInterface**(`address`, `nodeInfo`): `AccountInterface` + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `address` | `CompleteAddress` | +| `nodeInfo` | `NodeInfo` | + +#### Returns + +`AccountInterface` + +#### Inherited from + +EcdsaKBaseAccountContract.getInterface diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/classes/ecdsa.EcdsaRAccountContract.md b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/classes/ecdsa.EcdsaRAccountContract.md new file mode 100644 index 000000000000..caa361538ef0 --- /dev/null +++ b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/classes/ecdsa.EcdsaRAccountContract.md @@ -0,0 +1,107 @@ +--- +id: "ecdsa.EcdsaRAccountContract" +title: "Class: EcdsaRAccountContract" +sidebar_label: "EcdsaRAccountContract" +custom_edit_url: null +--- + +[ecdsa](../modules/ecdsa.md).EcdsaRAccountContract + +Account contract that authenticates transactions using ECDSA signatures +verified against a secp256k1 public key stored in an immutable encrypted note. +Eagerly loads the contract artifact + +## Hierarchy + +- `EcdsaRBaseAccountContract` + + ↳ **`EcdsaRAccountContract`** + +## Constructors + +### constructor + +• **new EcdsaRAccountContract**(`signingPrivateKey`): [`EcdsaRAccountContract`](ecdsa.EcdsaRAccountContract.md) + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `signingPrivateKey` | `Buffer`\<`ArrayBufferLike`\> | + +#### Returns + +[`EcdsaRAccountContract`](ecdsa.EcdsaRAccountContract.md) + +#### Overrides + +EcdsaRBaseAccountContract.constructor + +## Methods + +### getAuthWitnessProvider + +▸ **getAuthWitnessProvider**(`_address`): `AuthWitnessProvider` + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `_address` | `CompleteAddress` | + +#### Returns + +`AuthWitnessProvider` + +#### Inherited from + +EcdsaRBaseAccountContract.getAuthWitnessProvider + +___ + +### getContractArtifact + +▸ **getContractArtifact**(): `Promise`\<`ContractArtifact`\> + +#### Returns + +`Promise`\<`ContractArtifact`\> + +#### Overrides + +EcdsaRBaseAccountContract.getContractArtifact + +___ + +### getDeploymentFunctionAndArgs + +▸ **getDeploymentFunctionAndArgs**(): `Promise`\<\{ `constructorArgs`: `Buffer`\<`ArrayBufferLike`\>[] ; `constructorName`: `string` = 'constructor' }\> + +#### Returns + +`Promise`\<\{ `constructorArgs`: `Buffer`\<`ArrayBufferLike`\>[] ; `constructorName`: `string` = 'constructor' }\> + +#### Inherited from + +EcdsaRBaseAccountContract.getDeploymentFunctionAndArgs + +___ + +### getInterface + +▸ **getInterface**(`address`, `nodeInfo`): `AccountInterface` + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `address` | `CompleteAddress` | +| `nodeInfo` | `NodeInfo` | + +#### Returns + +`AccountInterface` + +#### Inherited from + +EcdsaRBaseAccountContract.getInterface diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/classes/ecdsa.EcdsaRSSHAccountContract.md b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/classes/ecdsa.EcdsaRSSHAccountContract.md new file mode 100644 index 000000000000..88a0c22852a5 --- /dev/null +++ b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/classes/ecdsa.EcdsaRSSHAccountContract.md @@ -0,0 +1,110 @@ +--- +id: "ecdsa.EcdsaRSSHAccountContract" +title: "Class: EcdsaRSSHAccountContract" +sidebar_label: "EcdsaRSSHAccountContract" +custom_edit_url: null +--- + +[ecdsa](../modules/ecdsa.md).EcdsaRSSHAccountContract + +Account contract that authenticates transactions using ECDSA signatures +verified against a secp256r1 public key stored in an immutable encrypted note. +Since this implementation relays signatures to an SSH agent, we provide the +public key here not for signature verification, but to identify actual identity +that will be used to sign authwitnesses. +Eagerly loads the contract artifact + +## Hierarchy + +- `EcdsaRSSHBaseAccountContract` + + ↳ **`EcdsaRSSHAccountContract`** + +## Constructors + +### constructor + +• **new EcdsaRSSHAccountContract**(`signingPrivateKey`): [`EcdsaRSSHAccountContract`](ecdsa.EcdsaRSSHAccountContract.md) + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `signingPrivateKey` | `Buffer`\<`ArrayBufferLike`\> | + +#### Returns + +[`EcdsaRSSHAccountContract`](ecdsa.EcdsaRSSHAccountContract.md) + +#### Overrides + +EcdsaRSSHBaseAccountContract.constructor + +## Methods + +### getAuthWitnessProvider + +▸ **getAuthWitnessProvider**(`_address`): `AuthWitnessProvider` + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `_address` | `CompleteAddress` | + +#### Returns + +`AuthWitnessProvider` + +#### Inherited from + +EcdsaRSSHBaseAccountContract.getAuthWitnessProvider + +___ + +### getContractArtifact + +▸ **getContractArtifact**(): `Promise`\<`ContractArtifact`\> + +#### Returns + +`Promise`\<`ContractArtifact`\> + +#### Overrides + +EcdsaRSSHBaseAccountContract.getContractArtifact + +___ + +### getDeploymentFunctionAndArgs + +▸ **getDeploymentFunctionAndArgs**(): `Promise`\<\{ `constructorArgs`: `Buffer`\<`ArrayBufferLike`\>[] ; `constructorName`: `string` = 'constructor' }\> + +#### Returns + +`Promise`\<\{ `constructorArgs`: `Buffer`\<`ArrayBufferLike`\>[] ; `constructorName`: `string` = 'constructor' }\> + +#### Inherited from + +EcdsaRSSHBaseAccountContract.getDeploymentFunctionAndArgs + +___ + +### getInterface + +▸ **getInterface**(`address`, `nodeInfo`): `AccountInterface` + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `address` | `CompleteAddress` | +| `nodeInfo` | `NodeInfo` | + +#### Returns + +`AccountInterface` + +#### Inherited from + +EcdsaRSSHBaseAccountContract.getInterface diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/classes/schnorr.SchnorrAccountContract.md b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/classes/schnorr.SchnorrAccountContract.md new file mode 100644 index 000000000000..ba045b038046 --- /dev/null +++ b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/classes/schnorr.SchnorrAccountContract.md @@ -0,0 +1,107 @@ +--- +id: "schnorr.SchnorrAccountContract" +title: "Class: SchnorrAccountContract" +sidebar_label: "SchnorrAccountContract" +custom_edit_url: null +--- + +[schnorr](../modules/schnorr.md).SchnorrAccountContract + +Account contract that authenticates transactions using Schnorr signatures +verified against a Grumpkin public key stored in an immutable encrypted note. +Eagerly loads the contract artifact + +## Hierarchy + +- `SchnorrBaseAccountContract` + + ↳ **`SchnorrAccountContract`** + +## Constructors + +### constructor + +• **new SchnorrAccountContract**(`signingPrivateKey`): [`SchnorrAccountContract`](schnorr.SchnorrAccountContract.md) + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `signingPrivateKey` | `Fq` | + +#### Returns + +[`SchnorrAccountContract`](schnorr.SchnorrAccountContract.md) + +#### Overrides + +SchnorrBaseAccountContract.constructor + +## Methods + +### getAuthWitnessProvider + +▸ **getAuthWitnessProvider**(`_address`): `AuthWitnessProvider` + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `_address` | `CompleteAddress` | + +#### Returns + +`AuthWitnessProvider` + +#### Inherited from + +SchnorrBaseAccountContract.getAuthWitnessProvider + +___ + +### getContractArtifact + +▸ **getContractArtifact**(): `Promise`\<`ContractArtifact`\> + +#### Returns + +`Promise`\<`ContractArtifact`\> + +#### Overrides + +SchnorrBaseAccountContract.getContractArtifact + +___ + +### getDeploymentFunctionAndArgs + +▸ **getDeploymentFunctionAndArgs**(): `Promise`\<\{ `constructorArgs`: `Fr`[] ; `constructorName`: `string` = 'constructor' }\> + +#### Returns + +`Promise`\<\{ `constructorArgs`: `Fr`[] ; `constructorName`: `string` = 'constructor' }\> + +#### Inherited from + +SchnorrBaseAccountContract.getDeploymentFunctionAndArgs + +___ + +### getInterface + +▸ **getInterface**(`address`, `nodeInfo`): `AccountInterface` + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `address` | `CompleteAddress` | +| `nodeInfo` | `NodeInfo` | + +#### Returns + +`AccountInterface` + +#### Inherited from + +SchnorrBaseAccountContract.getInterface diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/classes/single_key.SingleKeyAccountContract.md b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/classes/single_key.SingleKeyAccountContract.md new file mode 100644 index 000000000000..d9b230516512 --- /dev/null +++ b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/classes/single_key.SingleKeyAccountContract.md @@ -0,0 +1,107 @@ +--- +id: "single_key.SingleKeyAccountContract" +title: "Class: SingleKeyAccountContract" +sidebar_label: "SingleKeyAccountContract" +custom_edit_url: null +--- + +[single\_key](../modules/single_key.md).SingleKeyAccountContract + +Account contract that authenticates transactions using Schnorr signatures verified against +the note encryption key, relying on a single private key for both encryption and authentication. +Eagerly loads the contract artifact + +## Hierarchy + +- `SingleKeyBaseAccountContract` + + ↳ **`SingleKeyAccountContract`** + +## Constructors + +### constructor + +• **new SingleKeyAccountContract**(`signingPrivateKey`): [`SingleKeyAccountContract`](single_key.SingleKeyAccountContract.md) + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `signingPrivateKey` | `Fq` | + +#### Returns + +[`SingleKeyAccountContract`](single_key.SingleKeyAccountContract.md) + +#### Overrides + +SingleKeyBaseAccountContract.constructor + +## Methods + +### getAuthWitnessProvider + +▸ **getAuthWitnessProvider**(`account`): `AuthWitnessProvider` + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `account` | `CompleteAddress` | + +#### Returns + +`AuthWitnessProvider` + +#### Inherited from + +SingleKeyBaseAccountContract.getAuthWitnessProvider + +___ + +### getContractArtifact + +▸ **getContractArtifact**(): `Promise`\<`ContractArtifact`\> + +#### Returns + +`Promise`\<`ContractArtifact`\> + +#### Overrides + +SingleKeyBaseAccountContract.getContractArtifact + +___ + +### getDeploymentFunctionAndArgs + +▸ **getDeploymentFunctionAndArgs**(): `Promise`\<`undefined`\> + +#### Returns + +`Promise`\<`undefined`\> + +#### Inherited from + +SingleKeyBaseAccountContract.getDeploymentFunctionAndArgs + +___ + +### getInterface + +▸ **getInterface**(`address`, `nodeInfo`): `AccountInterface` + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `address` | `CompleteAddress` | +| `nodeInfo` | `NodeInfo` | + +#### Returns + +`AccountInterface` + +#### Inherited from + +SingleKeyBaseAccountContract.getInterface diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/index.md b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/index.md new file mode 100644 index 000000000000..0c19cb267f7e --- /dev/null +++ b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/index.md @@ -0,0 +1,16 @@ +--- +id: "index" +title: "@aztec/accounts" +sidebar_label: "Table of Contents" +sidebar_position: 0.5 +hide_table_of_contents: true +custom_edit_url: null +--- + +## Modules + +- [defaults](modules/defaults.md) +- [ecdsa](modules/ecdsa.md) +- [schnorr](modules/schnorr.md) +- [single\_key](modules/single_key.md) +- [testing](modules/testing.md) diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/accounts/interfaces/_category_.yml b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/interfaces/_category_.yml similarity index 100% rename from docs/versioned_docs/version-Latest/developers/reference/aztecjs/accounts/interfaces/_category_.yml rename to docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/interfaces/_category_.yml diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/interfaces/testing.InitialAccountData.md b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/interfaces/testing.InitialAccountData.md new file mode 100644 index 000000000000..7b2757593317 --- /dev/null +++ b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/interfaces/testing.InitialAccountData.md @@ -0,0 +1,42 @@ +--- +id: "testing.InitialAccountData" +title: "Interface: InitialAccountData" +sidebar_label: "InitialAccountData" +custom_edit_url: null +--- + +[testing](../modules/testing.md).InitialAccountData + +Data for generating an initial account. + +## Properties + +### address + +• **address**: `AztecAddress` + +Address of the schnorr account contract. + +___ + +### salt + +• **salt**: `Fr` + +Contract address salt. + +___ + +### secret + +• **secret**: `Fr` + +Secret to derive the keys for the account. + +___ + +### signingKey + +• **signingKey**: `Fq` + +Signing key od the account. diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/accounts/modules/_category_.yml b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/modules/_category_.yml similarity index 100% rename from docs/versioned_docs/version-Latest/developers/reference/aztecjs/accounts/modules/_category_.yml rename to docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/modules/_category_.yml diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/modules/defaults.md b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/modules/defaults.md new file mode 100644 index 000000000000..9252b70f72ae --- /dev/null +++ b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/modules/defaults.md @@ -0,0 +1,16 @@ +--- +id: "defaults" +title: "Module: defaults" +sidebar_label: "defaults" +sidebar_position: 0 +custom_edit_url: null +--- + +The `@aztec/accounts/defaults` export provides the base class [DefaultAccountContract](../classes/defaults.DefaultAccountContract.md) for implementing account contracts that use the default entrypoint payload module. + +Read more in [Writing an account contract](https://docs.aztec.network/developers/tutorials/codealong/contract_tutorials/write_accounts_contract). + +## Classes + +- [DefaultAccountContract](../classes/defaults.DefaultAccountContract.md) +- [DefaultAccountInterface](../classes/defaults.DefaultAccountInterface.md) diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/modules/ecdsa.md b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/modules/ecdsa.md new file mode 100644 index 000000000000..98a99dcece1b --- /dev/null +++ b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/modules/ecdsa.md @@ -0,0 +1,160 @@ +--- +id: "ecdsa" +title: "Module: ecdsa" +sidebar_label: "ecdsa" +sidebar_position: 0 +custom_edit_url: null +--- + +## Classes + +- [EcdsaKAccountContract](../classes/ecdsa.EcdsaKAccountContract.md) +- [EcdsaRAccountContract](../classes/ecdsa.EcdsaRAccountContract.md) +- [EcdsaRSSHAccountContract](../classes/ecdsa.EcdsaRSSHAccountContract.md) + +## Variables + +### EcdsaKAccountContractArtifact + +• `Const` **EcdsaKAccountContractArtifact**: `ContractArtifact` + +___ + +### EcdsaRAccountContractArtifact + +• `Const` **EcdsaRAccountContractArtifact**: `ContractArtifact` + +## Functions + +### getEcdsaKAccount + +▸ **getEcdsaKAccount**(`pxe`, `secretKey`, `signingPrivateKey`, `salt?`): `Promise`\<`AccountManager`\> + +Creates an Account that relies on an ECDSA signing key for authentication. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `pxe` | `PXE` | An PXE server instance. | +| `secretKey` | `Fr` | Secret key used to derive all the keystore keys. | +| `signingPrivateKey` | `Buffer`\<`ArrayBufferLike`\> | Secp256k1 key used for signing transactions. | +| `salt?` | `Salt` | Deployment salt. | + +#### Returns + +`Promise`\<`AccountManager`\> + +An account manager initialized with the account contract and its deployment params + +___ + +### getEcdsaKWallet + +▸ **getEcdsaKWallet**(`pxe`, `address`, `signingPrivateKey`): `Promise`\<`AccountWallet`\> + +Gets a wallet for an already registered account using ECDSA signatures. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `pxe` | `PXE` | An PXE server instance. | +| `address` | `AztecAddress` | Address for the account. | +| `signingPrivateKey` | `Buffer`\<`ArrayBufferLike`\> | ECDSA key used for signing transactions. | + +#### Returns + +`Promise`\<`AccountWallet`\> + +A wallet for this account that can be used to interact with a contract instance. + +___ + +### getEcdsaRAccount + +▸ **getEcdsaRAccount**(`pxe`, `secretKey`, `signingPrivateKey`, `salt?`): `Promise`\<`AccountManager`\> + +Creates an Account that relies on an ECDSA signing key for authentication. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `pxe` | `PXE` | An PXE server instance. | +| `secretKey` | `Fr` | Secret key used to derive all the keystore keys. | +| `signingPrivateKey` | `Buffer`\<`ArrayBufferLike`\> | Secp256k1 key used for signing transactions. | +| `salt?` | `Salt` | Deployment salt. | + +#### Returns + +`Promise`\<`AccountManager`\> + +An account manager initialized with the account contract and its deployment params + +___ + +### getEcdsaRSSHAccount + +▸ **getEcdsaRSSHAccount**(`pxe`, `secretKey`, `signingPublicKey`, `salt?`): `Promise`\<`AccountManager`\> + +Creates an Account that relies on an ECDSA signing key for authentication. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `pxe` | `PXE` | An PXE server instance. | +| `secretKey` | `Fr` | Secret key used to derive all the keystore keys. | +| `signingPublicKey` | `Buffer`\<`ArrayBufferLike`\> | Secp2561 key used to identify its corresponding private key in the SSH Agent. | +| `salt?` | `Salt` | Deployment salt. | + +#### Returns + +`Promise`\<`AccountManager`\> + +An account manager initialized with the account contract and its deployment params + +___ + +### getEcdsaRSSHWallet + +▸ **getEcdsaRSSHWallet**(`pxe`, `address`, `signingPublicKey`): `Promise`\<`AccountWallet`\> + +Gets a wallet for an already registered account using ECDSA signatures. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `pxe` | `PXE` | An PXE server instance. | +| `address` | `AztecAddress` | Address for the account. | +| `signingPublicKey` | `Buffer`\<`ArrayBufferLike`\> | - | + +#### Returns + +`Promise`\<`AccountWallet`\> + +A wallet for this account that can be used to interact with a contract instance. + +___ + +### getEcdsaRWallet + +▸ **getEcdsaRWallet**(`pxe`, `address`, `signingPrivateKey`): `Promise`\<`AccountWallet`\> + +Gets a wallet for an already registered account using ECDSA signatures. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `pxe` | `PXE` | An PXE server instance. | +| `address` | `AztecAddress` | Address for the account. | +| `signingPrivateKey` | `Buffer`\<`ArrayBufferLike`\> | ECDSA key used for signing transactions. | + +#### Returns + +`Promise`\<`AccountWallet`\> + +A wallet for this account that can be used to interact with a contract instance. diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/modules/schnorr.md b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/modules/schnorr.md new file mode 100644 index 000000000000..cbd6dcd7734e --- /dev/null +++ b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/modules/schnorr.md @@ -0,0 +1,108 @@ +--- +id: "schnorr" +title: "Module: schnorr" +sidebar_label: "schnorr" +sidebar_position: 0 +custom_edit_url: null +--- + +The `@aztec/accounts/schnorr` export provides an account contract implementation that uses Schnorr signatures with a Grumpkin key for authentication, and a separate Grumpkin key for encryption. +This is the suggested account contract type for most use cases within Aztec. + +## Classes + +- [SchnorrAccountContract](../classes/schnorr.SchnorrAccountContract.md) + +## Variables + +### SchnorrAccountContractArtifact + +• `Const` **SchnorrAccountContractArtifact**: `ContractArtifact` + +## Functions + +### getSchnorrAccount + +▸ **getSchnorrAccount**(`pxe`, `secretKey`, `signingPrivateKey`, `salt?`): `Promise`\<`AccountManager`\> + +Creates an Account Manager that relies on a Grumpkin signing key for authentication. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `pxe` | `PXE` | An PXE server instance. | +| `secretKey` | `Fr` | Secret key used to derive all the keystore keys. | +| `signingPrivateKey` | `Fq` | Grumpkin key used for signing transactions. | +| `salt?` | `Salt` | Deployment salt. | + +#### Returns + +`Promise`\<`AccountManager`\> + +An account manager initialized with the account contract and its deployment params + +___ + +### getSchnorrAccountContractAddress + +▸ **getSchnorrAccountContractAddress**(`secret`, `salt`, `signingPrivateKey?`): `Promise`\<`AztecAddress`\> + +Compute the address of a schnorr account contract. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `secret` | `Fr` | A seed for deriving the signing key and public keys. | +| `salt` | `Fr` | The contract address salt. | +| `signingPrivateKey?` | `Fq` | A specific signing private key that's not derived from the secret. | + +#### Returns + +`Promise`\<`AztecAddress`\> + +___ + +### getSchnorrWallet + +▸ **getSchnorrWallet**(`pxe`, `address`, `signingPrivateKey`): `Promise`\<`AccountWallet`\> + +Gets a wallet for an already registered account using Schnorr signatures. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `pxe` | `PXE` | An PXE server instance. | +| `address` | `AztecAddress` | Address for the account. | +| `signingPrivateKey` | `Fq` | Grumpkin key used for signing transactions. | + +#### Returns + +`Promise`\<`AccountWallet`\> + +A wallet for this account that can be used to interact with a contract instance. + +___ + +### getSchnorrWalletWithSecretKey + +▸ **getSchnorrWalletWithSecretKey**(`pxe`, `secretKey`, `signingPrivateKey`, `salt`): `Promise`\<`AccountWalletWithSecretKey`\> + +Gets a wallet for an already registered account using Schnorr signatures. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `pxe` | `PXE` | An PXE server instance. | +| `secretKey` | `Fr` | Secret key used to derive all the keystore keys. | +| `signingPrivateKey` | `Fq` | Grumpkin key used for signing transactions. | +| `salt` | `Salt` | Deployment salt. | + +#### Returns + +`Promise`\<`AccountWalletWithSecretKey`\> + +A wallet for this account that can be used to interact with a contract instance. diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/modules/single_key.md b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/modules/single_key.md new file mode 100644 index 000000000000..e376e50fbb03 --- /dev/null +++ b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/modules/single_key.md @@ -0,0 +1,64 @@ +--- +id: "single_key" +title: "Module: single_key" +sidebar_label: "single_key" +sidebar_position: 0 +custom_edit_url: null +--- + +The `@aztec/accounts/single_key` export provides a testing account contract implementation that uses a single Grumpkin key for both authentication and encryption. +It is not recommended to use this account type in production. + +## Classes + +- [SingleKeyAccountContract](../classes/single_key.SingleKeyAccountContract.md) + +## Variables + +### SchnorrSingleKeyAccountContractArtifact + +• `Const` **SchnorrSingleKeyAccountContractArtifact**: `ContractArtifact` + +## Functions + +### getUnsafeSchnorrAccount + +▸ **getUnsafeSchnorrAccount**(`pxe`, `secretKey`, `salt?`): `Promise`\<`AccountManager`\> + +Creates an Account that uses the same Grumpkin key for encryption and authentication. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `pxe` | `PXE` | An PXE server instance. | +| `secretKey` | `Fr` | Secret key used to derive all the keystore keys (in this case also used to get signing key). | +| `salt?` | `Salt` | Deployment salt. | + +#### Returns + +`Promise`\<`AccountManager`\> + +An account manager initialized with the account contract and its deployment params + +___ + +### getUnsafeSchnorrWallet + +▸ **getUnsafeSchnorrWallet**(`pxe`, `address`, `signingPrivateKey`): `Promise`\<`AccountWallet`\> + +Gets a wallet for an already registered account using Schnorr signatures with a single key for encryption and authentication. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `pxe` | `PXE` | An PXE server instance. | +| `address` | `AztecAddress` | Address for the account. | +| `signingPrivateKey` | `Fq` | Grumpkin key used for note encryption and signing transactions. | + +#### Returns + +`Promise`\<`AccountWallet`\> + +A wallet for this account that can be used to interact with a contract instance. diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/modules/testing.md b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/modules/testing.md new file mode 100644 index 000000000000..604fc19f388f --- /dev/null +++ b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/accounts/modules/testing.md @@ -0,0 +1,193 @@ +--- +id: "testing" +title: "Module: testing" +sidebar_label: "testing" +sidebar_position: 0 +custom_edit_url: null +--- + +The `@aztec/accounts/testing` export provides utility methods for testing, in particular in a Sandbox environment. + +Use [getInitialTestAccountsWallets](testing.md#getinitialtestaccountswallets) to obtain a list of wallets for the Sandbox pre-seeded accounts. + +## Interfaces + +- [InitialAccountData](../interfaces/testing.InitialAccountData.md) + +## Variables + +### INITIAL\_TEST\_ACCOUNT\_SALTS + +• `Const` **INITIAL\_TEST\_ACCOUNT\_SALTS**: `Fr`[] + +___ + +### INITIAL\_TEST\_ENCRYPTION\_KEYS + +• `Const` **INITIAL\_TEST\_ENCRYPTION\_KEYS**: `Fq`[] + +___ + +### INITIAL\_TEST\_SECRET\_KEYS + +• `Const` **INITIAL\_TEST\_SECRET\_KEYS**: `Fr`[] + +___ + +### INITIAL\_TEST\_SIGNING\_KEYS + +• `Const` **INITIAL\_TEST\_SIGNING\_KEYS**: `Fq`[] = `INITIAL_TEST_ENCRYPTION_KEYS` + +## Functions + +### deployFundedSchnorrAccount + +▸ **deployFundedSchnorrAccount**(`pxe`, `account`, `opts?`, `waitForProvenOptions?`): `Promise`\<`AccountManager`\> + +Deploy schnorr account contract. +It will pay for the fee for the deployment itself. So it must be funded with the prefilled public data. + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `pxe` | `PXE` | +| `account` | `DeployAccountData` | +| `opts` | `WaitOpts` & \{ `skipClassRegistration?`: `boolean` } | +| `waitForProvenOptions?` | `WaitForProvenOpts` | + +#### Returns + +`Promise`\<`AccountManager`\> + +___ + +### deployFundedSchnorrAccounts + +▸ **deployFundedSchnorrAccounts**(`pxe`, `accounts`, `opts?`, `waitForProvenOptions?`): `Promise`\<`AccountManager`[]\> + +Deploy schnorr account contracts. +They will pay for the fees for the deployment themselves. So they must be funded with the prefilled public data. + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `pxe` | `PXE` | +| `accounts` | `DeployAccountData`[] | +| `opts` | `WaitOpts` & \{ `skipClassRegistration?`: `boolean` } | +| `waitForProvenOptions?` | `WaitForProvenOpts` | + +#### Returns + +`Promise`\<`AccountManager`[]\> + +___ + +### generateSchnorrAccounts + +▸ **generateSchnorrAccounts**(`numberOfAccounts`): `Promise`\<\{ `address`: `AztecAddress` ; `salt`: `Fr` ; `secret`: `Fr` ; `signingKey`: `Fq` }[]\> + +Generate a fixed amount of random schnorr account contract instance. + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `numberOfAccounts` | `number` | + +#### Returns + +`Promise`\<\{ `address`: `AztecAddress` ; `salt`: `Fr` ; `secret`: `Fr` ; `signingKey`: `Fq` }[]\> + +___ + +### getDeployedTestAccounts + +▸ **getDeployedTestAccounts**(`pxe`): `Promise`\<[`InitialAccountData`](../interfaces/testing.InitialAccountData.md)[]\> + +Queries a PXE for it's registered accounts. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `pxe` | `PXE` | PXE instance. | + +#### Returns + +`Promise`\<[`InitialAccountData`](../interfaces/testing.InitialAccountData.md)[]\> + +A set of key data for each of the initial accounts. + +___ + +### getDeployedTestAccountsWallets + +▸ **getDeployedTestAccountsWallets**(`pxe`): `Promise`\<`AccountWalletWithSecretKey`[]\> + +Queries a PXE for it's registered accounts and returns wallets for those accounts using keys in the initial test accounts. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `pxe` | `PXE` | PXE instance. | + +#### Returns + +`Promise`\<`AccountWalletWithSecretKey`[]\> + +A set of AccountWallet implementations for each of the initial accounts. + +___ + +### getInitialTestAccounts + +▸ **getInitialTestAccounts**(): `Promise`\<[`InitialAccountData`](../interfaces/testing.InitialAccountData.md)[]\> + +Gets the basic information for initial test accounts. + +#### Returns + +`Promise`\<[`InitialAccountData`](../interfaces/testing.InitialAccountData.md)[]\> + +___ + +### getInitialTestAccountsManagers + +▸ **getInitialTestAccountsManagers**(`pxe`): `Promise`\<`AccountManager`[]\> + +Gets a collection of account managers for the Aztec accounts that are initially stored in the test environment. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `pxe` | `PXE` | PXE instance. | + +#### Returns + +`Promise`\<`AccountManager`[]\> + +A set of AccountManager implementations for each of the initial accounts. + +___ + +### getInitialTestAccountsWallets + +▸ **getInitialTestAccountsWallets**(`pxe`): `Promise`\<`AccountWalletWithSecretKey`[]\> + +Gets a collection of wallets for the Aztec accounts that are initially stored in the test environment. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `pxe` | `PXE` | PXE instance. | + +#### Returns + +`Promise`\<`AccountWalletWithSecretKey`[]\> + +A set of AccountWallet implementations for each of the initial accounts. diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztec-js/_category_.yml b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/aztec-js/_category_.yml similarity index 100% rename from docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztec-js/_category_.yml rename to docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/aztec-js/_category_.yml diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/aztec-js/index.md b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/aztec-js/index.md new file mode 100644 index 000000000000..2961da2dd54c --- /dev/null +++ b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/aztec-js/index.md @@ -0,0 +1,46 @@ +--- +id: "index" +title: "@aztec/aztec.js" +sidebar_label: "Table of Contents" +sidebar_position: 0.5 +hide_table_of_contents: true +custom_edit_url: null +--- + +The `account` module provides utilities for managing accounts. The AccountManager class +allows to deploy and register a fresh account, or to obtain a `Wallet` instance out of an account +already deployed. Use the `@aztec/accounts` package to load default account implementations that rely +on ECDSA or Schnorr signatures. + +## Interfaces + +- [AccountContract](interfaces/AccountContract.md) +- [AccountInterface](interfaces/AccountInterface.md) + +## Type Aliases + +### Salt + +Ƭ **Salt**: `Fr` \| `number` \| `bigint` + +A contract deployment salt. + +## Functions + +### getAccountContractAddress + +▸ **getAccountContractAddress**(`accountContract`, `secret`, `salt`): `Promise`\<`AztecAddress`\> + +Compute the address of an account contract from secret and salt. + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `accountContract` | [`AccountContract`](interfaces/AccountContract.md) | +| `secret` | `Fr` | +| `salt` | `Fr` | + +#### Returns + +`Promise`\<`AztecAddress`\> diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/aztec-js/interfaces/AccountContract.md b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/aztec-js/interfaces/AccountContract.md new file mode 100644 index 000000000000..8e86c77e9efa --- /dev/null +++ b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/aztec-js/interfaces/AccountContract.md @@ -0,0 +1,75 @@ +--- +id: "AccountContract" +title: "Interface: AccountContract" +sidebar_label: "AccountContract" +sidebar_position: 0 +custom_edit_url: null +--- + +An account contract instance. Knows its artifact, deployment arguments, how to create +transaction execution requests out of function calls, and how to authorize actions. + +## Methods + +### getAuthWitnessProvider + +▸ **getAuthWitnessProvider**(`address`): `AuthWitnessProvider` + +Returns the auth witness provider for the given address. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `address` | `CompleteAddress` | Address for which to create auth witnesses. | + +#### Returns + +`AuthWitnessProvider` + +___ + +### getContractArtifact + +▸ **getContractArtifact**(): `Promise`\<`ContractArtifact`\> + +Returns the artifact of this account contract. + +#### Returns + +`Promise`\<`ContractArtifact`\> + +___ + +### getDeploymentFunctionAndArgs + +▸ **getDeploymentFunctionAndArgs**(): `Promise`\<`undefined` \| \{ `constructorArgs`: `any`[] ; `constructorName`: `string` }\> + +Returns the deployment function name and arguments for this instance, or undefined if this contract does not require deployment. + +#### Returns + +`Promise`\<`undefined` \| \{ `constructorArgs`: `any`[] ; `constructorName`: `string` }\> + +___ + +### getInterface + +▸ **getInterface**(`address`, `nodeInfo`): [`AccountInterface`](AccountInterface.md) + +Returns the account interface for this account contract given a deployment at the provided address. +The account interface is responsible for assembling tx requests given requested function calls, and +for creating signed auth witnesses given action identifiers (message hashes). + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `address` | `CompleteAddress` | Address where this account contract is deployed. | +| `nodeInfo` | `NodeInfo` | Info on the chain where it is deployed. | + +#### Returns + +[`AccountInterface`](AccountInterface.md) + +An account interface instance for creating tx requests and authorizing actions. diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/aztec-js/interfaces/AccountInterface.md b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/aztec-js/interfaces/AccountInterface.md new file mode 100644 index 000000000000..ebf05e9baa9c --- /dev/null +++ b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/aztec-js/interfaces/AccountInterface.md @@ -0,0 +1,116 @@ +--- +id: "AccountInterface" +title: "Interface: AccountInterface" +sidebar_label: "AccountInterface" +sidebar_position: 0 +custom_edit_url: null +--- + +Handler for interfacing with an account. Knows how to create transaction execution +requests and authorize actions for its corresponding account. + +## Hierarchy + +- `EntrypointInterface` + +- `AuthWitnessProvider` + + ↳ **`AccountInterface`** + +## Methods + +### createAuthWit + +▸ **createAuthWit**(`messageHash`): `Promise`\<`AuthWitness`\> + +Computes an authentication witness from either a message hash + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `messageHash` | `Fr` \| `Buffer`\<`ArrayBufferLike`\> | The message hash to approve | + +#### Returns + +`Promise`\<`AuthWitness`\> + +The authentication witness + +#### Inherited from + +AuthWitnessProvider.createAuthWit + +___ + +### createTxExecutionRequest + +▸ **createTxExecutionRequest**(`exec`, `fee`, `options`): `Promise`\<`TxExecutionRequest`\> + +Generates an execution request out of set of function calls. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `exec` | `ExecutionPayload` | The execution intents to be run. | +| `fee` | `FeeOptions` | The fee options for the transaction. | +| `options` | `TxExecutionOptions` | Nonce and whether the transaction is cancellable. | + +#### Returns + +`Promise`\<`TxExecutionRequest`\> + +The authenticated transaction execution request. + +#### Inherited from + +EntrypointInterface.createTxExecutionRequest + +___ + +### getAddress + +▸ **getAddress**(): `AztecAddress` + +Returns the address for this account. + +#### Returns + +`AztecAddress` + +___ + +### getChainId + +▸ **getChainId**(): `Fr` + +Returns the chain id for this account + +#### Returns + +`Fr` + +___ + +### getCompleteAddress + +▸ **getCompleteAddress**(): `CompleteAddress` + +Returns the complete address for this account. + +#### Returns + +`CompleteAddress` + +___ + +### getVersion + +▸ **getVersion**(): `Fr` + +Returns the rollup version for this account + +#### Returns + +`Fr` diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztec-js/interfaces/_category_.yml b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/aztec-js/interfaces/_category_.yml similarity index 100% rename from docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztec-js/interfaces/_category_.yml rename to docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/aztec-js/interfaces/_category_.yml diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/pxe/_category_.yml b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/pxe/_category_.yml similarity index 100% rename from docs/versioned_docs/version-Latest/developers/reference/aztecjs/pxe/_category_.yml rename to docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/pxe/_category_.yml diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/pxe/enums/EventType.md b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/pxe/enums/EventType.md new file mode 100644 index 000000000000..338e46d1034e --- /dev/null +++ b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/pxe/enums/EventType.md @@ -0,0 +1,21 @@ +--- +id: "EventType" +title: "Enumeration: EventType" +sidebar_label: "EventType" +sidebar_position: 0 +custom_edit_url: null +--- + +This is used in getting events via the filter + +## Enumeration Members + +### Encrypted + +• **Encrypted** = ``"Encrypted"`` + +___ + +### Unencrypted + +• **Unencrypted** = ``"Unencrypted"`` diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/pxe/enums/_category_.yml b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/pxe/enums/_category_.yml similarity index 100% rename from docs/versioned_docs/version-Latest/developers/reference/aztecjs/pxe/enums/_category_.yml rename to docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/pxe/enums/_category_.yml diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/pxe/index.md b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/pxe/index.md new file mode 100644 index 000000000000..390faf79398f --- /dev/null +++ b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/pxe/index.md @@ -0,0 +1,38 @@ +--- +id: "index" +title: "@aztec/stdlib" +sidebar_label: "Exports" +sidebar_position: 0.5 +custom_edit_url: null +--- + +## Enumerations + +- [EventType](enums/EventType.md) + +## Interfaces + +- [ContractClassMetadata](interfaces/ContractClassMetadata.md) +- [ContractMetadata](interfaces/ContractMetadata.md) +- [PXE](interfaces/PXE.md) +- [PXEInfo](interfaces/PXEInfo.md) + +## Type Aliases + +### EventMetadataDefinition + +Ƭ **EventMetadataDefinition**: `Object` + +#### Type declaration + +| Name | Type | +| :------ | :------ | +| `abiType` | `AbiType` | +| `eventSelector` | `EventSelector` | +| `fieldNames` | `string`[] | + +## Variables + +### PXESchema + +• `Const` **PXESchema**: `ApiSchemaFor`\<[`PXE`](interfaces/PXE.md)\> diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/pxe/interfaces/ContractClassMetadata.md b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/pxe/interfaces/ContractClassMetadata.md new file mode 100644 index 000000000000..4a152c2a34a9 --- /dev/null +++ b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/pxe/interfaces/ContractClassMetadata.md @@ -0,0 +1,25 @@ +--- +id: "ContractClassMetadata" +title: "Interface: ContractClassMetadata" +sidebar_label: "ContractClassMetadata" +sidebar_position: 0 +custom_edit_url: null +--- + +## Properties + +### artifact + +• `Optional` **artifact**: `ContractArtifact` + +___ + +### contractClass + +• `Optional` **contractClass**: `ContractClassWithId` + +___ + +### isContractClassPubliclyRegistered + +• **isContractClassPubliclyRegistered**: `boolean` diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/pxe/interfaces/ContractMetadata.md b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/pxe/interfaces/ContractMetadata.md new file mode 100644 index 000000000000..7bd09ee675a8 --- /dev/null +++ b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/pxe/interfaces/ContractMetadata.md @@ -0,0 +1,25 @@ +--- +id: "ContractMetadata" +title: "Interface: ContractMetadata" +sidebar_label: "ContractMetadata" +sidebar_position: 0 +custom_edit_url: null +--- + +## Properties + +### contractInstance + +• `Optional` **contractInstance**: `ContractInstanceWithAddress` + +___ + +### isContractInitialized + +• **isContractInitialized**: `boolean` + +___ + +### isContractPubliclyDeployed + +• **isContractPubliclyDeployed**: `boolean` diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/pxe/interfaces/PXE.md b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/pxe/interfaces/PXE.md new file mode 100644 index 000000000000..e40259845337 --- /dev/null +++ b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/pxe/interfaces/PXE.md @@ -0,0 +1,723 @@ +--- +id: "PXE" +title: "Interface: PXE" +sidebar_label: "PXE" +sidebar_position: 0 +custom_edit_url: null +--- + +Private eXecution Environment (PXE) runs locally for each user, providing functionality for all the operations +needed to interact with the Aztec network, including account management, private data management, +transaction local simulation, and access to an Aztec node. This interface, as part of a Wallet, +is exposed to dapps for interacting with the network on behalf of the user. + +## Methods + +### getBlock + +▸ **getBlock**(`number`): `Promise`\<`undefined` \| `L2Block`\> + +Get the given block. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `number` | `number` | The block number being requested. | + +#### Returns + +`Promise`\<`undefined` \| `L2Block`\> + +The blocks requested. + +___ + +### getBlockNumber + +▸ **getBlockNumber**(): `Promise`\<`number`\> + +Fetches the current block number. + +#### Returns + +`Promise`\<`number`\> + +The block number. + +___ + +### getContractClassLogs + +▸ **getContractClassLogs**(`filter`): `Promise`\<`GetContractClassLogsResponse`\> + +Gets contract class logs based on the provided filter. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `filter` | `LogFilter` | The filter to apply to the logs. | + +#### Returns + +`Promise`\<`GetContractClassLogsResponse`\> + +The requested logs. + +___ + +### getContractClassMetadata + +▸ **getContractClassMetadata**(`id`, `includeArtifact?`): `Promise`\<[`ContractClassMetadata`](ContractClassMetadata.md)\> + +Returns the contract class metadata given a contract class id. +The metadata consists of its contract class, whether it has been publicly registered, and its artifact. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `id` | `Fr` | Identifier of the class. | +| `includeArtifact?` | `boolean` | Identifier of the class. | + +#### Returns + +`Promise`\<[`ContractClassMetadata`](ContractClassMetadata.md)\> + +- It returns the contract class metadata, with the artifact field being optional, and will only be returned if true is passed in +for `includeArtifact` +TODO(@spalladino): The PXE actually holds artifacts and not classes, what should we return? Also, +should the pxe query the node for contract public info, and merge it with its own definitions? +TODO(@spalladino): This method is strictly needed to decide whether to publicly register a class or not +during a public deployment. We probably want a nicer and more general API for this, but it'll have to +do for the time being. + +**`Remark`** + +- it queries the node to check whether the contract class with the given id has been publicly registered. + +___ + +### getContractMetadata + +▸ **getContractMetadata**(`address`): `Promise`\<[`ContractMetadata`](ContractMetadata.md)\> + +Returns the contract metadata given an address. +The metadata consists of its contract instance, which includes the contract class identifier, +initialization hash, deployment salt, and public keys hash; whether the contract instance has been initialized; +and whether the contract instance with the given address has been publicly deployed. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `address` | `AztecAddress` | The address that the contract instance resides at. | + +#### Returns + +`Promise`\<[`ContractMetadata`](ContractMetadata.md)\> + +- It returns the contract metadata +TODO(@spalladino): Should we return the public keys in plain as well here? + +**`Remark`** + +- it queries the node to check whether the contract instance has been initialized / publicly deployed through a node. +This query is not dependent on the PXE. + +___ + +### getContracts + +▸ **getContracts**(): `Promise`\<`AztecAddress`[]\> + +Retrieves the addresses of contracts added to this PXE Service. + +#### Returns + +`Promise`\<`AztecAddress`[]\> + +An array of contracts addresses registered on this PXE Service. + +___ + +### getCurrentBaseFees + +▸ **getCurrentBaseFees**(): `Promise`\<`GasFees`\> + +Method to fetch the current base fees. + +#### Returns + +`Promise`\<`GasFees`\> + +The current base fees. + +___ + +### getL1ToL2MembershipWitness + +▸ **getL1ToL2MembershipWitness**(`contractAddress`, `messageHash`, `secret`): `Promise`\<[`bigint`, `SiblingPath`\<``39``\>]\> + +Fetches an L1 to L2 message from the node. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `contractAddress` | `AztecAddress` | Address of a contract by which the message was emitted. | +| `messageHash` | `Fr` | Hash of the message. | +| `secret` | `Fr` | Secret used to compute a nullifier. | + +#### Returns + +`Promise`\<[`bigint`, `SiblingPath`\<``39``\>]\> + +The l1 to l2 membership witness (index of message in the tree and sibling path). + +**`Dev`** + +Contract address and secret are only used to compute the nullifier to get non-nullified messages + +___ + +### getL2ToL1MembershipWitness + +▸ **getL2ToL1MembershipWitness**(`blockNumber`, `l2Tol1Message`): `Promise`\<[`bigint`, `SiblingPath`\<`number`\>]\> + +Gets the membership witness for a message that was emitted at a particular block + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `blockNumber` | `number` | The block number in which to search for the message | +| `l2Tol1Message` | `Fr` | The message to search for | + +#### Returns + +`Promise`\<[`bigint`, `SiblingPath`\<`number`\>]\> + +The membership witness for the message + +___ + +### getNodeInfo + +▸ **getNodeInfo**(): `Promise`\<`NodeInfo`\> + +Returns the information about the server's node. Includes current Node version, compatible Noir version, +L1 chain identifier, rollup version, and L1 address of the rollup contract. + +#### Returns + +`Promise`\<`NodeInfo`\> + +- The node information. + +___ + +### getNotes + +▸ **getNotes**(`filter`): `Promise`\<`UniqueNote`[]\> + +Gets notes registered in this PXE based on the provided filter. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `filter` | `NotesFilter` | The filter to apply to the notes. | + +#### Returns + +`Promise`\<`UniqueNote`[]\> + +The requested notes. + +___ + +### getPXEInfo + +▸ **getPXEInfo**(): `Promise`\<[`PXEInfo`](PXEInfo.md)\> + +Returns information about this PXE. + +#### Returns + +`Promise`\<[`PXEInfo`](PXEInfo.md)\> + +___ + +### getPrivateEvents + +▸ **getPrivateEvents**\<`T`\>(`contractAddress`, `eventMetadata`, `from`, `numBlocks`, `recipients`): `Promise`\<`T`[]\> + +Returns the private events given search parameters. + +#### Type parameters + +| Name | +| :------ | +| `T` | + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `contractAddress` | `AztecAddress` | The address of the contract to get events from. | +| `eventMetadata` | [`EventMetadataDefinition`](../#eventmetadatadefinition) | Metadata of the event. This should be the class generated from the contract. e.g. Contract.events.Event | +| `from` | `number` | The block number to search from. | +| `numBlocks` | `number` | The amount of blocks to search. | +| `recipients` | `AztecAddress`[] | The addresses that decrypted the logs. | + +#### Returns + +`Promise`\<`T`[]\> + +- The deserialized events. + +___ + +### getProvenBlockNumber + +▸ **getProvenBlockNumber**(): `Promise`\<`number`\> + +Fetches the current proven block number. + +#### Returns + +`Promise`\<`number`\> + +The block number. + +___ + +### getPublicEvents + +▸ **getPublicEvents**\<`T`\>(`eventMetadata`, `from`, `limit`): `Promise`\<`T`[]\> + +Returns the public events given search parameters. + +#### Type parameters + +| Name | +| :------ | +| `T` | + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `eventMetadata` | [`EventMetadataDefinition`](../#eventmetadatadefinition) | Metadata of the event. This should be the class generated from the contract. e.g. Contract.events.Event | +| `from` | `number` | The block number to search from. | +| `limit` | `number` | The amount of blocks to search. | + +#### Returns + +`Promise`\<`T`[]\> + +- The deserialized events. + +___ + +### getPublicLogs + +▸ **getPublicLogs**(`filter`): `Promise`\<`GetPublicLogsResponse`\> + +Gets public logs based on the provided filter. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `filter` | `LogFilter` | The filter to apply to the logs. | + +#### Returns + +`Promise`\<`GetPublicLogsResponse`\> + +The requested logs. + +___ + +### getPublicStorageAt + +▸ **getPublicStorageAt**(`contract`, `slot`): `Promise`\<`Fr`\> + +Gets the storage value at the given contract storage slot. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `contract` | `AztecAddress` | Address of the contract to query. | +| `slot` | `Fr` | Slot to query. | + +#### Returns + +`Promise`\<`Fr`\> + +Storage value at the given contract slot. + +**`Remarks`** + +The storage slot here refers to the slot as it is defined in Noir not the index in the merkle tree. +Aztec's version of `eth_getStorageAt`. + +**`Throws`** + +If the contract is not deployed. + +___ + +### getRegisteredAccounts + +▸ **getRegisteredAccounts**(): `Promise`\<`CompleteAddress`[]\> + +Retrieves the user accounts registered on this PXE Service. + +#### Returns + +`Promise`\<`CompleteAddress`[]\> + +An array of the accounts registered on this PXE Service. + +___ + +### getSenders + +▸ **getSenders**(): `Promise`\<`AztecAddress`[]\> + +Retrieves the addresses stored as senders on this PXE Service. + +#### Returns + +`Promise`\<`AztecAddress`[]\> + +An array of the senders on this PXE Service. + +___ + +### getTxEffect + +▸ **getTxEffect**(`txHash`): `Promise`\<`undefined` \| `IndexedTxEffect`\> + +Gets a tx effect. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `txHash` | `TxHash` | The hash of the tx corresponding to the tx effect. | + +#### Returns + +`Promise`\<`undefined` \| `IndexedTxEffect`\> + +The requested tx effect with block info (or undefined if not found). + +___ + +### getTxReceipt + +▸ **getTxReceipt**(`txHash`): `Promise`\<`TxReceipt`\> + +Fetches a transaction receipt for a given transaction hash. Returns a mined receipt if it was added +to the chain, a pending receipt if it's still in the mempool of the connected Aztec node, or a dropped +receipt if not found in the connected Aztec node. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `txHash` | `TxHash` | The transaction hash. | + +#### Returns + +`Promise`\<`TxReceipt`\> + +A receipt of the transaction. + +___ + +### isL1ToL2MessageSynced + +▸ **isL1ToL2MessageSynced**(`l1ToL2Message`): `Promise`\<`boolean`\> + +Returns whether an L1 to L2 message is synced by archiver and if it's ready to be included in a block. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `l1ToL2Message` | `Fr` | The L1 to L2 message to check. | + +#### Returns + +`Promise`\<`boolean`\> + +Whether the message is synced and ready to be included in a block. + +___ + +### profileTx + +▸ **profileTx**(`txRequest`, `profileMode`, `skipProofGeneration?`, `msgSender?`): `Promise`\<`TxProfileResult`\> + +Profiles a transaction, reporting gate counts (unless disabled) and returns an execution trace. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `txRequest` | `TxExecutionRequest` | An authenticated tx request ready for simulation | +| `profileMode` | ``"gates"`` \| ``"execution-steps"`` \| ``"full"`` | - | +| `skipProofGeneration?` | `boolean` | - | +| `msgSender?` | `AztecAddress` | (Optional) The message sender to use for the simulation. | + +#### Returns + +`Promise`\<`TxProfileResult`\> + +A trace of the program execution with gate counts. + +**`Throws`** + +If the code for the functions executed in this transaction have not been made available via `addContracts`. + +___ + +### proveTx + +▸ **proveTx**(`txRequest`, `privateExecutionResult?`): `Promise`\<`TxProvingResult`\> + +Proves the private portion of a simulated transaction, ready to send to the network +(where validators prove the public portion). + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `txRequest` | `TxExecutionRequest` | An authenticated tx request ready for proving | +| `privateExecutionResult?` | `PrivateExecutionResult` | (optional) The result of the private execution of the transaction. The txRequest will be executed if not provided | + +#### Returns + +`Promise`\<`TxProvingResult`\> + +A result containing the proof and public inputs of the tail circuit. + +**`Throws`** + +If contract code not found, or public simulation reverts. +Also throws if simulatePublic is true and public simulation reverts. + +___ + +### registerAccount + +▸ **registerAccount**(`secretKey`, `partialAddress`): `Promise`\<`CompleteAddress`\> + +Registers a user account in PXE given its master encryption private key. +Once a new account is registered, the PXE Service will trial-decrypt all published notes on +the chain and store those that correspond to the registered account. Will do nothing if the +account is already registered. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `secretKey` | `Fr` | Secret key of the corresponding user master public key. | +| `partialAddress` | `Fr` | The partial address of the account contract corresponding to the account being registered. | + +#### Returns + +`Promise`\<`CompleteAddress`\> + +The complete address of the account. + +___ + +### registerContract + +▸ **registerContract**(`contract`): `Promise`\<`void`\> + +Adds deployed contracts to the PXE Service. Deployed contract information is used to access the +contract code when simulating local transactions. This is automatically called by aztec.js when +deploying a contract. Dapps that wish to interact with contracts already deployed should register +these contracts in their users' PXE Service through this method. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `contract` | `Object` | A contract instance to register, with an optional artifact which can be omitted if the contract class has already been registered. | +| `contract.artifact?` | `ContractArtifact` | - | +| `contract.instance` | `ContractInstanceWithAddress` | - | + +#### Returns + +`Promise`\<`void`\> + +___ + +### registerContractClass + +▸ **registerContractClass**(`artifact`): `Promise`\<`void`\> + +Registers a contract class in the PXE without registering any associated contract instance with it. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `artifact` | `ContractArtifact` | The build artifact for the contract class. | + +#### Returns + +`Promise`\<`void`\> + +___ + +### registerSender + +▸ **registerSender**(`address`): `Promise`\<`AztecAddress`\> + +Registers a user contact in PXE. + +Once a new contact is registered, the PXE Service will be able to receive notes tagged from this contact. +Will do nothing if the account is already registered. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `address` | `AztecAddress` | Address of the user to add to the address book | + +#### Returns + +`Promise`\<`AztecAddress`\> + +The address address of the account. + +___ + +### removeSender + +▸ **removeSender**(`address`): `Promise`\<`void`\> + +Removes a sender in the address book. + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `address` | `AztecAddress` | + +#### Returns + +`Promise`\<`void`\> + +___ + +### sendTx + +▸ **sendTx**(`tx`): `Promise`\<`TxHash`\> + +Sends a transaction to an Aztec node to be broadcasted to the network and mined. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `tx` | `Tx` | The transaction as created via `proveTx`. | + +#### Returns + +`Promise`\<`TxHash`\> + +A hash of the transaction, used to identify it. + +___ + +### simulateTx + +▸ **simulateTx**(`txRequest`, `simulatePublic`, `msgSender?`, `skipTxValidation?`, `skipFeeEnforcement?`, `scopes?`): `Promise`\<`TxSimulationResult`\> + +Simulates a transaction based on the provided preauthenticated execution request. +This will run a local simulation of private execution (and optionally of public as well), run the +kernel circuits to ensure adherence to protocol rules (without generating a proof), and return the +simulation results . + +Note that this is used with `ContractFunctionInteraction::simulateTx` to bypass certain checks. +In that case, the transaction returned is only potentially ready to be sent to the network for execution. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `txRequest` | `TxExecutionRequest` | An authenticated tx request ready for simulation | +| `simulatePublic` | `boolean` | Whether to simulate the public part of the transaction. | +| `msgSender?` | `AztecAddress` | (Optional) The message sender to use for the simulation. | +| `skipTxValidation?` | `boolean` | (Optional) If false, this function throws if the transaction is unable to be included in a block at the current state. | +| `skipFeeEnforcement?` | `boolean` | (Optional) If false, fees are enforced. | +| `scopes?` | `AztecAddress`[] | (Optional) The accounts whose notes we can access in this call. Currently optional and will default to all. | + +#### Returns + +`Promise`\<`TxSimulationResult`\> + +A simulated transaction result object that includes public and private return values. + +**`Throws`** + +If the code for the functions executed in this transaction have not been made available via `addContracts`. +Also throws if simulatePublic is true and public simulation reverts. + +___ + +### simulateUtility + +▸ **simulateUtility**(`functionName`, `args`, `to`, `authwits?`, `from?`, `scopes?`): `Promise`\<`UtilitySimulationResult`\> + +Simulate the execution of a contract utility function. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `functionName` | `string` | The name of the utility contract function to be called. | +| `args` | `any`[] | The arguments to be provided to the function. | +| `to` | `AztecAddress` | The address of the contract to be called. | +| `authwits?` | `AuthWitness`[] | (Optional) The authentication witnesses required for the function call. | +| `from?` | `AztecAddress` | (Optional) The msg sender to set for the call. | +| `scopes?` | `AztecAddress`[] | (Optional) The accounts whose notes we can access in this call. Currently optional and will default to all. | + +#### Returns + +`Promise`\<`UtilitySimulationResult`\> + +The result of the utility function call, structured based on the function ABI. + +___ + +### updateContract + +▸ **updateContract**(`contractAddress`, `artifact`): `Promise`\<`void`\> + +Updates a deployed contract in the PXE Service. This is used to update the contract artifact when +an update has happened, so the new code can be used in the simulation of local transactions. +This is called by aztec.js when instantiating a contract in a given address with a mismatching artifact. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `contractAddress` | `AztecAddress` | The address of the contract to update. | +| `artifact` | `ContractArtifact` | The updated artifact for the contract. | + +#### Returns + +`Promise`\<`void`\> diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/pxe/interfaces/PXEInfo.md b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/pxe/interfaces/PXEInfo.md new file mode 100644 index 000000000000..b34b5866adef --- /dev/null +++ b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/pxe/interfaces/PXEInfo.md @@ -0,0 +1,25 @@ +--- +id: "PXEInfo" +title: "Interface: PXEInfo" +sidebar_label: "PXEInfo" +sidebar_position: 0 +custom_edit_url: null +--- + +Provides basic information about the running PXE. + +## Properties + +### protocolContractAddresses + +• **protocolContractAddresses**: `ProtocolContractAddresses` + +Protocol contract addresses + +___ + +### pxeVersion + +• **pxeVersion**: `string` + +Version as tracked in the aztec-packages repository. diff --git a/docs/versioned_docs/version-Latest/developers/reference/aztecjs/pxe/interfaces/_category_.yml b/docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/pxe/interfaces/_category_.yml similarity index 100% rename from docs/versioned_docs/version-Latest/developers/reference/aztecjs/pxe/interfaces/_category_.yml rename to docs/versioned_docs/version-Latest/developers/reference/aztecjs/aztecjs/pxe/interfaces/_category_.yml diff --git a/docs/versioned_docs/version-Latest/developers/reference/considerations/limitations.md b/docs/versioned_docs/version-Latest/developers/reference/considerations/limitations.md index a5f7cc265c49..34728b11c3bf 100644 --- a/docs/versioned_docs/version-Latest/developers/reference/considerations/limitations.md +++ b/docs/versioned_docs/version-Latest/developers/reference/considerations/limitations.md @@ -128,7 +128,7 @@ Due to the rigidity of zk-SNARK circuits, there are upper bounds on the amount o Here are the current constants: -```rust title="constants" showLineNumbers +```rust title="constants" showLineNumbers // "PER CALL" CONSTANTS pub global MAX_NOTE_HASHES_PER_CALL: u32 = 16; pub global MAX_NULLIFIERS_PER_CALL: u32 = 16; @@ -198,7 +198,7 @@ pub global MAX_PRIVATE_LOGS_PER_TX: u32 = 32; pub global MAX_PUBLIC_LOGS_PER_TX: u32 = 8; pub global MAX_CONTRACT_CLASS_LOGS_PER_TX: u32 = 1; ``` -> Source code: noir-projects/noir-protocol-circuits/crates/types/src/constants.nr#L28-L97 +> Source code: noir-projects/noir-protocol-circuits/crates/types/src/constants.nr#L28-L97 #### What are the consequences? diff --git a/docs/versioned_docs/version-Latest/developers/reference/debugging/aztecnr-errors.md b/docs/versioned_docs/version-Latest/developers/reference/debugging/aztecnr-errors.md index f808dd6234f7..e8ff5a3ac5dd 100644 --- a/docs/versioned_docs/version-Latest/developers/reference/debugging/aztecnr-errors.md +++ b/docs/versioned_docs/version-Latest/developers/reference/debugging/aztecnr-errors.md @@ -10,7 +10,7 @@ This section contains some errors that you may encounter when writing and compil All smart contracts written in Aztec.nr need the `aztec` dependency. In your `Nargo.toml` under `[dependencies]`, add this: ```toml -aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/aztec" } +aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/aztec" } ``` You can learn more about dependencies and their paths [here](../smart_contract_reference/dependencies.md). diff --git a/docs/versioned_docs/version-Latest/developers/reference/environment_reference/cheat_codes.md b/docs/versioned_docs/version-Latest/developers/reference/environment_reference/cheat_codes.md index f79fe211ef80..9e1d0b9ac200 100644 --- a/docs/versioned_docs/version-Latest/developers/reference/environment_reference/cheat_codes.md +++ b/docs/versioned_docs/version-Latest/developers/reference/environment_reference/cheat_codes.md @@ -528,7 +528,7 @@ Note: One Field element occupies a storage slot. Hence, structs with multiple fi #### Example -```typescript title="load_private_cheatcode" showLineNumbers +```typescript title="load_private_cheatcode" showLineNumbers const mintAmount = 100n; await mintTokensToPrivate(token, wallet, admin, mintAmount); @@ -546,7 +546,7 @@ const values = notes.map(note => note.items[2]); const balance = values.reduce((sum, current) => sum + current.toBigInt(), 0n); expect(balance).toEqual(mintAmount); ``` -> Source code: yarn-project/end-to-end/src/e2e_cheat_codes.test.ts#L181-L198 +> Source code: yarn-project/end-to-end/src/e2e_cheat_codes.test.ts#L181-L198 ## Participate diff --git a/docs/versioned_docs/version-Latest/developers/reference/environment_reference/cli_wallet_reference.md b/docs/versioned_docs/version-Latest/developers/reference/environment_reference/cli_wallet_reference.md index 08983450b33c..ee5d936a7f02 100644 --- a/docs/versioned_docs/version-Latest/developers/reference/environment_reference/cli_wallet_reference.md +++ b/docs/versioned_docs/version-Latest/developers/reference/environment_reference/cli_wallet_reference.md @@ -119,20 +119,20 @@ In the sandbox pre-loaded test accounts can be used to cover fee juice when depl First import them: -```bash title="import-test-accounts" showLineNumbers +```bash title="import-test-accounts" showLineNumbers aztec-wallet import-test-accounts ``` +> Source code: yarn-project/cli-wallet/test/flows/basic.sh#L9-L11 -> Source code: yarn-project/cli-wallet/test/flows/basic.sh#L9-L11 Then use the alias (test0, test1...) when paying in fee juice. Eg to create accounts: -```bash title="declare-accounts" showLineNumbers +```bash title="declare-accounts" showLineNumbers aztec-wallet create-account -a alice --payment method=fee_juice,feePayer=test0 aztec-wallet create-account -a bob --payment method=fee_juice,feePayer=test0 ``` +> Source code: yarn-project/end-to-end/src/guides/up_quick_start.sh#L21-L24 -> Source code: yarn-project/end-to-end/src/guides/up_quick_start.sh#L21-L24 ### Mint and Bridge Fee Juice @@ -140,12 +140,12 @@ aztec-wallet create-account -a bob --payment method=fee_juice,feePayer=test0 First register an account, mint the fee asset on L1 and bridge it to fee juice: -```bash title="bridge-fee-juice" showLineNumbers +```bash title="bridge-fee-juice" showLineNumbers aztec-wallet create-account -a main --register-only aztec-wallet bridge-fee-juice 1000000000000000000 main --mint --no-wait ``` +> Source code: yarn-project/cli-wallet/test/flows/create_account_pay_native.sh#L8-L11 -> Source code: yarn-project/cli-wallet/test/flows/create_account_pay_native.sh#L8-L11 You'll have to wait for two blocks to pass for bridged fee juice to be ready on Aztec. For the sandbox you do this by putting through two arbitrary transactions. Eg: @@ -160,11 +160,11 @@ aztec-wallet send increment -ca counter --args accounts:test0 accounts:test0 -f Now the funded account can deploy itself with the bridged fees, claiming the bridged fee juice and deploying the contract in one transaction: -```bash title="claim-deploy-account" showLineNumbers +```bash title="claim-deploy-account" showLineNumbers aztec-wallet deploy-account -f main --payment method=fee_juice,claim ``` +> Source code: yarn-project/cli-wallet/test/flows/create_account_pay_native.sh#L25-L27 -> Source code: yarn-project/cli-wallet/test/flows/create_account_pay_native.sh#L25-L27 #### Minting on Testnet diff --git a/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/aztec-nr/uint-note/uint_note.md b/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/aztec-nr/uint-note/uint_note.md index a5f80371527f..bd81a0631104 100644 --- a/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/aztec-nr/uint-note/uint_note.md +++ b/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/aztec-nr/uint-note/uint_note.md @@ -34,10 +34,10 @@ UintNote::get_value(self); ### partial -/ Creates a partial note that will hide the owner and storage slot but not the value, since the note will be later / completed in public. This is a powerful technique for scenarios in which the value cannot be known in private / (e.g. because it depends on some public state, such as a DEX). /// The returned `PartialUintNote` value must be sent to public execution via a secure channel, since it is not / possible to verify the integrity of its contents due to it hiding information. The recommended ways to do this / are to retrieve it from public storage, or to receive it in an internal public function call. /// Each partial note should only be used once, since otherwise multiple notes would be linked together and known to / belong to the same owner. /// As part of the partial note creation process, a log will be sent to `recipient` from `sender` so that they can / discover the note. `recipient` will typically be the same as `owner`. +/ Creates a partial note that will hide the owner and storage slot but not the value, since the note will be later / completed in public. This is a powerful technique for scenarios in which the value cannot be known in private / (e.g. because it depends on some public state, such as a DEX). /// This function inserts a partial note validity commitment into the nullifier tree to be later on able to verify / that the partial note and completer are legitimate. See function docs of `compute_validity_commitment` for more / details. /// Each partial note should only be used once, since otherwise multiple notes would be linked together and known to / belong to the same owner. /// As part of the partial note creation process, a log will be sent to `recipient` from `sender` so that they can / discover the note. `recipient` will typically be the same as `owner`. ```rust -UintNote::partial(owner, storage_slot, context, recipient, sender, ); +UintNote::partial(owner, storage_slot, context, recipient, sender, completer, ); ``` #### Parameters @@ -48,6 +48,7 @@ UintNote::partial(owner, storage_slot, context, recipient, sender, ); | context | &mut PrivateContext | | recipient | AztecAddress | | sender | AztecAddress | +| completer | AztecAddress | | | | # UintPartialNotePrivateContent @@ -90,34 +91,35 @@ UintPartialNotePrivateContent::compute_partial_commitment(self, storage_slot); ## Methods -### compute_validity_commitment +### complete -/ Computes a partial note validity commitment. This commitment is stored in public storage when creating the / partial note in private and then is used to check that completer and note are valid upon partial note / completion in public (completer is the entity that can complete the partial note). +/ Completes the partial note, creating a new note that can be used like any other UintNote. ```rust -PartialUintNote::compute_validity_commitment(self, completer); +PartialUintNote::complete(self, context, completer, value); ``` #### Parameters | Name | Type | | --- | --- | | self | | +| context | &mut PublicContext | | completer | AztecAddress | +| value | u128 | -### complete +### compute_validity_commitment -/ Completes the partial note, creating a new note that can be used like any other UintNote. +/ Computes a validity commitment for this partial note. The commitment cryptographically binds the note's private / data with the designated completer address. When the note is later completed in public execution, we can load / this commitment from the nullifier tree and verify that both the partial note (e.g. that the storage slot / corresponds to the correct owner, and that we're using the correct state variable) and completer are / legitimate. ```rust -PartialUintNote::complete(self, value, context); +PartialUintNote::compute_validity_commitment(self, completer); ``` #### Parameters | Name | Type | | --- | --- | | self | | -| value | u128 | -| context | &mut PublicContext | +| completer | AztecAddress | ### compute_note_completion_log diff --git a/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/dependencies.md b/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/dependencies.md index 6fc99096d512..06b3eaf424b3 100644 --- a/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/dependencies.md +++ b/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/dependencies.md @@ -9,7 +9,7 @@ On this page you will find information about Aztec.nr libraries and up-to-date p ## Aztec ```toml -aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/aztec" } +aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/aztec" } ``` This is the core Aztec library that is required for every Aztec.nr smart contract. @@ -17,7 +17,7 @@ This is the core Aztec library that is required for every Aztec.nr smart contrac ## Authwit ```toml -authwit = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/authwit"} +authwit = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/authwit"} ``` This allows you to use authentication witnesses in your contract. Read a guide of how to use it [here](../../guides/smart_contracts/writing_contracts/authwit.md). @@ -25,7 +25,7 @@ This allows you to use authentication witnesses in your contract. Read a guide o ## Address note ```toml -address_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/address-note" } +address_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/address-note" } ``` This is a library for utilizing notes that hold addresses. Find it on [GitHub](https://github.com/AztecProtocol/aztec-packages/tree/master/noir-projects/aztec-nr/address-note/src). @@ -33,7 +33,7 @@ This is a library for utilizing notes that hold addresses. Find it on [GitHub](h ## Easy private state ```toml -easy_private_state = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/easy-private-state" } +easy_private_state = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/easy-private-state" } ``` This is an abstraction library for using private variables like [`EasyPrivateUint` (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/6c20b45993ee9cbd319ab8351e2722e0c912f427/noir-projects/aztec-nr/easy-private-state/src/easy_private_state.nr#L17). @@ -41,7 +41,7 @@ This is an abstraction library for using private variables like [`EasyPrivateUin ## Protocol Types ```toml -protocol_types = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/noir-protocol-circuits/crates/types"} +protocol_types = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/noir-protocol-circuits/crates/types"} ``` This library contains types that are used in the Aztec protocol. Find it on [GitHub](https://github.com/AztecProtocol/aztec-packages/tree/master/noir-projects/noir-protocol-circuits/crates/types/src). @@ -49,7 +49,7 @@ This library contains types that are used in the Aztec protocol. Find it on [Git ## Value note ```toml -value_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/value-note" } +value_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/value-note" } ``` This is a library for a note that stores one arbitrary value. You can see an example of how it might be used in the [crowdfunding contract codealong tutorial](../../tutorials/codealong/contract_tutorials/crowdfunding_contract.md). diff --git a/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/globals.md b/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/globals.md index 1f4d7a0ccf29..0d71342b4a14 100644 --- a/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/globals.md +++ b/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/globals.md @@ -12,14 +12,14 @@ For developers coming from solidity, this concept will be similar to how the glo ## Private Global Variables -```rust title="tx-context" showLineNumbers +```rust title="tx-context" showLineNumbers pub struct TxContext { pub chain_id: Field, pub version: Field, pub gas_settings: GasSettings, } ``` -> Source code: noir-projects/noir-protocol-circuits/crates/types/src/transaction/tx_context.nr#L8-L14 +> Source code: noir-projects/noir-protocol-circuits/crates/types/src/transaction/tx_context.nr#L8-L14 The private global variables are equal to the transaction context and contain: @@ -46,7 +46,7 @@ The gas limits set by the user for the transaction, the max fee per gas, and the ## Public Global Variables -```rust title="global-variables" showLineNumbers +```rust title="global-variables" showLineNumbers pub struct GlobalVariables { pub chain_id: Field, pub version: Field, @@ -58,7 +58,7 @@ pub struct GlobalVariables { pub gas_fees: GasFees, } ``` -> Source code: noir-projects/noir-protocol-circuits/crates/types/src/abis/global_variables.nr#L9-L20 +> Source code: noir-projects/noir-protocol-circuits/crates/types/src/abis/global_variables.nr#L9-L20 The public global variables contain the values present in the `private global variables` described above, with the addition of: diff --git a/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/portals/data_structures.md b/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/portals/data_structures.md index aa59633d83b3..5e6180bf910c 100644 --- a/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/portals/data_structures.md +++ b/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/portals/data_structures.md @@ -10,7 +10,7 @@ The `DataStructures` are structs that we are using throughout the message infras An entity on L1, specifying the address and the chainId for the entity. Used when specifying sender/recipient with an entity that is on L1. -```solidity title="l1_actor" showLineNumbers +```solidity title="l1_actor" showLineNumbers /** * @notice Actor on L1. * @param actor - The address of the actor @@ -21,7 +21,7 @@ struct L1Actor { uint256 chainId; } ``` -> Source code: l1-contracts/src/core/libraries/DataStructures.sol#L11-L21 +> Source code: l1-contracts/src/core/libraries/DataStructures.sol#L11-L21 | Name | Type | Description | @@ -34,7 +34,7 @@ struct L1Actor { An entity on L2, specifying the address and the version for the entity. Used when specifying sender/recipient with an entity that is on L2. -```solidity title="l2_actor" showLineNumbers +```solidity title="l2_actor" showLineNumbers /** * @notice Actor on L2. * @param actor - The aztec address of the actor @@ -45,7 +45,7 @@ struct L2Actor { uint256 version; } ``` -> Source code: l1-contracts/src/core/libraries/DataStructures.sol#L23-L33 +> Source code: l1-contracts/src/core/libraries/DataStructures.sol#L23-L33 | Name | Type | Description | @@ -57,7 +57,7 @@ struct L2Actor { A message that is sent from L1 to L2. -```solidity title="l1_to_l2_msg" showLineNumbers +```solidity title="l1_to_l2_msg" showLineNumbers /** * @notice Struct containing a message from L1 to L2 * @param sender - The sender of the message @@ -74,7 +74,7 @@ struct L1ToL2Msg { uint256 index; } ``` -> Source code: l1-contracts/src/core/libraries/DataStructures.sol#L35-L51 +> Source code: l1-contracts/src/core/libraries/DataStructures.sol#L35-L51 | Name | Type | Description | @@ -88,7 +88,7 @@ struct L1ToL2Msg { A message that is sent from L2 to L1. -```solidity title="l2_to_l1_msg" showLineNumbers +```solidity title="l2_to_l1_msg" showLineNumbers /** * @notice Struct containing a message from L2 to L1 * @param sender - The sender of the message @@ -102,7 +102,7 @@ struct L2ToL1Msg { bytes32 content; } ``` -> Source code: l1-contracts/src/core/libraries/DataStructures.sol#L53-L66 +> Source code: l1-contracts/src/core/libraries/DataStructures.sol#L53-L66 | Name | Type | Description | diff --git a/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/portals/inbox.md b/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/portals/inbox.md index 72711c4bb8ac..ce29e1021c2d 100644 --- a/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/portals/inbox.md +++ b/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/portals/inbox.md @@ -11,7 +11,7 @@ The `Inbox` is a contract deployed on L1 that handles message passing from L1 to Sends a message from L1 to L2. -```solidity title="send_l1_to_l2_message" showLineNumbers +```solidity title="send_l1_to_l2_message" showLineNumbers /** * @notice Inserts a new message into the Inbox * @dev Emits `MessageSent` with data for easy access by the sequencer @@ -26,7 +26,7 @@ function sendL2Message( bytes32 _secretHash ) external returns (bytes32, uint256); ``` -> Source code: l1-contracts/src/core/interfaces/messagebridge/IInbox.sol#L35-L49 +> Source code: l1-contracts/src/core/interfaces/messagebridge/IInbox.sol#L35-L49 @@ -47,7 +47,7 @@ function sendL2Message( Allows the `Rollup` to consume multiple messages in a single transaction. -```solidity title="consume" showLineNumbers +```solidity title="consume" showLineNumbers /** * @notice Consumes the current tree, and starts a new one if needed * @dev Only callable by the rollup contract @@ -60,13 +60,13 @@ Allows the `Rollup` to consume multiple messages in a single transaction. */ function consume(uint256 _toConsume) external returns (bytes32); ``` -> Source code: l1-contracts/src/core/interfaces/messagebridge/IInbox.sol#L51-L63 +> Source code: l1-contracts/src/core/interfaces/messagebridge/IInbox.sol#L51-L63 | Name | Type | Description | | -------------- | ----------- | -------------------------- | -| ReturnValue | `bytes32` | Root of the consumed tree. | +| ReturnValue | `bytes32` | Root of the consumed tree. | #### Edge cases -- Will revert with `Inbox__Unauthorized()` if `msg.sender != ROLLUP` (rollup contract is sometimes referred to as state transitioner in the docs). +- Will revert with `Inbox__Unauthorized()` if `msg.sender != ROLLUP` (rollup contract is sometimes referred to as state transitioner in the docs). diff --git a/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/portals/outbox.md b/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/portals/outbox.md index cd86fda1835c..ba3ada7021be 100644 --- a/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/portals/outbox.md +++ b/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/portals/outbox.md @@ -11,7 +11,7 @@ The `Outbox` is a contract deployed on L1 that handles message passing from the Inserts the root of a merkle tree containing all of the L2 to L1 messages in a block specified by _l2BlockNumber. -```solidity title="outbox_insert" showLineNumbers +```solidity title="outbox_insert" showLineNumbers /** * @notice Inserts the root of a merkle tree containing all of the L2 to L1 messages in * a block specified by _l2BlockNumber. @@ -23,7 +23,7 @@ Inserts the root of a merkle tree containing all of the L2 to L1 messages in a b */ function insert(uint256 _l2BlockNumber, bytes32 _root, uint256 _minHeight) external; ``` -> Source code: l1-contracts/src/core/interfaces/messagebridge/IOutbox.sol#L22-L33 +> Source code: l1-contracts/src/core/interfaces/messagebridge/IOutbox.sol#L22-L33 @@ -35,7 +35,7 @@ function insert(uint256 _l2BlockNumber, bytes32 _root, uint256 _minHeight) exter #### Edge cases -- Will revert with `Outbox__Unauthorized()` if `msg.sender != ROLLUP_CONTRACT`. +- Will revert with `Outbox__Unauthorized()` if `msg.sender != ROLLUP_CONTRACT`. - Will revert with `Errors.Outbox__RootAlreadySetAtBlock(uint256 l2BlockNumber)` if the root for the specific block has already been set. - Will revert with `Errors.Outbox__InsertingInvalidRoot()` if the rollup is trying to insert bytes32(0) as the root. @@ -43,7 +43,7 @@ function insert(uint256 _l2BlockNumber, bytes32 _root, uint256 _minHeight) exter Allows a recipient to consume a message from the `Outbox`. -```solidity title="outbox_consume" showLineNumbers +```solidity title="outbox_consume" showLineNumbers /** * @notice Consumes an entry from the Outbox * @dev Only useable by portals / recipients of messages @@ -62,7 +62,7 @@ function consume( bytes32[] calldata _path ) external; ``` -> Source code: l1-contracts/src/core/interfaces/messagebridge/IOutbox.sol#L35-L53 +> Source code: l1-contracts/src/core/interfaces/messagebridge/IOutbox.sol#L35-L53 @@ -75,7 +75,7 @@ function consume( #### Edge cases -- Will revert with `Outbox__InvalidRecipient(address expected, address actual);` if `msg.sender != _message.recipient.actor`. +- Will revert with `Outbox__InvalidRecipient(address expected, address actual);` if `msg.sender != _message.recipient.actor`. - Will revert with `Outbox__InvalidChainId()` if `block.chainid != _message.recipient.chainId`. - Will revert with `Outbox__NothingToConsumeAtBlock(uint256 l2BlockNumber)` if the root for the block has not been set yet. - Will revert with `Outbox__AlreadyNullified(uint256 l2BlockNumber, uint256 leafIndex)` if the message at leafIndex for the block has already been consumed. @@ -87,7 +87,7 @@ function consume( Checks to see if an index of the L2 to L1 message tree for a specific block has been consumed. -```solidity title="outbox_has_message_been_consumed_at_block_and_index" showLineNumbers +```solidity title="outbox_has_message_been_consumed_at_block_and_index" showLineNumbers /** * @notice Checks to see if an index of the L2 to L1 message tree for a specific block has been consumed * @dev - This function does not throw. Out-of-bounds access is considered valid, but will always return false @@ -99,7 +99,7 @@ function hasMessageBeenConsumedAtBlockAndIndex(uint256 _l2BlockNumber, uint256 _ view returns (bool); ``` -> Source code: l1-contracts/src/core/interfaces/messagebridge/IOutbox.sol#L55-L66 +> Source code: l1-contracts/src/core/interfaces/messagebridge/IOutbox.sol#L55-L66 diff --git a/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/portals/registry.md b/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/portals/registry.md index e65195116bb3..5bd5b2acc7b5 100644 --- a/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/portals/registry.md +++ b/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/portals/registry.md @@ -11,10 +11,10 @@ The registry is a contract deployed on L1, that contains addresses for the `Roll Retrieves the number of versions that have been deployed. -```solidity title="registry_number_of_versions" showLineNumbers +```solidity title="registry_number_of_versions" showLineNumbers function numberOfVersions() external view returns (uint256); ``` -> Source code: l1-contracts/src/governance/interfaces/IRegistry.sol#L22-L24 +> Source code: l1-contracts/src/governance/interfaces/IRegistry.sol#L22-L24 | Name | Description | @@ -25,10 +25,10 @@ function numberOfVersions() external view returns (uint256); Retrieves the current rollup contract. -```solidity title="registry_get_canonical_rollup" showLineNumbers +```solidity title="registry_get_canonical_rollup" showLineNumbers function getCanonicalRollup() external view returns (IRollup); ``` -> Source code: l1-contracts/src/governance/interfaces/IRegistry.sol#L14-L16 +> Source code: l1-contracts/src/governance/interfaces/IRegistry.sol#L14-L16 | Name | Description | @@ -39,10 +39,10 @@ function getCanonicalRollup() external view returns (IRollup); Retrieves the rollup contract for a specfic version. -```solidity title="registry_get_rollup" showLineNumbers +```solidity title="registry_get_rollup" showLineNumbers function getRollup(uint256 _chainId) external view returns (IRollup); ``` -> Source code: l1-contracts/src/governance/interfaces/IRegistry.sol#L18-L20 +> Source code: l1-contracts/src/governance/interfaces/IRegistry.sol#L18-L20 | Name | Description | diff --git a/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/storage/index.md b/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/storage/index.md index 5ce0efeacaa6..a6cc2ceb2438 100644 --- a/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/storage/index.md +++ b/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/storage/index.md @@ -62,10 +62,10 @@ numbers: Map>, When declaring a public mapping in Storage, we have to specify that the type is public by declaring it as `PublicState` instead of specifying a note type like with private storage above. -```rust title="storage_minters" showLineNumbers +```rust title="storage_minters" showLineNumbers minters: Map, Context>, ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L74-L76 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L74-L76 ### `at` @@ -74,10 +74,10 @@ When dealing with a Map, we can access the value at a given key using the `::at` This function behaves similarly for both private and public maps. An example could be if we have a map with `minters`, which is mapping addresses to a flag for whether they are allowed to mint tokens or not. -```rust title="read_minter" showLineNumbers +```rust title="read_minter" showLineNumbers assert(storage.minters.at(context.msg_sender()).read(), "caller is not minter"); ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L198-L200 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L198-L200 Above, we are specifying that we want to get the storage in the Map `at` the `msg_sender()`, read the value stored and check that `msg_sender()` is indeed a minter. Doing a similar operation in Solidity code would look like: diff --git a/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/storage/private_state.md b/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/storage/private_state.md index 2f68a5b833ed..cce5c6a798ac 100644 --- a/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/storage/private_state.md +++ b/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/storage/private_state.md @@ -34,7 +34,7 @@ Notes are the fundamental elements in the private world. A note has to implement the following traits: -```rust title="note_interfaces" showLineNumbers +```rust title="note_interfaces" showLineNumbers pub trait NoteType { /// Returns the unique identifier for the note type. This is typically used when processing note logs. fn get_id() -> Field; @@ -67,7 +67,7 @@ pub trait NoteHash { unconstrained fn compute_nullifier_unconstrained(self, note_hash_for_nullify: Field) -> Field; } ``` -> Source code: noir-projects/aztec-nr/aztec/src/note/note_interface.nr#L5-L37 +> Source code: noir-projects/aztec-nr/aztec/src/note/note_interface.nr#L5-L37 The interplay between a private state variable and its notes can be confusing. Here's a summary to aid intuition: @@ -107,20 +107,20 @@ Like for public state, we define the struct to have context and a storage slot. An example of `PrivateMutable` usage in the account contracts is keeping track of public keys. The `PrivateMutable` is added to the `Storage` struct as follows: -```rust title="storage-private-mutable-declaration" showLineNumbers +```rust title="storage-private-mutable-declaration" showLineNumbers legendary_card: PrivateMutable, ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L30-L32 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L30-L32 ### `new` As part of the initialization of the `Storage` struct, the `PrivateMutable` is created as follows at the specified storage slot. -```rust title="start_vars_private_mutable" showLineNumbers +```rust title="start_vars_private_mutable" showLineNumbers legendary_card: PrivateMutable::new(context, 3), ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L57-L59 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L57-L59 ### `initialize` @@ -143,15 +143,15 @@ Extend on what happens if you try to use non-initialized state. ### `is_initialized` -An unconstrained method to check whether the PrivateMutable has been initialized or not. It takes an optional owner and returns a boolean. You can view the implementation [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/noir-projects/aztec-nr/aztec/src/state_vars/private_mutable.nr). +An unconstrained method to check whether the PrivateMutable has been initialized or not. It takes an optional owner and returns a boolean. You can view the implementation [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/noir-projects/aztec-nr/aztec/src/state_vars/private_mutable.nr). -```rust title="private_mutable_is_initialized" showLineNumbers +```rust title="private_mutable_is_initialized" showLineNumbers #[utility] unconstrained fn is_legendary_initialized() -> bool { storage.legendary_card.is_initialized() } ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L139-L144 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L139-L144 ### `replace` @@ -160,14 +160,14 @@ To update the value of a `PrivateMutable`, we can use the `replace` method. The An example of this is seen in a example card game, where we create a new note (a `CardNote`) containing some new data, and replace the current note with it: -```rust title="state_vars-PrivateMutableReplace" showLineNumbers +```rust title="state_vars-PrivateMutableReplace" showLineNumbers storage.legendary_card.replace(new_card).emit(encode_and_encrypt_note( &mut context, context.msg_sender(), context.msg_sender(), )); ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L130-L136 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L130-L136 If two people are trying to modify the PrivateMutable at the same time, only one will succeed as we don't allow duplicate nullifiers! Developers should put in place appropriate access controls to avoid race conditions (unless a race is intended!). @@ -176,10 +176,10 @@ If two people are trying to modify the PrivateMutable at the same time, only one This function allows us to get the note of a PrivateMutable, essentially reading the value. -```rust title="state_vars-PrivateMutableGet" showLineNumbers +```rust title="state_vars-PrivateMutableGet" showLineNumbers let card = storage.legendary_card.get_note().note; ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L124-L126 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L124-L126 #### Nullifying Note reads @@ -194,16 +194,16 @@ Functionally similar to [`get_note`](#get_note), but executed in unconstrained f ## `PrivateImmutable` -`PrivateImmutable` (formerly known as `ImmutableSingleton`) represents a unique private state variable that, as the name suggests, is immutable. Once initialized, its value cannot be altered. You can view the implementation [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/noir-projects/aztec-nr/aztec/src/state_vars/private_immutable.nr). +`PrivateImmutable` (formerly known as `ImmutableSingleton`) represents a unique private state variable that, as the name suggests, is immutable. Once initialized, its value cannot be altered. You can view the implementation [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/noir-projects/aztec-nr/aztec/src/state_vars/private_immutable.nr). ### `new` As part of the initialization of the `Storage` struct, the `PrivateMutable` is created as follows, here at storage slot 1. -```rust title="storage-private-immutable-declaration" showLineNumbers +```rust title="storage-private-immutable-declaration" showLineNumbers private_immutable: PrivateImmutable, ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L38-L40 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L38-L40 ### `initialize` @@ -218,7 +218,7 @@ For example, if the storage slot depends on the an address then it is possible t Set the value of an PrivateImmutable by calling the `initialize` method: -```rust title="initialize-private-mutable" showLineNumbers +```rust title="initialize-private-mutable" showLineNumbers #[private] fn initialize_private_immutable(randomness: Field, points: u8) { let new_card = CardNote::new(points, randomness, context.msg_sender()); @@ -230,14 +230,14 @@ fn initialize_private_immutable(randomness: Field, points: u8) { )); } ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L99-L110 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L99-L110 Once initialized, an PrivateImmutable's value remains unchangeable. This method can only be called once. ### `is_initialized` -An unconstrained method to check if the PrivateImmutable has been initialized. Takes an optional owner and returns a boolean. You can find the implementation [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/noir-projects/aztec-nr/aztec/src/state_vars/private_immutable.nr). +An unconstrained method to check if the PrivateImmutable has been initialized. Takes an optional owner and returns a boolean. You can find the implementation [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/noir-projects/aztec-nr/aztec/src/state_vars/private_immutable.nr). ### `get_note` @@ -245,13 +245,13 @@ Similar to the `PrivateMutable`, we can use the `get_note` method to read the va Use this method to retrieve the value of an initialized PrivateImmutable. -```rust title="get_note-private-immutable" showLineNumbers +```rust title="get_note-private-immutable" showLineNumbers #[private] fn get_imm_card() -> CardNote { storage.private_immutable.get_note() } ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L146-L151 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L146-L151 Unlike a `PrivateMutable`, the `get_note` function for an PrivateImmutable doesn't nullify the current note in the background. This means that multiple accounts can concurrently call this function to read the value. @@ -266,14 +266,14 @@ Functionally similar to `get_note`, but executed unconstrained and can be used b `PrivateSet` is used for managing a collection of notes. All notes in a `PrivateSet` are of the same `NoteType`. But whether these notes all belong to one entity, or are accessible and editable by different entities, is up to the developer. The set is a collection of notes inserted into the data-tree, but notes are never removed from the tree itself, they are only nullified. -You can view the implementation [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/noir-projects/aztec-nr/aztec/src/state_vars/private_set.nr). +You can view the implementation [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/noir-projects/aztec-nr/aztec/src/state_vars/private_set.nr). And can be added to the `Storage` struct as follows. Here adding a set for a custom note. -```rust title="storage-set-declaration" showLineNumbers +```rust title="storage-set-declaration" showLineNumbers set: PrivateSet, ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L35-L37 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L35-L37 ### `new` @@ -282,10 +282,10 @@ The `new` method tells the contract how to operate on the underlying storage. We can initialize the set as follows: -```rust title="storage-set-init" showLineNumbers +```rust title="storage-set-init" showLineNumbers set: PrivateSet::new(context, 5), ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L68-L70 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L68-L70 ### `insert` @@ -294,10 +294,10 @@ Allows us to modify the storage by inserting a note into the `PrivateSet`. A hash of the note will be generated, and inserted into the note hash tree, allowing us to later use in contract interactions. Recall that the content of the note should be shared with the owner to allow them to use it, as mentioned this can be done via an encrypted log or offchain via web2, or completely offline. -```rust title="insert" showLineNumbers +```rust title="insert" showLineNumbers self.set.insert(addend_note).emit(encode_and_encrypt_note(self.context, owner, sender)); ``` -> Source code: noir-projects/aztec-nr/easy-private-state/src/easy_private_uint.nr#L36-L38 +> Source code: noir-projects/aztec-nr/easy-private-state/src/easy_private_uint.nr#L36-L38 ### `insert_from_public` @@ -310,17 +310,17 @@ The usage is similar to using the `insert` method with the difference that this This function pops (gets, removes and returns) the notes the account has access to based on the provided filter. -The kernel circuits are constrained to a maximum number of notes this function can return at a time. Check [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/noir-projects/noir-protocol-circuits/crates/types/src/constants.nr) and look for `MAX_NOTE_HASH_READ_REQUESTS_PER_CALL` for the up-to-date number. +The kernel circuits are constrained to a maximum number of notes this function can return at a time. Check [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/noir-projects/noir-protocol-circuits/crates/types/src/constants.nr) and look for `MAX_NOTE_HASH_READ_REQUESTS_PER_CALL` for the up-to-date number. Because of this limit, we should always consider using the second argument `NoteGetterOptions` to limit the number of notes we need to read and constrain in our programs. This is quite important as every extra call increases the time used to prove the program and we don't want to spend more time than necessary. -An example of such options is using the [filter_notes_min_sum (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/noir-projects/aztec-nr/value-note/src/filter.nr) to get "enough" notes to cover a given value. Essentially, this function will return just enough notes to cover the amount specified such that we don't need to read all our notes. For users with a lot of notes, this becomes increasingly important. +An example of such options is using the [filter_notes_min_sum (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/noir-projects/aztec-nr/value-note/src/filter.nr) to get "enough" notes to cover a given value. Essentially, this function will return just enough notes to cover the amount specified such that we don't need to read all our notes. For users with a lot of notes, this becomes increasingly important. -```rust title="pop_notes" showLineNumbers +```rust title="pop_notes" showLineNumbers let options = NoteGetterOptions::with_filter(filter_notes_min_sum, subtrahend as Field); let notes = self.set.pop_notes(options); ``` -> Source code: noir-projects/aztec-nr/easy-private-state/src/easy_private_uint.nr#L43-L46 +> Source code: noir-projects/aztec-nr/easy-private-state/src/easy_private_uint.nr#L43-L46 ### `get_notes` @@ -337,14 +337,14 @@ Note that if you obtained the note you are about to remove via `get_notes` it's Functionally similar to [`get_notes`](#get_notes), but executed unconstrained and can be used by the wallet to fetch notes for use by front-ends etc. -```rust title="view_notes" showLineNumbers +```rust title="view_notes" showLineNumbers let mut options = NoteViewerOptions::new(); let notes = set.view_notes(options.set_offset(offset)); ``` -> Source code: noir-projects/aztec-nr/value-note/src/balance_utils.nr#L15-L18 +> Source code: noir-projects/aztec-nr/value-note/src/balance_utils.nr#L15-L18 -There's also a limit on the maximum number of notes that can be returned in one go. To find the current limit, refer to [this file (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/noir-projects/aztec-nr/aztec/src/note/constants.nr) and look for `MAX_NOTES_PER_PAGE`. +There's also a limit on the maximum number of notes that can be returned in one go. To find the current limit, refer to [this file (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/noir-projects/aztec-nr/aztec/src/note/constants.nr) and look for `MAX_NOTES_PER_PAGE`. The key distinction is that this method is unconstrained. It does not perform a check to verify if the notes actually exist, which is something the [`get_notes`](#get_notes) method does under the hood. Therefore, it should only be used in an unconstrained contract function. @@ -354,7 +354,7 @@ This function requires a `NoteViewerOptions`. The `NoteViewerOptions` is essenti `NoteGetterOptions` encapsulates a set of configurable options for filtering and retrieving a selection of notes from a data oracle. Developers can design instances of `NoteGetterOptions`, to determine how notes should be filtered and returned to the functions of their smart contracts. -You can view the implementation [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/noir-projects/aztec-nr/aztec/src/note/note_getter_options.nr). +You can view the implementation [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/noir-projects/aztec-nr/aztec/src/note/note_getter_options.nr). ### `selects: BoundedVec, N>` @@ -434,7 +434,7 @@ This method sets the status of notes to retrieve (active or nullified). The following code snippet creates an instance of `NoteGetterOptions`, which has been configured to find the cards that belong to an account with nullifying key hash equal to `account_npk_m_hash`. The returned cards are sorted by their points in descending order, and the first `offset` cards with the highest points are skipped. -```rust title="state_vars-NoteGetterOptionsSelectSortOffset" showLineNumbers +```rust title="state_vars-NoteGetterOptionsSelectSortOffset" showLineNumbers pub fn create_npk_card_getter_options( account: AztecAddress, offset: u32, @@ -449,12 +449,12 @@ where .set_offset(offset) } ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/options.nr#L14-L28 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/options.nr#L14-L28 The first value of `.select` and `.sort` indicates the property of the note we're looking for. For this we use helper functions that are autogenerated from the note definition. `CardNote` that has the following fields: -```rust title="state_vars-CardNote" showLineNumbers +```rust title="state_vars-CardNote" showLineNumbers // We derive the Serialize trait because this struct is returned from a contract function. When returned, // the struct is serialized using the Serialize trait and added to a hasher via the `add_to_hasher` utility. // We use a hash rather than the serialized struct itself to keep circuit inputs constant. @@ -466,7 +466,7 @@ pub struct CardNote { owner: AztecAddress, } ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/types/card_note.nr#L3-L14 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/types/card_note.nr#L3-L14 `CardNote::properties()` will return a struct with the values to pass for each field, which are related to their indices inside the `CardNote` struct, internal offset and length. @@ -477,7 +477,7 @@ In the example, `.select(CardNote::properties().npk_m_hash, Comparator.EQ, accou There can be as many conditions as the number of fields a note type has. The following example finds cards whose fields match the three given values: -```rust title="state_vars-NoteGetterOptionsMultiSelects" showLineNumbers +```rust title="state_vars-NoteGetterOptionsMultiSelects" showLineNumbers pub fn create_exact_card_getter_options( points: u8, secret: Field, @@ -493,12 +493,12 @@ where .select(CardNote::properties().owner, Comparator.EQ, account) } ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/options.nr#L30-L45 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/options.nr#L30-L45 While `selects` lets us find notes with specific values, `filter` lets us find notes in a more dynamic way. The function below picks the cards whose points are at least `min_points`, although this now can be done by using the select function with a GTE comparator: -```rust title="state_vars-OptionFilter" showLineNumbers +```rust title="state_vars-OptionFilter" showLineNumbers pub fn filter_min_points( cards: [Option>; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL], min_points: u8, @@ -514,12 +514,12 @@ pub fn filter_min_points( selected_cards } ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/options.nr#L47-L62 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/options.nr#L47-L62 We can use it as a filter to further reduce the number of the final notes: -```rust title="state_vars-NoteGetterOptionsFilter" showLineNumbers +```rust title="state_vars-NoteGetterOptionsFilter" showLineNumbers pub fn create_cards_with_min_points_getter_options( min_points: u8, ) -> NoteGetterOptions @@ -532,14 +532,14 @@ where ) } ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/options.nr#L64-L76 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/options.nr#L64-L76 One thing to remember is, `filter` will be applied on the notes after they are picked from the database, so it is more efficient to use select with comparators where possible. Another side effect of this is that it's possible that the actual notes we end up getting are fewer than the limit. The limit is `MAX_NOTE_HASH_READ_REQUESTS_PER_CALL` by default. But we can set it to any value **smaller** than that: -```rust title="state_vars-NoteGetterOptionsPickOne" showLineNumbers +```rust title="state_vars-NoteGetterOptionsPickOne" showLineNumbers pub fn create_largest_card_getter_options() -> NoteGetterOptions where CardNote: Packable, @@ -548,27 +548,27 @@ where options.sort(CardNote::properties().points, SortOrder.DESC).set_limit(1) } ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/options.nr#L78-L86 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/options.nr#L78-L86 #### Example 2 An example of how we can use a Comparator to select notes when calling a Noir contract from aztec.js is below. -```typescript title="state_vars-NoteGetterOptionsComparatorExampleTs" showLineNumbers +```typescript title="state_vars-NoteGetterOptionsComparatorExampleTs" showLineNumbers contract.methods.read_note_values(Comparator.GTE, 5).simulate(), ``` -> Source code: yarn-project/end-to-end/src/e2e_note_getter.test.ts#L49-L51 +> Source code: yarn-project/end-to-end/src/e2e_note_getter.test.ts#L49-L51 In this example, we use the above typescript code to invoke a call to our Noir contract below. This Noir contract function takes an input to match with, and a comparator to use when fetching and selecting notes from storage. -```rust title="state_vars-NoteGetterOptionsComparatorExampleNoir" showLineNumbers +```rust title="state_vars-NoteGetterOptionsComparatorExampleNoir" showLineNumbers #[utility] unconstrained fn read_note(comparator: u8, amount: Field) -> BoundedVec { let mut options = NoteViewerOptions::new(); storage.set.view_notes(options.select(CardNote::properties().points, comparator, amount)) } ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L112-L118 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L112-L118 diff --git a/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/storage/public_state.md b/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/storage/public_state.md index 13990a13580d..830c354240c5 100644 --- a/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/storage/public_state.md +++ b/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/storage/public_state.md @@ -10,7 +10,7 @@ For a higher level overview of the state model in Aztec, see the [state model]( The `PublicMutable` (formerly known as `PublicState`) struct is generic over the variable type `T`. The type _must_ implement Serialize and Deserialize traits, as specified here: -```rust title="serialize" showLineNumbers +```rust title="serialize" showLineNumbers /// Trait for serializing Noir types into arrays of Fields. /// /// An implementation of the Serialize trait has to follow Noir's intrinsic serialization (each member of a struct @@ -46,9 +46,9 @@ pub trait Serialize { fn serialize(self) -> [Field; N]; } ``` -> Source code: noir-projects/noir-protocol-circuits/crates/types/src/traits.nr#L195-L230 +> Source code: noir-projects/noir-protocol-circuits/crates/types/src/traits.nr#L195-L230 -```rust title="deserialize" showLineNumbers +```rust title="deserialize" showLineNumbers /// Trait for deserializing Noir types from arrays of Fields. /// /// An implementation of the Deserialize trait has to follow Noir's intrinsic serialization (each member of a struct @@ -72,41 +72,41 @@ pub trait Deserialize { fn deserialize(fields: [Field; N]) -> Self; } ``` -> Source code: noir-projects/noir-protocol-circuits/crates/types/src/traits.nr#L301-L324 +> Source code: noir-projects/noir-protocol-circuits/crates/types/src/traits.nr#L301-L324 The struct contains a `storage_slot` which, similar to Ethereum, is used to figure out _where_ in storage the variable is located. Notice that while we don't have the exact same state model as EVM chains it will look similar from the contract developers point of view. -You can find the details of `PublicMutable` in the implementation [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/noir-projects/aztec-nr/aztec/src/state_vars/public_mutable.nr). +You can find the details of `PublicMutable` in the implementation [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/noir-projects/aztec-nr/aztec/src/state_vars/public_mutable.nr). For a version of `PublicMutable` that can also be read in private, head to [`SharedMutable`](./shared_state.md#sharedmutable). :::info -An example using a larger struct can be found in the [lending example (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/master/noir-projects/noir-contracts/contracts/app/lending_contract)'s use of an [`Asset` (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.3/noir-projects/noir-contracts/contracts/app/lending_contract/src/asset.nr). +An example using a larger struct can be found in the [lending example (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/master/noir-projects/noir-contracts/contracts/app/lending_contract)'s use of an [`Asset` (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.4/noir-projects/noir-contracts/contracts/app/lending_contract/src/asset.nr). ::: ### `new` -When declaring the storage for `T` as a persistent public storage variable, we use the `PublicMutable::new()` constructor. As seen below, this takes the `storage_slot` and the `serialization_methods` as arguments along with the `Context`, which in this case is used to share interface with other structures. You can view the implementation [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/noir-projects/aztec-nr/aztec/src/state_vars/public_mutable.nr). +When declaring the storage for `T` as a persistent public storage variable, we use the `PublicMutable::new()` constructor. As seen below, this takes the `storage_slot` and the `serialization_methods` as arguments along with the `Context`, which in this case is used to share interface with other structures. You can view the implementation [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/noir-projects/aztec-nr/aztec/src/state_vars/public_mutable.nr). #### Single value example Say that we wish to add `admin` public state variable into our storage struct. In the struct we can define it as: -```rust title="storage-leader-declaration" showLineNumbers +```rust title="storage-leader-declaration" showLineNumbers leader: PublicMutable, ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L27-L29 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L27-L29 #### Mapping example Say we want to have a group of `minters` that are able to mint assets in our contract, and we want them in public storage, because access control in private is quite cumbersome. In the `Storage` struct we can add it as follows: -```rust title="storage-minters-declaration" showLineNumbers +```rust title="storage-minters-declaration" showLineNumbers minters: Map, Context>, ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L44-L46 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L44-L46 ### `read` @@ -117,20 +117,20 @@ On the `PublicMutable` structs we have a `read` method to read the value at the For our `admin` example from earlier, this could be used as follows to check that the stored value matches the `msg_sender()`. -```rust title="read_admin" showLineNumbers +```rust title="read_admin" showLineNumbers assert(storage.admin.read().eq(context.msg_sender()), "caller is not admin"); ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L186-L188 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L186-L188 #### Reading from our `minters` example As we saw in the Map earlier, a very similar operation can be done to perform a lookup in a map. -```rust title="read_minter" showLineNumbers +```rust title="read_minter" showLineNumbers assert(storage.minters.at(context.msg_sender()).read(), "caller is not minter"); ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L198-L200 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L198-L200 ### `write` @@ -139,18 +139,18 @@ We have a `write` method on the `PublicMutable` struct that takes the value to w #### Writing to our `admin` example -```rust title="write_admin" showLineNumbers +```rust title="write_admin" showLineNumbers storage.admin.write(new_admin); ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L109-L111 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L109-L111 #### Writing to our `minters` example -```rust title="write_minter" showLineNumbers +```rust title="write_minter" showLineNumbers storage.minters.at(minter).write(approve); ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L189-L191 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L189-L191 --- @@ -161,55 +161,55 @@ storage.minters.at(minter).write(approve); Just like the `PublicMutable` it is generic over the variable type `T`. The type `MUST` implement the `Serialize` and `Deserialize` traits. -```rust title="storage-public-immutable-declaration" showLineNumbers +```rust title="storage-public-immutable-declaration" showLineNumbers public_immutable: PublicImmutable, ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L41-L43 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L41-L43 -You can find the details of `PublicImmutable` in the implementation [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/noir-projects/aztec-nr/aztec/src/state_vars/public_immutable.nr). +You can find the details of `PublicImmutable` in the implementation [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/noir-projects/aztec-nr/aztec/src/state_vars/public_immutable.nr). ### `new` Is done exactly like the `PublicMutable` struct, but with the `PublicImmutable` struct. -```rust title="storage-public-immutable-declaration" showLineNumbers +```rust title="storage-public-immutable-declaration" showLineNumbers public_immutable: PublicImmutable, ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L41-L43 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L41-L43 ### `initialize` This function sets the immutable value. It can only be called once. -```rust title="initialize_decimals" showLineNumbers +```rust title="initialize_decimals" showLineNumbers storage.decimals.initialize(decimals); ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L99-L101 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L99-L101 :::warning A `PublicImmutable`'s storage **must** only be set once via `initialize`. Attempting to override this by manually accessing the underlying storage slots breaks all properties of the data structure, rendering it useless. ::: -```rust title="initialize_public_immutable" showLineNumbers +```rust title="initialize_public_immutable" showLineNumbers #[public] fn initialize_public_immutable(points: u8) { let mut new_leader = Leader { account: context.msg_sender(), points }; storage.public_immutable.initialize(new_leader); ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L84-L89 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L84-L89 ### `read` Returns the stored immutable value. This function is available in public, private and utility contexts. -```rust title="read_public_immutable" showLineNumbers +```rust title="read_public_immutable" showLineNumbers #[utility] unconstrained fn get_public_immutable() -> Leader { storage.public_immutable.read() ``` -> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L92-L96 +> Source code: noir-projects/noir-contracts/contracts/docs/docs_example_contract/src/main.nr#L92-L96 diff --git a/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/storage/shared_state.md b/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/storage/shared_state.md index 758fa6ad4cab..8959203c6254 100644 --- a/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/storage/shared_state.md +++ b/docs/versioned_docs/version-Latest/developers/reference/smart_contract_reference/storage/shared_state.md @@ -54,14 +54,14 @@ This prevents the network-wide privacy set from being split between transactions ## `SharedMutable` -`SharedMutable` is a shared state variable for mutable state. It provides capabilities to read the same state both in private and public, and to schedule value changes after a delay. You can view the implementation [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/noir-projects/aztec-nr/aztec/src/state_vars/shared_mutable/shared_mutable.nr). +`SharedMutable` is a shared state variable for mutable state. It provides capabilities to read the same state both in private and public, and to schedule value changes after a delay. You can view the implementation [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/noir-projects/aztec-nr/aztec/src/state_vars/shared_mutable/shared_mutable.nr). Unlike other state variables, `SharedMutable` receives not only a type parameter for the underlying datatype, but also a `DELAY` type parameter with the value change delay as a number of blocks. -```rust title="shared_mutable_storage" showLineNumbers +```rust title="shared_mutable_storage" showLineNumbers authorized: SharedMutable, ``` -> Source code: noir-projects/noir-contracts/contracts/app/auth_contract/src/main.nr#L22-L24 +> Source code: noir-projects/noir-contracts/contracts/app/auth_contract/src/main.nr#L22-L24 :::note @@ -76,13 +76,13 @@ This is the means by which a `SharedMutable` variable mutates its contents. It s This function can only be called in public, typically after some access control check: -```rust title="shared_mutable_schedule" showLineNumbers +```rust title="shared_mutable_schedule" showLineNumbers #[public] fn set_authorized(authorized: AztecAddress) { assert_eq(storage.admin.read(), context.msg_sender(), "caller is not admin"); storage.authorized.schedule_value_change(authorized); ``` -> Source code: noir-projects/noir-contracts/contracts/app/auth_contract/src/main.nr#L34-L39 +> Source code: noir-projects/noir-contracts/contracts/app/auth_contract/src/main.nr#L34-L39 If one wishes to schedule a value change from private, simply enqueue a public call to a public `internal` contract function. Recall that **all scheduled value changes, including the new value and scheduled block are public**. @@ -95,31 +95,31 @@ A `SharedMutable`'s storage **must** only be mutated via `schedule_value_change` Returns the current value in a public, private or utility execution context. Once a value change is scheduled via `schedule_value_change` and a number of blocks equal to the delay passes, this automatically returns the new value. -```rust title="shared_mutable_get_current_public" showLineNumbers +```rust title="shared_mutable_get_current_public" showLineNumbers storage.authorized.get_current_value() ``` -> Source code: noir-projects/noir-contracts/contracts/app/auth_contract/src/main.nr#L46-L48 +> Source code: noir-projects/noir-contracts/contracts/app/auth_contract/src/main.nr#L46-L48 Calling this function in a private execution context will have a 1 block delay, as compared to calling in the public context. This is because calling `get_current_value` in private constructs a historical state proof, using the latest proven block, for the public value, so the "current value" in private execution will be delayed by 1 block when compared to what the public value is. Also, calling in private will set the `max_block_number` property of the transaction request, introducing a new validity condition to the entire transaction: it cannot be included in any block with a block number larger than `max_block_number`. This could [potentially leak some privacy](#privacy-considerations). -```rust title="shared_mutable_get_current_private" showLineNumbers +```rust title="shared_mutable_get_current_private" showLineNumbers let authorized = storage.authorized.get_current_value(); ``` -> Source code: noir-projects/noir-contracts/contracts/app/auth_contract/src/main.nr#L78-L80 +> Source code: noir-projects/noir-contracts/contracts/app/auth_contract/src/main.nr#L78-L80 ### `get_scheduled_value` Returns the last scheduled value change, along with the block number at which the scheduled value becomes the current value. This may either be a pending change, if the block number is in the future, or the last executed scheduled change if the block number is in the past (in which case there are no pending changes). -```rust title="shared_mutable_get_scheduled_public" showLineNumbers +```rust title="shared_mutable_get_scheduled_public" showLineNumbers let (scheduled_value, _block_of_change): (AztecAddress, u32) = storage.authorized.get_scheduled_value(); ``` -> Source code: noir-projects/noir-contracts/contracts/app/auth_contract/src/main.nr#L55-L58 +> Source code: noir-projects/noir-contracts/contracts/app/auth_contract/src/main.nr#L55-L58 It is not possible to call this function in private: doing so would not be very useful at it cannot be asserted that a scheduled value change will not be immediately replaced if `shcedule_value_change` where to be called. diff --git a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/contract_tutorials/counter_contract.md b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/contract_tutorials/counter_contract.md index dbd54a9d8766..09c2664e0745 100644 --- a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/contract_tutorials/counter_contract.md +++ b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/contract_tutorials/counter_contract.md @@ -7,7 +7,7 @@ import Image from "@theme/IdealImage"; In this guide, we will create our first Aztec.nr smart contract. We will build a simple private counter, where you can keep your own private counter - so no one knows what ID you are at or when you increment! This contract will get you started with the basic setup and syntax of Aztec.nr, but doesn't showcase all of the awesome stuff Aztec is capable of. -This tutorial is compatible with the Aztec version `v0.87.3`. Install the correct version with `aztec-up -v 0.87.3`. Or if you'd like to use a different version, you can find the relevant tutorial by clicking the version dropdown at the top of the page. +This tutorial is compatible with the Aztec version `v0.87.4`. Install the correct version with `aztec-up -v 0.87.4`. Or if you'd like to use a different version, you can find the relevant tutorial by clicking the version dropdown at the top of the page. ## Prerequisites @@ -39,9 +39,9 @@ Add the following dependencies to `Nargo.toml` under the autogenerated content: ```toml [dependencies] -aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/aztec" } -value_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/value-note"} -easy_private_state = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/easy-private-state"} +aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/aztec" } +value_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/value-note"} +easy_private_state = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/easy-private-state"} ``` ## Define the functions @@ -70,7 +70,7 @@ pub contract Counter { } ``` -```rust title="imports" showLineNumbers +```rust title="imports" showLineNumbers use aztec::macros::{functions::{initializer, private, public, utility}, storage::storage}; use aztec::prelude::{AztecAddress, Map}; use aztec::protocol_types::{ @@ -80,7 +80,7 @@ use aztec::protocol_types::{ use easy_private_state::EasyPrivateUint; use value_note::{balance_utils, value_note::ValueNote}; ``` -> Source code: noir-projects/noir-contracts/contracts/test/counter_contract/src/main.nr#L8-L17 +> Source code: noir-projects/noir-contracts/contracts/test/counter_contract/src/main.nr#L8-L17 - `use aztec::macros::{functions::{initializer, private, utility}, storage::storage};` @@ -102,13 +102,13 @@ use value_note::{balance_utils, value_note::ValueNote}; Add this below the imports. It declares the storage variables for our contract. We are going to store a mapping of values for each `AztecAddress`. -```rust title="storage_struct" showLineNumbers +```rust title="storage_struct" showLineNumbers #[storage] struct Storage { counters: Map, Context>, } ``` -> Source code: noir-projects/noir-contracts/contracts/test/counter_contract/src/main.nr#L19-L24 +> Source code: noir-projects/noir-contracts/contracts/test/counter_contract/src/main.nr#L19-L24 ## Keep the counter private @@ -117,7 +117,7 @@ Now we’ve got a mechanism for storing our private state, we can start using it Let’s create a constructor method to run on deployment that assigns an initial count to a specified owner. This function is called `initialize`, but behaves like a constructor. It is the `#[initializer]` decorator that specifies that this function behaves like a constructor. Write this: -```rust title="constructor" showLineNumbers +```rust title="constructor" showLineNumbers #[initializer] #[private] // We can name our initializer anything we want as long as it's marked as aztec(initializer) @@ -126,7 +126,7 @@ fn initialize(headstart: u64, owner: AztecAddress) { counters.at(owner).add(headstart, owner, context.msg_sender()); } ``` -> Source code: noir-projects/noir-contracts/contracts/test/counter_contract/src/main.nr#L26-L34 +> Source code: noir-projects/noir-contracts/contracts/test/counter_contract/src/main.nr#L26-L34 This function accesses the counts from storage. Then it assigns the passed initial counter to the `owner`'s counter privately using `at().add()`. @@ -137,7 +137,7 @@ We have annotated this and other functions with `#[private]` which are ABI macro Now let’s implement the `increment` function we defined in the first step. -```rust title="increment" showLineNumbers +```rust title="increment" showLineNumbers #[private] fn increment(owner: AztecAddress, sender: AztecAddress) { unsafe { @@ -153,7 +153,7 @@ fn increment(owner: AztecAddress, sender: AztecAddress) { counters.at(owner).add(1, owner, sender); } ``` -> Source code: noir-projects/noir-contracts/contracts/test/counter_contract/src/main.nr#L36-L51 +> Source code: noir-projects/noir-contracts/contracts/test/counter_contract/src/main.nr#L36-L51 The `increment` function works very similarly to the `constructor`, but instead directly adds 1 to the counter rather than passing in an initial count parameter. @@ -166,7 +166,7 @@ Because our counters are private, the network can't directly verify if a note wa The last thing we need to implement is the function in order to retrieve a counter. In the `getCounter` we defined in the first step, write this: -```rust title="get_counter" showLineNumbers +```rust title="get_counter" showLineNumbers #[utility] unconstrained fn get_counter(owner: AztecAddress) -> Field { let counters = storage.counters; @@ -198,7 +198,7 @@ fn emit_in_public(n: Field) { context.push_note_hash(n); } ``` -> Source code: noir-projects/noir-contracts/contracts/test/counter_contract/src/main.nr#L91-L123 +> Source code: noir-projects/noir-contracts/contracts/test/counter_contract/src/main.nr#L91-L123 This is a `utility` function which is used to obtain the counter information outside of a transaction. We retrieve a reference to the `owner`'s `counter` from the `counters` Map. The `get_balance` function then operates on the owner's counter. This yields a private counter that only the private key owner can decrypt. diff --git a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/contract_tutorials/crowdfunding_contract.md b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/contract_tutorials/crowdfunding_contract.md index 07e4d6b828da..681f95c3bdd6 100644 --- a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/contract_tutorials/crowdfunding_contract.md +++ b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/contract_tutorials/crowdfunding_contract.md @@ -22,7 +22,7 @@ Along the way you will: - Wrap an address with its interface (token) - Create custom private value notes -This tutorial is compatible with the Aztec version `v0.87.3`. Install the correct version with `aztec-up -v 0.87.3`. Or if you'd like to use a different version, you can find the relevant tutorial by clicking the version dropdown at the top of the page. +This tutorial is compatible with the Aztec version `v0.87.4`. Install the correct version with `aztec-up -v 0.87.4`. Or if you'd like to use a different version, you can find the relevant tutorial by clicking the version dropdown at the top of the page. ## Setup @@ -102,9 +102,9 @@ Add the required dependency by going to your project's `Nargo.toml` file, and ad ```rust [dependencies] -aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/aztec" } -uint_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/uint-note" } -router = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/noir-contracts/contracts/protocol/router_contract" } +aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/aztec" } +uint_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/uint-note" } +router = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/noir-contracts/contracts/protocol/router_contract" } ``` This snippet also imports some of the other dependencies we will be using. @@ -120,11 +120,11 @@ Inside the Crowdfunding contract definition, use the dependency that defines the use dep::aztec::protocol_types::address::AztecAddress; ``` -The `aztec::protocol_types` can be browsed [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/noir-projects/noir-protocol-circuits/crates/types/src). And like rust dependencies, the relative path inside the dependency corresponds to `address::AztecAddress`. +The `aztec::protocol_types` can be browsed [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/noir-projects/noir-protocol-circuits/crates/types/src). And like rust dependencies, the relative path inside the dependency corresponds to `address::AztecAddress`. This contract uses another file called `config.nr`. Create this in the same directory as `main.nr` and paste this in: -```rust title="config.nr" showLineNumbers +```rust title="config.nr" showLineNumbers use dep::aztec::protocol_types::{address::AztecAddress, traits::Packable}; use std::meta::derive; @@ -137,14 +137,14 @@ pub struct Config { pub deadline: u64, // End of the crowdfunding campaign after which no more donations are accepted } ``` -> Source code: noir-projects/noir-contracts/contracts/app/crowdfunding_contract/src/config.nr#L1-L13 +> Source code: noir-projects/noir-contracts/contracts/app/crowdfunding_contract/src/config.nr#L1-L13 #### Storage To retain the initializer parameters in the contract's Storage, we'll need to declare them in a preceding `Storage` struct in our `main.nr`: -```rust title="storage" showLineNumbers +```rust title="storage" showLineNumbers #[storage] struct Storage { config: PublicImmutable, @@ -152,19 +152,19 @@ struct Storage { donation_receipts: PrivateSet, } ``` -> Source code: noir-projects/noir-contracts/contracts/app/crowdfunding_contract/src/main.nr#L38-L45 +> Source code: noir-projects/noir-contracts/contracts/app/crowdfunding_contract/src/main.nr#L38-L45 Now complete the initializer by setting the storage variables with the parameters: -```rust title="init" showLineNumbers +```rust title="init" showLineNumbers #[public] #[initializer] fn init(donation_token: AztecAddress, operator: AztecAddress, deadline: u64) { storage.config.initialize(Config { donation_token, operator, deadline }); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/crowdfunding_contract/src/main.nr#L48-L59 +> Source code: noir-projects/noir-contracts/contracts/app/crowdfunding_contract/src/main.nr#L48-L59 ### 2. Taking private donations @@ -175,10 +175,10 @@ To check that the donation occurs before the campaign deadline, we must access t We read the deadline from public storage in private and use the router contract to assert that the current `timestamp` is before the deadline. -```rust title="call-check-deadline" showLineNumbers +```rust title="call-check-deadline" showLineNumbers privately_check_timestamp(Comparator.LT, config.deadline, &mut context); ``` -> Source code: noir-projects/noir-contracts/contracts/app/crowdfunding_contract/src/main.nr#L68-L70 +> Source code: noir-projects/noir-contracts/contracts/app/crowdfunding_contract/src/main.nr#L68-L70 We perform this check via the router contract to not reveal which contract is performing the check - this is achieved by calling a private function on the router contract which then enqueues a call to a public function on the router contract. The result is that `msg_sender` in the public call will then be the router contract. @@ -187,7 +187,7 @@ If it's unique to this contract, then there'll be a privacy leak regardless, as Now conclude adding all dependencies to the `Crowdfunding` contract: -```rust title="all-deps" showLineNumbers +```rust title="all-deps" showLineNumbers use crate::config::Config; use dep::aztec::{ event::event_interface::EventInterface, @@ -207,10 +207,10 @@ use router::utils::privately_check_timestamp; use std::meta::derive; use token::Token; ``` -> Source code: noir-projects/noir-contracts/contracts/app/crowdfunding_contract/src/main.nr#L9-L28 +> Source code: noir-projects/noir-contracts/contracts/app/crowdfunding_contract/src/main.nr#L9-L28 -Like before, you can find these and other `aztec::protocol_types` [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/noir-projects/noir-protocol-circuits/crates/types/src). +Like before, you can find these and other `aztec::protocol_types` [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/noir-projects/noir-protocol-circuits/crates/types/src). #### Interfacing with another contract @@ -219,7 +219,7 @@ The token being used for donations is stored simply as an `AztecAddress` (named Add this `Token` contract to Nargo.toml: ``` -token = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/noir-contracts/contracts/app/token_contract" } +token = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/noir-contracts/contracts/app/token_contract" } ``` With the dependency already `use`d at the start of the contract, the token contract can be called to make the transfer from msg sender to this contract. @@ -228,7 +228,7 @@ With the dependency already `use`d at the start of the contract, the token contr The last thing to do is create a new value note and add it to the `donation_receipts`. So the full donation function is now -```rust title="donate" showLineNumbers +```rust title="donate" showLineNumbers #[private] fn donate(amount: u128) { let config = storage.config.read(); @@ -254,7 +254,7 @@ fn donate(amount: u128) { )); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/crowdfunding_contract/src/main.nr#L61-L90 +> Source code: noir-projects/noir-contracts/contracts/app/crowdfunding_contract/src/main.nr#L61-L90 ### 3. Operator withdrawals @@ -269,7 +269,7 @@ The last point is achieved by emitting an unencrypted event log. Copy the last function into your Crowdfunding contract: -```rust title="operator-withdrawals" showLineNumbers +```rust title="operator-withdrawals" showLineNumbers // Withdraws balance to the operator. Requires that msg_sender() is the operator. #[private] fn withdraw(amount: u128) { @@ -293,12 +293,12 @@ fn _publish_donation_receipts(amount: u128, to: AztecAddress) { WithdrawalProcessed { amount, who: to }.emit(encode_event(&mut context)); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/crowdfunding_contract/src/main.nr#L92-L115 +> Source code: noir-projects/noir-contracts/contracts/app/crowdfunding_contract/src/main.nr#L92-L115 This is emitting an event, which we will need to create. Paste this earlier in our contract after our `Storage` declaration: -```rust title="withdrawal-processed-event" showLineNumbers +```rust title="withdrawal-processed-event" showLineNumbers #[derive(Serialize)] #[event] struct WithdrawalProcessed { @@ -306,7 +306,7 @@ struct WithdrawalProcessed { amount: u128, } ``` -> Source code: noir-projects/noir-contracts/contracts/app/crowdfunding_contract/src/main.nr#L30-L37 +> Source code: noir-projects/noir-contracts/contracts/app/crowdfunding_contract/src/main.nr#L30-L37 You should be able to compile successfully with `aztec-nargo compile`. @@ -315,10 +315,10 @@ You should be able to compile successfully with `aztec-nargo compile`. ## Conclusion -For comparison, the full Crowdfunding contract can be found [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/noir-projects/noir-contracts/contracts/app/crowdfunding_contract). +For comparison, the full Crowdfunding contract can be found [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/noir-projects/noir-contracts/contracts/app/crowdfunding_contract). If a new token wishes to honour donors with free tokens based on donation amounts, this is possible via the donation_receipts (a `PrivateSet`). -See [claim_contract (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/noir-projects/noir-contracts/contracts/claim_contract). +See [claim_contract (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/noir-projects/noir-contracts/contracts/claim_contract). ## Next steps diff --git a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/contract_tutorials/nft_contract.md b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/contract_tutorials/nft_contract.md index 26eea60d30d1..a251f4b61ea5 100644 --- a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/contract_tutorials/nft_contract.md +++ b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/contract_tutorials/nft_contract.md @@ -17,9 +17,9 @@ In this tutorial you will learn how to: - Handle different private note types - Pass data between private and public state -This tutorial is compatible with the Aztec version `v0.87.3`. Install the correct version with `aztec-up -v 0.87.3`. Or if you'd like to use a different version, you can find the relevant tutorial by clicking the version dropdown at the top of the page. +This tutorial is compatible with the Aztec version `v0.87.4`. Install the correct version with `aztec-up -v 0.87.4`. Or if you'd like to use a different version, you can find the relevant tutorial by clicking the version dropdown at the top of the page. -We are going to start with a blank project and fill in the token contract source code defined [here (GitHub Link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr), and explain what is being added as we go. +We are going to start with a blank project and fill in the token contract source code defined [here (GitHub Link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr), and explain what is being added as we go. ## Requirements @@ -47,9 +47,9 @@ Inside `Nargo.toml` paste the following: ```toml [dependencies] -aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/aztec" } -authwit={ git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/authwit"} -compressed_string = {git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/compressed-string"} +aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/aztec" } +authwit={ git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/authwit"} +compressed_string = {git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/compressed-string"} ``` We will be working within `main.nr` for the rest of the tutorial. @@ -122,7 +122,6 @@ These functions are useful for getting contract information in another contract Internal functions are functions that can only be called by the contract itself. These can be used when the contract needs to call one of it's public functions from one of it's private functions. -- [`_store_payload_in_transient_storage_unsafe`](#_store_payload_in_transient_storage_unsafe) - a public function that is called when preparing a private balance increase. This function handles the needed public state updates. - [`finalize_transfer_to_private_unsafe`](#_finalize_transfer_to_private_unsafe) - finalizes a transfer from public to private state ### Utility functions @@ -137,7 +136,7 @@ Before we can implement the functions, we need set up the contract storage, and :::info Copy required files -We will be going over the code in `main.nr` [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.3/noir-projects/noir-contracts/contracts/app/nft_contract/src). If you are following along and want to compile `main.nr` yourself, you need to add the other files in the directory as they contain imports that are used in `main.nr`. +We will be going over the code in `main.nr` [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.4/noir-projects/noir-contracts/contracts/app/nft_contract/src). If you are following along and want to compile `main.nr` yourself, you need to add the other files in the directory as they contain imports that are used in `main.nr`. ::: @@ -187,7 +186,7 @@ We are importing: ### Types files -We are also importing types from a `types.nr` file, which imports types from the `types` folder. You can view them [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.3/noir-projects/noir-contracts/contracts/app/nft_contract/src). +We are also importing types from a `types.nr` file, which imports types from the `types` folder. You can view them [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.4/noir-projects/noir-contracts/contracts/app/nft_contract/src). :::note @@ -201,7 +200,7 @@ Now that we have dependencies imported into our contract we can define the stora Below the dependencies, paste the following Storage struct: -```rust title="storage_struct" showLineNumbers +```rust title="storage_struct" showLineNumbers #[storage] struct Storage { // The symbol of the NFT @@ -220,7 +219,7 @@ struct Storage { public_owners: Map, Context>, } ``` -> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L47-L65 +> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L47-L65 ## Custom Notes @@ -229,7 +228,7 @@ The contract storage uses a [custom note](../../../guides/smart_contracts/writin Randomness is required because notes are stored as commitments (hashes) in the note hash tree. Without randomness, the contents of a note may be derived through brute force (e.g. without randomness, if you know my Aztec address, you may be able to figure out which note hash in the tree is mine by hashing my address with many potential `token_id`s). -```rust title="nft_note" showLineNumbers +```rust title="nft_note" showLineNumbers /// A private note representing a token id associated to an account. #[custom_note] #[derive(Eq, Serialize)] @@ -247,7 +246,7 @@ pub struct NFTNote { token_id: Field, } ``` -> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/types/nft_note.nr#L23-L40 +> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/types/nft_note.nr#L26-L43 ## Functions @@ -258,7 +257,7 @@ Copy and paste the body of each function into the appropriate place in your proj This function sets the admin and makes them a minter, and sets the name and symbol. -```rust title="constructor" showLineNumbers +```rust title="constructor" showLineNumbers #[public] #[initializer] fn constructor(admin: AztecAddress, name: str<31>, symbol: str<31>) { @@ -269,7 +268,7 @@ fn constructor(admin: AztecAddress, name: str<31>, symbol: str<31>) { storage.symbol.initialize(FieldCompressedString::from_string(symbol)); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L67-L77 +> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L67-L77 ### Public function implementations @@ -284,35 +283,35 @@ Storage is referenced as `storage.variable`. The function checks that the `msg_sender` is the `admin`. If not, the transaction will fail. If it is, the `new_admin` is saved as the `admin`. -```rust title="set_admin" showLineNumbers +```rust title="set_admin" showLineNumbers #[public] fn set_admin(new_admin: AztecAddress) { assert(storage.admin.read().eq(context.msg_sender()), "caller is not an admin"); storage.admin.write(new_admin); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L79-L85 +> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L79-L85 #### `set_minter` This function allows the `admin` to add or a remove a `minter` from the public `minters` mapping. It checks that `msg_sender` is the `admin` and finally adds the `minter` to the `minters` mapping. -```rust title="set_minter" showLineNumbers +```rust title="set_minter" showLineNumbers #[public] fn set_minter(minter: AztecAddress, approve: bool) { assert(storage.admin.read().eq(context.msg_sender()), "caller is not an admin"); storage.minters.at(minter).write(approve); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L87-L93 +> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L87-L93 #### `mint` This public function checks that the `token_id` is not 0 and does not already exist and the `msg_sender` is authorized to mint. Then it indicates that the `token_id` exists, which is useful for verifying its existence if it gets transferred to private, and updates the owner in the `public_owners` mapping. -```rust title="mint" showLineNumbers +```rust title="mint" showLineNumbers #[public] fn mint(to: AztecAddress, token_id: Field) { assert(token_id != 0, "zero token ID not supported"); @@ -324,12 +323,12 @@ fn mint(to: AztecAddress, token_id: Field) { storage.public_owners.at(token_id).write(to); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L95-L106 +> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L95-L106 #### `transfer_in_public` -```rust title="transfer_in_public" showLineNumbers +```rust title="transfer_in_public" showLineNumbers #[public] fn transfer_in_public(from: AztecAddress, to: AztecAddress, token_id: Field, nonce: Field) { if (!from.eq(context.msg_sender())) { @@ -344,7 +343,7 @@ fn transfer_in_public(from: AztecAddress, to: AztecAddress, token_id: Field, non public_owners_storage.write(to); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L148-L162 +> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L148-L162 ##### Authorizing token spends (via authwits) @@ -357,14 +356,22 @@ If the `msg_sender` is the same as the account to debit from, the authorization This public function finalizes a transfer that has been set up by a call to [`prepare_private_balance_increase`](#prepare_private_balance_increase) by reducing the public balance of the associated account and emitting the note for the intended recipient. -```rust title="finalize_transfer_to_private" showLineNumbers +```rust title="finalize_transfer_to_private" showLineNumbers #[public] fn finalize_transfer_to_private(token_id: Field, partial_note: PartialNFTNote) { - let from = context.msg_sender(); - _finalize_transfer_to_private(from, token_id, partial_note, &mut context, storage); + // Completer is the entity that can complete the partial note. In this case, it's the same as the account + // `from` from whose account the token is being transferred. + let from_and_completer = context.msg_sender(); + _finalize_transfer_to_private( + from_and_completer, + token_id, + partial_note, + &mut context, + storage, + ); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L229-L235 +> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L224-L238 ### Private function implementations @@ -384,7 +391,7 @@ Storage is referenced as `storage.variable`. Transfers token with `token_id` from public balance of the sender to a private balance of `to`. Calls [`_prepare_private_balance_increase`](#prepare_private_balance_increase) to get the hiding point slot (a transient storage slot where we can keep the partial note) and then calls [`_finalize_transfer_to_private_unsafe`](#_finalize_transfer_to_private_unsafe) to finalize the transfer in the public context. -```rust title="transfer_to_private" showLineNumbers +```rust title="transfer_to_private" showLineNumbers #[private] fn transfer_to_private(to: AztecAddress, token_id: Field) { let from = context.msg_sender(); @@ -399,7 +406,7 @@ fn transfer_to_private(to: AztecAddress, token_id: Field) { nft._finalize_transfer_to_private_unsafe(from, token_id, partial_note).enqueue(&mut context); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L165-L179 +> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L165-L179 #### `prepare_private_balance_increase` @@ -412,9 +419,7 @@ This function calls `_prepare_private_balance_increase` which is marked as `#[co ::: -It also calls [`_store_payload_in_transient_storage_unsafe`](#_store_payload_in_transient_storage_unsafe) to store the partial note in "transient storage" (more below) - -```rust title="prepare_private_balance_increase" showLineNumbers +```rust title="prepare_private_balance_increase" showLineNumbers #[private] fn prepare_private_balance_increase(to: AztecAddress) -> PartialNFTNote { _prepare_private_balance_increase(to, &mut context, storage) @@ -431,28 +436,29 @@ fn _prepare_private_balance_increase( context: &mut PrivateContext, storage: Storage<&mut PrivateContext>, ) -> PartialNFTNote { - // We create a partial note with unpopulated/zero token id for 'to' + let sender_and_completer = context.msg_sender(); + + // We setup a partial note with unpopulated/zero token id for 'to'. let partial_note = NFTNote::partial( to, storage.private_nfts.at(to).storage_slot, context, to, - context.msg_sender(), + sender_and_completer, + sender_and_completer, ); - NFT::at(context.this_address())._store_nft_set_partial_note(partial_note).enqueue(context); - partial_note } ``` -> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L183-L213 +> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L183-L214 #### `cancel_authwit` Cancels a private authwit by emitting the corresponding nullifier. -```rust title="cancel_authwit" showLineNumbers +```rust title="cancel_authwit" showLineNumbers #[private] fn cancel_authwit(inner_hash: Field) { let on_behalf_of = context.msg_sender(); @@ -460,14 +466,14 @@ fn cancel_authwit(inner_hash: Field) { context.push_nullifier(nullifier); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L275-L282 +> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L285-L292 #### `transfer_in_private` Transfers an NFT between two addresses in the private context. Uses [authwits](../../../../aztec/concepts/advanced/authwit.md) to allow contracts to transfer NFTs on behalf of other accounts. -```rust title="transfer_in_private" showLineNumbers +```rust title="transfer_in_private" showLineNumbers #[private] fn transfer_in_private(from: AztecAddress, to: AztecAddress, token_id: Field, nonce: Field) { if (!from.eq(context.msg_sender())) { @@ -488,14 +494,14 @@ fn transfer_in_private(from: AztecAddress, to: AztecAddress, token_id: Field, no nfts.at(to).insert(new_note).emit(encode_and_encrypt_note(&mut context, to, from)); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L284-L304 +> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L294-L314 #### `transfer_to_public` Transfers and NFT from private storage to public storage. The private call enqueues a call to [`_finish_transfer_to_public`](#_finish_transfer_to_public) which updates the public owner of the `token_id`. -```rust title="transfer_to_public" showLineNumbers +```rust title="transfer_to_public" showLineNumbers #[private] fn transfer_to_public(from: AztecAddress, to: AztecAddress, token_id: Field, nonce: Field) { if (!from.eq(context.msg_sender())) { @@ -514,63 +520,52 @@ fn transfer_to_public(from: AztecAddress, to: AztecAddress, token_id: Field, non ); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L306-L324 +> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L316-L334 ### Internal function implementations Internal functions are functions that can only be called by this contract. The following 3 functions are public functions that are called from the [private execution context](#execution-contexts). Marking these as `internal` ensures that only the desired private functions in this contract are able to call them. Private functions defer execution to public functions because private functions cannot update public state directly. -#### `_store_payload_in_transient_storage_unsafe` - -It is labeled unsafe because the public function does not check the value of the storage slot before writing, but it is safe because of the private execution preceding this call. - -This is transient storage since the storage is not permanent, but is scoped to the current transaction only, after which it will be reset. The partial note is stored the "hiding point slot" value (computed in `_prepare_private_balance_increase()`) in public storage. However subsequent enqueued call to `_finalize_transfer_to_private_unsafe()` will read the partial note in this slot, complete it and emit it. Since the note is completed, there is no use of storing the hiding point slot anymore so we will reset to empty. This saves a write to public storage too. - -```rust title="store_payload_in_transient_storage_unsafe" showLineNumbers -#[public] -#[internal] -fn _store_nft_set_partial_note(partial_note: PartialNFTNote) { - // We store the partial note in a slot equal to its commitment. This is safe because the commitment is computed - // using a generator different from the one used to compute storage slots, so there can be no collisions. - // We could consider storing all pending partial notes in e.g. some array, but ultimately this is pointless: all - // we need to verify is that the note is valid. - context.storage_write(partial_note.commitment(), true); -} -``` -> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L215-L225 - - #### `_finalize_transfer_to_private_unsafe` This function is labeled as unsafe because the sender is not enforced in this function, but it is safe because the sender is enforced in the execution of the private function that calls this function. -```rust title="finalize_transfer_to_private_unsafe" showLineNumbers +```rust title="finalize_transfer_to_private_unsafe" showLineNumbers +/// This is a wrapper around `_finalize_transfer_to_private` placed here so that a call +/// to `_finalize_transfer_to_private` can be enqueued. Called unsafe as it does not check `from_and_completer` +/// (this has to be done in the calling function). #[public] #[internal] fn _finalize_transfer_to_private_unsafe( - from: AztecAddress, + from_and_completer: AztecAddress, token_id: Field, partial_note: PartialNFTNote, ) { - _finalize_transfer_to_private(from, token_id, partial_note, &mut context, storage); + _finalize_transfer_to_private( + from_and_completer, + token_id, + partial_note, + &mut context, + storage, + ); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L237-L247 +> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L240-L259 #### `_finish_transfer_to_public` Updates the public owner of the `token_id` to the `to` address. -```rust title="finish_transfer_to_public" showLineNumbers +```rust title="finish_transfer_to_public" showLineNumbers #[public] #[internal] fn _finish_transfer_to_public(to: AztecAddress, token_id: Field) { storage.public_owners.at(token_id).write(to); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L326-L332 +> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L336-L342 ### View function implementations @@ -581,28 +576,28 @@ NFT implements the following `view` functions: A getter function for reading the public `admin` value. -```rust title="admin" showLineNumbers +```rust title="admin" showLineNumbers #[public] #[view] fn get_admin() -> Field { storage.admin.read().to_field() } ``` -> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L132-L138 +> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L132-L138 #### `is_minter` A getter function for checking the value of associated with a `minter` in the public `minters` mapping. -```rust title="is_minter" showLineNumbers +```rust title="is_minter" showLineNumbers #[public] #[view] fn is_minter(minter: AztecAddress) -> bool { storage.minters.at(minter).read() } ``` -> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L140-L146 +> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L140-L146 #### `owner_of` @@ -633,7 +628,7 @@ The NFT implements the following [utility](../../../../aztec/concepts/call_types A getter function for checking the private balance of the provided Aztec account. Returns an array of token IDs owned by `owner` in private and a flag indicating whether a page limit was reached. -```rust title="get_private_nfts" showLineNumbers +```rust title="get_private_nfts" showLineNumbers #[utility] unconstrained fn get_private_nfts( owner: AztecAddress, @@ -654,7 +649,7 @@ unconstrained fn get_private_nfts( (owned_nft_ids, page_limit_reached) } ``` -> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L345-L365 +> Source code: noir-projects/noir-contracts/contracts/app/nft_contract/src/main.nr#L355-L375 ## Compiling @@ -675,7 +670,7 @@ aztec codegen target -o src/artifacts ### Optional: Dive deeper into this contract and concepts mentioned here -- Review [the end to end tests (Github link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/yarn-project/end-to-end/src/e2e_nft.test.ts) for reference. +- Review [the end to end tests (Github link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/yarn-project/end-to-end/src/e2e_nft.test.ts) for reference. - [Nullifier tree](../../../../aztec/concepts/advanced/storage/indexed_merkle_tree.mdx) - [Public / Private function calls](../../../../aztec/smart_contracts/functions/public_private_calls.md). - [Contract Storage](../../../../aztec/concepts/storage/index.md) diff --git a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/contract_tutorials/private_voting_contract.md b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/contract_tutorials/private_voting_contract.md index 8ad8be88c418..d0c621973028 100644 --- a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/contract_tutorials/private_voting_contract.md +++ b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/contract_tutorials/private_voting_contract.md @@ -9,7 +9,7 @@ import Image from '@theme/IdealImage'; In this tutorial we will go through writing a very simple private voting smart contract in Aztec.nr. You will learn about private functions, public functions, composability between them, state management and creatively using nullifiers to prevent people from voting twice! -This tutorial is compatible with the Aztec version `v0.87.3`. Install the correct version with `aztec-up -v 0.87.3`. Or if you'd like to use a different version, you can find the relevant tutorial by clicking the version dropdown at the top of the page. +This tutorial is compatible with the Aztec version `v0.87.4`. Install the correct version with `aztec-up -v 0.87.4`. Or if you'd like to use a different version, you can find the relevant tutorial by clicking the version dropdown at the top of the page. We will build this: @@ -50,7 +50,7 @@ We will need the Aztec library to create this contract. In your `Nargo.toml` you ```toml [dependencies] -aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/aztec" } +aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/aztec" } ``` ## Initiate the contract and define imports @@ -69,7 +69,7 @@ This defines a contract called `Voter`. Everything will sit inside this block. Inside this, paste these imports: -```rust title="imports" showLineNumbers +```rust title="imports" showLineNumbers use dep::aztec::{ keys::getters::get_public_keys, macros::{functions::{initializer, internal, private, public, utility}, storage::storage}, @@ -77,7 +77,7 @@ use dep::aztec::{ use dep::aztec::prelude::{AztecAddress, Map, PublicImmutable, PublicMutable}; use dep::aztec::protocol_types::traits::{Hash, ToField}; ``` -> Source code: noir-projects/noir-contracts/contracts/app/easy_private_voting_contract/src/main.nr#L8-L16 +> Source code: noir-projects/noir-contracts/contracts/app/easy_private_voting_contract/src/main.nr#L8-L16 We are using various utils within the Aztec `prelude` library: @@ -90,6 +90,7 @@ We are using various utils within the Aztec `prelude` library: - `use dep::aztec::prelude::{AztecAddress, Map, PublicImmutable, PublicMutable};` Imports: + - `AztecAddress`: a type for account/contract addresses, - `Map`: a key-value storage structure, - `PublicMutable`: public state that can be updated, @@ -98,13 +99,12 @@ We are using various utils within the Aztec `prelude` library: - `use dep::aztec::protocol_types::traits::{Hash, ToField};` Provides the `Hash` and `ToField` traits, used for hashing values and converting them to a Field, used for nullifier creation and other computations. - ## Set up storage Under these imports, we need to set up our contract storage. Define the storage struct like so: -```rust title="storage_struct" showLineNumbers +```rust title="storage_struct" showLineNumbers #[storage] struct Storage { admin: PublicMutable, // admin can end vote @@ -113,7 +113,7 @@ struct Storage { active_at_block: PublicImmutable, // when people can start voting } ``` -> Source code: noir-projects/noir-contracts/contracts/app/easy_private_voting_contract/src/main.nr#L17-L25 +> Source code: noir-projects/noir-contracts/contracts/app/easy_private_voting_contract/src/main.nr#L17-L25 In this contract, we will store three vars: @@ -127,7 +127,7 @@ In this contract, we will store three vars: The next step is to initialize the contract with a constructor. The constructor will take an address as a parameter and set the admin. -```rust title="constructor" showLineNumbers +```rust title="constructor" showLineNumbers #[public] #[initializer] // annotation to mark function as a constructor @@ -137,7 +137,7 @@ fn constructor(admin: AztecAddress) { storage.active_at_block.initialize(context.block_number() as u32); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/easy_private_voting_contract/src/main.nr#L27-L36 +> Source code: noir-projects/noir-contracts/contracts/app/easy_private_voting_contract/src/main.nr#L27-L36 This function takes the admin argument and writes it to the storage. We are also using this function to set the `vote_ended` boolean as false in the same way. @@ -154,7 +154,7 @@ To ensure someone only votes once, we will create a nullifier as part of the fun Create a private function called `cast_vote`: -```rust title="cast_vote" showLineNumbers +```rust title="cast_vote" showLineNumbers #[private] // annotation to mark function as private and expose private context fn cast_vote(candidate: Field) { @@ -168,7 +168,7 @@ fn cast_vote(candidate: Field) { ); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/easy_private_voting_contract/src/main.nr#L38-L51 +> Source code: noir-projects/noir-contracts/contracts/app/easy_private_voting_contract/src/main.nr#L38-L51 In this function, we do not create a nullifier with the address directly. This would leak privacy as it would be easy to reverse-engineer. We must add some randomness or some form of secret, like nullifier secrets. @@ -179,7 +179,7 @@ After pushing the nullifier, we update the `tally` to reflect this vote. As we k Create this new public function like this: -```rust title="add_to_tally_public" showLineNumbers +```rust title="add_to_tally_public" showLineNumbers #[public] #[internal] fn add_to_tally_public(candidate: Field) { @@ -188,7 +188,7 @@ fn add_to_tally_public(candidate: Field) { storage.tally.at(candidate).write(new_tally); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/easy_private_voting_contract/src/main.nr#L53-L61 +> Source code: noir-projects/noir-contracts/contracts/app/easy_private_voting_contract/src/main.nr#L53-L61 The first thing we do here is assert that the vote has not ended. @@ -201,13 +201,13 @@ The code after the assertion will only run if the assertion is true. In this sni We will create a function that anyone can call that will return the number of votes at a given vote Id. Paste this in your contract: -```rust title="get_vote" showLineNumbers +```rust title="get_vote" showLineNumbers #[utility] unconstrained fn get_vote(candidate: Field) -> Field { storage.tally.at(candidate).read() } ``` -> Source code: noir-projects/noir-contracts/contracts/app/easy_private_voting_contract/src/main.nr#L70-L75 +> Source code: noir-projects/noir-contracts/contracts/app/easy_private_voting_contract/src/main.nr#L70-L75 We set it as `utility` because we don't intend to call this as part of a transaction: we want to call it from our application code to e.g. display the result in a UI. @@ -218,14 +218,14 @@ To ensure that only an `admin` can end a voting period, we can use another `asse Paste this function in your contract: -```rust title="end_vote" showLineNumbers +```rust title="end_vote" showLineNumbers #[public] fn end_vote() { assert(storage.admin.read().eq(context.msg_sender()), "Only admin can end votes"); // assert that caller is admin storage.vote_ended.write(true); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/easy_private_voting_contract/src/main.nr#L63-L69 +> Source code: noir-projects/noir-contracts/contracts/app/easy_private_voting_contract/src/main.nr#L63-L69 Here, we are asserting that the `msg_sender()` is equal to the `admin` stored in public state. diff --git a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/contract_tutorials/token_contract.md b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/contract_tutorials/token_contract.md index 8f221731d975..d7ac064d5d42 100644 --- a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/contract_tutorials/token_contract.md +++ b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/contract_tutorials/token_contract.md @@ -17,9 +17,9 @@ In this tutorial you will learn how to: - Handle different private note types - Pass data between private and public state -We are going to start with a blank project and fill in the token contract source code defined [here (GitHub Link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr), and explain what is being added as we go. +We are going to start with a blank project and fill in the token contract source code defined [here (GitHub Link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr), and explain what is being added as we go. -This tutorial is compatible with the Aztec version `v0.87.3`. Install the correct version with `aztec-up -v 0.87.3`. Or if you'd like to use a different version, you can find the relevant tutorial by clicking the version dropdown at the top of the page. +This tutorial is compatible with the Aztec version `v0.87.4`. Install the correct version with `aztec-up -v 0.87.4`. Or if you'd like to use a different version, you can find the relevant tutorial by clicking the version dropdown at the top of the page. ## Requirements @@ -47,10 +47,10 @@ Inside `Nargo.toml` paste the following: ```toml [dependencies] -aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/aztec" } -authwit={ git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/authwit"} -compressed_string = {git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/compressed-string"} -uint_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/uint-note" } +aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/aztec" } +authwit={ git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/authwit"} +compressed_string = {git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/compressed-string"} +uint_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/uint-note" } ``` We will be working within `main.nr` for the rest of the tutorial. @@ -131,7 +131,7 @@ Before we can implement the functions, we need set up the contract storage, and :::info Copy required files -We will be going over the code in `main.nr` [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.3/noir-projects/noir-contracts/contracts/app/token_contract/src). If you are following along and want to compile `main.nr` yourself, you need to add the other files in the directory as they contain imports that are used in `main.nr`. +We will be going over the code in `main.nr` [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.4/noir-projects/noir-contracts/contracts/app/token_contract/src). If you are following along and want to compile `main.nr` yourself, you need to add the other files in the directory as they contain imports that are used in `main.nr`. ::: @@ -192,7 +192,7 @@ We are importing: ### Types files -We are also importing types from a `types.nr` file, which imports types from the `types` folder. You can view them [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.3/noir-projects/noir-contracts/contracts/app/token_contract/src). +We are also importing types from a `types.nr` file, which imports types from the `types` folder. You can view them [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.4/noir-projects/noir-contracts/contracts/app/token_contract/src). :::note @@ -206,7 +206,7 @@ Now that we have dependencies imported into our contract we can define the stora Below the dependencies, paste the following Storage struct: -```rust title="storage_struct" showLineNumbers +```rust title="storage_struct" showLineNumbers #[storage] struct Storage { admin: PublicMutable, @@ -219,7 +219,7 @@ struct Storage { decimals: PublicImmutable, } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L68-L88 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L68-L88 Reading through the storage variables: @@ -239,7 +239,7 @@ Copy and paste the body of each function into the appropriate place in your proj This function sets the creator of the contract (passed as `msg_sender` from the constructor) as the admin and makes them a minter, and sets name, symbol, and decimals. -```rust title="constructor" showLineNumbers +```rust title="constructor" showLineNumbers #[public] #[initializer] fn constructor(admin: AztecAddress, name: str<31>, symbol: str<31>, decimals: u8) { @@ -251,7 +251,7 @@ fn constructor(admin: AztecAddress, name: str<31>, symbol: str<31>, decimals: u8 storage.decimals.initialize(decimals); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L90-L103 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L90-L103 ### Public function implementations @@ -266,28 +266,28 @@ Storage is referenced as `storage.variable`. After storage is initialized, the contract checks that the `msg_sender` is the `admin`. If not, the transaction will fail. If it is, the `new_admin` is saved as the `admin`. -```rust title="set_admin" showLineNumbers +```rust title="set_admin" showLineNumbers #[public] fn set_admin(new_admin: AztecAddress) { assert(storage.admin.read().eq(context.msg_sender()), "caller is not admin"); storage.admin.write(new_admin); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L105-L113 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L105-L113 #### `set_minter` This function allows the `admin` to add or a remove a `minter` from the public `minters` mapping. It checks that `msg_sender` is the `admin` and finally adds the `minter` to the `minters` mapping. -```rust title="set_minter" showLineNumbers +```rust title="set_minter" showLineNumbers #[public] fn set_minter(minter: AztecAddress, approve: bool) { assert(storage.admin.read().eq(context.msg_sender()), "caller is not admin"); storage.minters.at(minter).write(approve); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L183-L193 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L183-L193 #### `mint_to_public` @@ -296,7 +296,7 @@ This function allows an account approved in the public `minters` mapping to crea First, storage is initialized. Then the function checks that the `msg_sender` is approved to mint in the `minters` mapping. If it is, a new `U128` value is created of the `amount` provided. The function reads the recipients public balance and then adds the amount to mint, saving the output as `new_balance`, then reads to total supply and adds the amount to mint, saving the output as `supply`. `new_balance` and `supply` are then written to storage. -```rust title="mint_to_public" showLineNumbers +```rust title="mint_to_public" showLineNumbers #[public] fn mint_to_public(to: AztecAddress, amount: u128) { assert(storage.minters.at(context.msg_sender()).read(), "caller is not minter"); @@ -306,7 +306,7 @@ fn mint_to_public(to: AztecAddress, amount: u128) { storage.total_supply.write(supply); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L195-L206 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L195-L206 #### `transfer_in_public` @@ -319,7 +319,7 @@ If the `msg_sender` is **NOT** the same as the account to debit from, the functi If the `msg_sender` is the same as the account to debit tokens from, the authorization check is bypassed and the function proceeds to update the account's `public_balance`. -```rust title="transfer_in_public" showLineNumbers +```rust title="transfer_in_public" showLineNumbers #[public] fn transfer_in_public(from: AztecAddress, to: AztecAddress, amount: u128, nonce: Field) { if (!from.eq(context.msg_sender())) { @@ -333,7 +333,7 @@ fn transfer_in_public(from: AztecAddress, to: AztecAddress, amount: u128, nonce: storage.public_balances.at(to).write(to_balance); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L208-L221 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L208-L221 #### `burn_public` @@ -342,7 +342,7 @@ This public function enables public burning (destroying) of tokens from the send After storage is initialized, the [authorization flow specified above](#authorizing-token-spends) is checked. Then the sender's public balance and the `total_supply` are updated and saved to storage. -```rust title="burn_public" showLineNumbers +```rust title="burn_public" showLineNumbers #[public] fn burn_public(from: AztecAddress, amount: u128, nonce: Field) { if (!from.eq(context.msg_sender())) { @@ -356,14 +356,14 @@ fn burn_public(from: AztecAddress, amount: u128, nonce: Field) { storage.total_supply.write(new_supply); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L223-L238 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L223-L238 #### `finalize_mint_to_private` This public function finalizes a transfer that has been set up by a call to `prepare_private_balance_increase` by reducing the public balance of the associated account and emitting the note for the intended recipient. -```rust title="finalize_mint_to_private" showLineNumbers +```rust title="finalize_mint_to_private" showLineNumbers /// Finalizes a mint of token `amount` to a private balance of `to`. The mint must be prepared by calling /// `prepare_private_balance_increase` first and the resulting /// `partial_note` must be passed as an argument to this function. @@ -373,29 +373,51 @@ This public function finalizes a transfer that has been set up by a call to `pre /// (e.g. used during token bridging, in AMM liquidity token etc.). #[public] fn finalize_mint_to_private(amount: u128, partial_note: PartialUintNote) { - assert(storage.minters.at(context.msg_sender()).read(), "caller is not minter"); + // Completer is the entity that can complete the partial note. In this case, it's the same as the minter + // account. + let minter_and_completer = context.msg_sender(); + assert(storage.minters.at(minter_and_completer).read(), "caller is not minter"); - _finalize_mint_to_private(amount, partial_note, &mut context, storage); + _finalize_mint_to_private( + minter_and_completer, + amount, + partial_note, + &mut context, + storage, + ); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L531-L545 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L544-L567 #### `finalize_transfer_to_private` Similar to `finalize_mint_to_private`, this public function finalizes a transfer that has been set up by a call to `prepare_private_balance_increase` by reducing the public balance of the associated account and emitting the note for the intended recipient. -```rust title="finalize_transfer_to_private" showLineNumbers -/// Finalizes a transfer of token `amount` from public balance of `from` to a private balance of `to`. -/// The transfer must be prepared by calling `prepare_private_balance_increase` first and the resulting -/// `partial_note` must be passed as an argument to this function. +```rust title="finalize_transfer_to_private" showLineNumbers +/// Finalizes a transfer of token `amount` from public balance of `msg_sender` to a private balance of `to`. +/// The transfer must be prepared by calling `prepare_private_balance_increase` from `msg_sender` account and +/// the resulting `partial_note` must be passed as an argument to this function. +/// +/// Note that this contract does not protect against a `partial_note` being used multiple times and it is up to +/// the caller of this function to ensure that it doesn't happen. If the same `partial_note` is used multiple +/// times, the token `amount` would most likely get lost (the partial note log processing functionality would fail +/// to find the pending partial note when trying to complete it). #[public] fn finalize_transfer_to_private(amount: u128, partial_note: PartialUintNote) { - let from = context.msg_sender(); - _finalize_transfer_to_private(from, amount, partial_note, &mut context, storage); + // Completer is the entity that can complete the partial note. In this case, it's the same as the account + // `from` from whose balance we're subtracting the `amount`. + let from_and_completer = context.msg_sender(); + _finalize_transfer_to_private( + from_and_completer, + amount, + partial_note, + &mut context, + storage, + ); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L462-L471 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L456-L478 ### Private function implementations @@ -419,7 +441,7 @@ After initializing storage, the function checks that the `msg_sender` is authori The function returns `1` to indicate successful execution. -```rust title="transfer_to_public" showLineNumbers +```rust title="transfer_to_public" showLineNumbers #[private] fn transfer_to_public(from: AztecAddress, to: AztecAddress, amount: u128, nonce: Field) { if (!from.eq(context.msg_sender())) { @@ -436,7 +458,7 @@ fn transfer_to_public(from: AztecAddress, to: AztecAddress, amount: u128, nonce: Token::at(context.this_address())._increase_public_balance(to, amount).enqueue(&mut context); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L240-L256 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L240-L256 #### `transfer` @@ -445,7 +467,7 @@ This private function enables private token transfers between Aztec accounts. After initializing storage, the function checks that the `msg_sender` is authorized to spend tokens. See [the Authorizing token spends section](#authorizing-token-spends) above for more detail--the only difference being that `assert_valid_message_for` is modified to work specifically in the private context. After authorization, the function gets the current balances for the sender and recipient and decrements and increments them, respectively, using the `value_note` helper functions. -```rust title="transfer" showLineNumbers +```rust title="transfer" showLineNumbers #[private] fn transfer(to: AztecAddress, amount: u128) { let from = context.msg_sender(); @@ -485,14 +507,14 @@ fn transfer(to: AztecAddress, amount: u128) { )); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L258-L299 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L258-L299 #### `transfer_in_private` This private function enables an account to transfer tokens on behalf of another account. The account that tokens are being debited from must have authorized the `msg_sender` to spend tokens on its behalf. -```rust title="transfer_in_private" showLineNumbers +```rust title="transfer_in_private" showLineNumbers #[private] fn transfer_in_private(from: AztecAddress, to: AztecAddress, amount: u128, nonce: Field) { if (!from.eq(context.msg_sender())) { @@ -509,7 +531,7 @@ fn transfer_in_private(from: AztecAddress, to: AztecAddress, amount: u128, nonce storage.balances.at(to).add(to, amount).emit(encode_and_encrypt_note(&mut context, to, from)); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L363-L383 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L363-L383 #### `transfer_to_private` @@ -518,7 +540,7 @@ This function execution flow starts in the private context and is completed with First a partial note is prepared then a call to the public, internal `_finalize_transfer_to_private_unsafe` is enqueued. The enqueued public call subtracts the `amount` from public balance of `msg_sender` and finalizes the partial note with the `amount`. -```rust title="transfer_to_private" showLineNumbers +```rust title="transfer_to_private" showLineNumbers // Transfers token `amount` from public balance of message sender to a private balance of `to`. #[private] fn transfer_to_private(to: AztecAddress, amount: u128) { @@ -534,18 +556,19 @@ fn transfer_to_private(to: AztecAddress, amount: u128) { token._finalize_transfer_to_private_unsafe(from, amount, partial_note).enqueue(&mut context); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L402-L417 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L402-L417 #### `mint_to_private` This private function prepares a partial `UintNote` at the recipients storage slot in the contract and enqueues a public call to `_finalize_mint_to_private_unsafe`, which asserts that the `msg_sender` is an authorized minter and finalized the mint by incrementing the total supply and emitting the complete, encrypted `UintNote` to the intended recipient. Note that the `amount` and the minter (`from`) are public, but the recipient is private. -```rust title="mint_to_private" showLineNumbers +```rust title="mint_to_private" showLineNumbers /// Mints token `amount` to a private balance of `to`. Message sender has to have minter permissions (checked /// in the enqueued call). #[private] fn mint_to_private( + // TODO(benesjan): This allows minter to set arbitrary `from`. That seems undesirable. Will nuke it in a followup PR. from: AztecAddress, // sender of the tag to: AztecAddress, amount: u128, @@ -555,22 +578,22 @@ fn mint_to_private( // We prepare the partial note to which we'll "send" the minted amount. let partial_note = _prepare_private_balance_increase(from, to, &mut context, storage); - // At last we finalize the mint. Usage of the `unsafe` method here is safe because we set the `from` - // function argument to a message sender, guaranteeing that only a message sender with minter permissions - // can successfully execute the function. + // At last we finalize the mint. Usage of the `unsafe` method here is safe because we set + // the `minter_and_completer` function argument to a message sender, guaranteeing that only a message sender + // with minter permissions can successfully execute the function. token._finalize_mint_to_private_unsafe(context.msg_sender(), amount, partial_note).enqueue( &mut context, ); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L508-L529 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L520-L542 #### `cancel_authwit` This private function allows a user to cancel an authwit that was previously granted. This is achieved by emitting the corresponding nullifier before it is used. -```rust title="cancel_authwit" showLineNumbers +```rust title="cancel_authwit" showLineNumbers #[private] fn cancel_authwit(inner_hash: Field) { let on_behalf_of = context.msg_sender(); @@ -578,7 +601,7 @@ fn cancel_authwit(inner_hash: Field) { context.push_nullifier(nullifier); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L354-L361 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L354-L361 #### `burn_private` @@ -587,7 +610,7 @@ This private function enables accounts to privately burn (destroy) tokens. After initializing storage, the function checks that the `msg_sender` is authorized to spend tokens. Then it gets the sender's current balance and decrements it. Finally it stages a public function call to [`_reduce_total_supply`](#_reduce_total_supply). -```rust title="burn_private" showLineNumbers +```rust title="burn_private" showLineNumbers #[private] fn burn_private(from: AztecAddress, amount: u128, nonce: Field) { if (!from.eq(context.msg_sender())) { @@ -603,7 +626,7 @@ fn burn_private(from: AztecAddress, amount: u128, nonce: Field) { Token::at(context.this_address())._reduce_total_supply(amount).enqueue(&mut context); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L385-L400 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L385-L400 #### `prepare_private_balance_increase` @@ -612,7 +635,7 @@ TODO: update from `prepare_transfer_to_private` This private function prepares to transfer from a public balance to a private balance by setting up a partial note for the recipient. The function returns the `hiding_point_slot`. After this, the public [`finalize_transfer_to_private`](#finalize_transfer_to_private) must be called, passing the amount and the hiding point slot. -```rust title="prepare_private_balance_increase" showLineNumbers +```rust title="prepare_private_balance_increase" showLineNumbers /// Prepares an increase of private balance of `to` (partial note). The increase needs to be finalized by calling /// some of the finalization functions (`finalize_transfer_to_private`, `finalize_mint_to_private`) with the /// returned partial note. @@ -622,7 +645,7 @@ fn prepare_private_balance_increase(to: AztecAddress, from: AztecAddress) -> Par _prepare_private_balance_increase(from, to, &mut context, storage) } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L419-L428 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L419-L428 ### Internal function implementations @@ -633,7 +656,7 @@ Internal functions are functions that can only be called by this contract. The f This function is called from [`transfer_to_public`](#transfer_to_public). The account's private balance is decremented in `transfer_to_public` and the public balance is increased in this function. -```rust title="increase_public_balance" showLineNumbers +```rust title="increase_public_balance" showLineNumbers /// TODO(#9180): Consider adding macro support for functions callable both as an entrypoint and as an internal /// function. #[public] @@ -642,14 +665,14 @@ fn _increase_public_balance(to: AztecAddress, amount: u128) { _increase_public_balance_inner(to, amount, storage); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L591-L599 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L609-L617 #### `_reduce_total_supply` This function is called from [`burn`](#burn). The account's private balance is decremented in `burn` and the public `total_supply` is reduced in this function. -```rust title="reduce_total_supply" showLineNumbers +```rust title="reduce_total_supply" showLineNumbers #[public] #[internal] fn _reduce_total_supply(amount: u128) { @@ -658,7 +681,7 @@ fn _reduce_total_supply(amount: u128) { storage.total_supply.write(new_supply); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L611-L619 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L629-L637 #### `_finalize_transfer_to_private_unsafe` @@ -667,41 +690,56 @@ This public internal function decrements the public balance of the `from` accoun This function is called by the private function [`transfer_to_private`](#transfer_to_private) to finalize the transfer. The `transfer_to_private` enforces the `from` argument, which is why using it `unsafe` is okay. -```rust title="finalize_transfer_to_private_unsafe" showLineNumbers +```rust title="finalize_transfer_to_private_unsafe" showLineNumbers /// This is a wrapper around `_finalize_transfer_to_private` placed here so that a call -/// to `_finalize_transfer_to_private` can be enqueued. Called unsafe as it does not check `from` (this has to be -/// done in the calling function). +/// to `_finalize_transfer_to_private` can be enqueued. Called unsafe as it does not check `from_and_completer` +/// (this has to be done in the calling function). #[public] #[internal] fn _finalize_transfer_to_private_unsafe( - from: AztecAddress, + from_and_completer: AztecAddress, amount: u128, partial_note: PartialUintNote, ) { - _finalize_transfer_to_private(from, amount, partial_note, &mut context, storage); + _finalize_transfer_to_private( + from_and_completer, + amount, + partial_note, + &mut context, + storage, + ); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L473-L486 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L480-L499 #### `_finalize_mint_to_private_unsafe` Similar to `_finalize_transfer_to_private_unsafe`, this public internal function increments the private balance of the recipient by finalizing the partial note and emitting the encrypted note. It also increments the public total supply and ensures that the sender of the transaction is authorized to mint tokens on the contract. -```rust title="finalize_mint_to_private_unsafe" showLineNumbers +```rust title="finalize_mint_to_private_unsafe" showLineNumbers +/// This is a wrapper around `_finalize_mint_to_private` placed here so that a call +/// to `_finalize_mint_to_private` can be enqueued. Called unsafe as it does not check `minter_and_completer` (this +/// has to be done in the calling function). #[public] #[internal] fn _finalize_mint_to_private_unsafe( - from: AztecAddress, + minter_and_completer: AztecAddress, amount: u128, partial_note: PartialUintNote, ) { // We check the minter permissions as it was not done in `mint_to_private` function. - assert(storage.minters.at(from).read(), "caller is not minter"); - _finalize_mint_to_private(amount, partial_note, &mut context, storage); + assert(storage.minters.at(minter_and_completer).read(), "caller is not minter"); + _finalize_mint_to_private( + minter_and_completer, + amount, + partial_note, + &mut context, + storage, + ); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L547-L559 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L569-L590 ### View function implementations @@ -714,56 +752,56 @@ Public view calls that are part of a transaction will be executed by the sequenc A getter function for reading the public `admin` value. -```rust title="admin" showLineNumbers +```rust title="admin" showLineNumbers #[public] #[view] fn get_admin() -> Field { storage.admin.read().to_field() } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L151-L157 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L151-L157 #### `is_minter` A getter function for checking the value of associated with a `minter` in the public `minters` mapping. -```rust title="is_minter" showLineNumbers +```rust title="is_minter" showLineNumbers #[public] #[view] fn is_minter(minter: AztecAddress) -> bool { storage.minters.at(minter).read() } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L159-L165 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L159-L165 #### `total_supply` A getter function for checking the token `total_supply`. -```rust title="total_supply" showLineNumbers +```rust title="total_supply" showLineNumbers #[public] #[view] fn total_supply() -> u128 { storage.total_supply.read() } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L167-L173 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L167-L173 #### `balance_of_public` A getter function for checking the public balance of the provided Aztec account. -```rust title="balance_of_public" showLineNumbers +```rust title="balance_of_public" showLineNumbers #[public] #[view] fn balance_of_public(owner: AztecAddress) -> u128 { storage.public_balances.at(owner).read() } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L175-L181 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L175-L181 ### Utility function implementations @@ -772,15 +810,15 @@ fn balance_of_public(owner: AztecAddress) -> u128 { #### `balance_of_private` -A getter function for checking the private balance of the provided Aztec account. Note that the [Private Execution Environment (PXE) (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.3/yarn-project/pxe) must have `ivsk` ([incoming viewing secret key](../../../../aztec/concepts/accounts/keys.md#incoming-viewing-keys)) in order to decrypt the notes. +A getter function for checking the private balance of the provided Aztec account. Note that the [Private Execution Environment (PXE) (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.4/yarn-project/pxe) must have `ivsk` ([incoming viewing secret key](../../../../aztec/concepts/accounts/keys.md#incoming-viewing-keys)) in order to decrypt the notes. -```rust title="balance_of_private" showLineNumbers +```rust title="balance_of_private" showLineNumbers #[utility] pub(crate) unconstrained fn balance_of_private(owner: AztecAddress) -> u128 { storage.balances.at(owner).balance_of() } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L621-L626 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L639-L644 ## Compiling @@ -809,7 +847,7 @@ It builds on the Token contract described here and goes into more detail about A ### Optional: Dive deeper into this contract and concepts mentioned here -- Review [the end to end tests (Github link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/yarn-project/end-to-end/src/e2e_token_contract/) for reference. +- Review [the end to end tests (Github link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/yarn-project/end-to-end/src/e2e_token_contract/) for reference. - [Commitments (Wikipedia link)](https://en.wikipedia.org/wiki/Commitment_scheme) - [Nullifier tree](../../../../aztec/concepts/advanced/storage/indexed_merkle_tree.mdx) - [Public / Private function calls](../../../../aztec/smart_contracts/functions/public_private_calls.md). diff --git a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/contract_tutorials/write_accounts_contract.md b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/contract_tutorials/write_accounts_contract.md index 2478e1072ba2..dec55da2c973 100644 --- a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/contract_tutorials/write_accounts_contract.md +++ b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/contract_tutorials/write_accounts_contract.md @@ -15,7 +15,7 @@ You will learn: - Typescript glue code to format and authenticate transactions - Deploying and testing the account contract -This tutorial is compatible with the Aztec version `v0.87.3`. Install the correct version with `aztec-up -v 0.87.3`. Or if you'd like to use a different version, you can find the relevant tutorial by clicking the version dropdown at the top of the page. +This tutorial is compatible with the Aztec version `v0.87.4`. Install the correct version with `aztec-up -v 0.87.4`. Or if you'd like to use a different version, you can find the relevant tutorial by clicking the version dropdown at the top of the page. Writing your own account contract allows you to define the rules by which user transactions are authorized and paid for, as well as how user keys are managed (including key rotation and recovery). In other words, writing an account contract lets you make the most out of account abstraction in the Aztec network. @@ -31,7 +31,7 @@ For the sake of simplicity, we will hardcode the signing public key into the con Let's start with the account contract itself in Aztec.nr. Create a new Aztec.nr contract project that will contain a file with the code for the account contract, with a hardcoded public key: -```rust title="contract" showLineNumbers +```rust title="contract" showLineNumbers // Account contract that uses Schnorr signatures for authentication using a hardcoded public key. use dep::aztec::macros::aztec; @@ -84,21 +84,21 @@ pub contract SchnorrHardcodedAccount { } } ``` -> Source code: noir-projects/noir-contracts/contracts/account/schnorr_hardcoded_account_contract/src/main.nr#L1-L55 +> Source code: noir-projects/noir-contracts/contracts/account/schnorr_hardcoded_account_contract/src/main.nr#L1-L55 For this to compile, you will need to add the following dependencies to your `Nargo.toml`: ```toml [dependencies] -aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/aztec" } -authwit = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/authwit" } +aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/aztec" } +authwit = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/authwit" } schnorr = { git = "https://github.com/noir-lang/schnorr", tag = "v0.1.1" } ``` The important part of this contract is the `entrypoint` function, which will be the first function executed in any transaction originated from this account. This function has two main responsibilities: authenticating the transaction and executing calls. It receives a `payload` with the list of function calls to execute, and requests a corresponding authentication witness from an oracle to validate it. Authentication witnesses are used for authorizing actions for an account, whether it is just checking a signature, like in this case, or granting authorization for another account to act on an accounts behalf (e.g. token approvals). You will find this logic implemented in the `AccountActions` module, which use the `AppPayload` and `FeePayload` structs: -```rust title="entrypoint" showLineNumbers +```rust title="entrypoint" showLineNumbers pub fn entrypoint(self, app_payload: AppPayload, fee_payload: FeePayload, cancellable: bool) { let valid_fn = self.is_valid_impl; @@ -118,20 +118,20 @@ pub fn entrypoint(self, app_payload: AppPayload, fee_payload: FeePayload, cancel } } ``` -> Source code: noir-projects/aztec-nr/authwit/src/account.nr#L40-L59 +> Source code: noir-projects/aztec-nr/authwit/src/account.nr#L40-L59 -```rust title="app-payload-struct" showLineNumbers +```rust title="app-payload-struct" showLineNumbers #[derive(Serialize)] pub struct AppPayload { function_calls: [FunctionCall; ACCOUNT_MAX_CALLS], pub nonce: Field, } ``` -> Source code: noir-projects/aztec-nr/authwit/src/entrypoint/app.nr#L19-L25 +> Source code: noir-projects/aztec-nr/authwit/src/entrypoint/app.nr#L19-L25 -```rust title="fee-payload-struct" showLineNumbers +```rust title="fee-payload-struct" showLineNumbers #[derive(Serialize)] pub struct FeePayload { function_calls: [FunctionCall; MAX_FEE_FUNCTION_CALLS], @@ -139,7 +139,7 @@ pub struct FeePayload { is_fee_payer: bool, } ``` -> Source code: noir-projects/aztec-nr/authwit/src/entrypoint/fee.nr#L17-L24 +> Source code: noir-projects/aztec-nr/authwit/src/entrypoint/fee.nr#L17-L24 :::info @@ -148,7 +148,7 @@ Using the `AccountActions` module and the payload structs is not mandatory. You The `AccountActions` module provides default implementations for most of the account contract methods needed, but it requires a function for validating an auth witness. In this function you will customize how your account validates an action: whether it is using a specific signature scheme, a multi-party approval, a password, etc. -```rust title="is-valid" showLineNumbers +```rust title="is-valid" showLineNumbers #[contract_library_method] fn is_valid_impl(_context: &mut PrivateContext, outer_hash: Field) -> bool { // Load auth witness and format as an u8 array @@ -165,7 +165,7 @@ fn is_valid_impl(_context: &mut PrivateContext, outer_hash: Field) -> bool { schnorr::verify_signature(public_key, signature, outer_hash.to_be_bytes::<32>()) } ``` -> Source code: noir-projects/noir-contracts/contracts/account/schnorr_hardcoded_account_contract/src/main.nr#L37-L53 +> Source code: noir-projects/noir-contracts/contracts/account/schnorr_hardcoded_account_contract/src/main.nr#L37-L53 For our account contract, we will take the hash of the action to authorize, request the corresponding auth witness from the oracle, and validate it against our hardcoded public key. If the signature is correct, we authorize the action. @@ -190,7 +190,7 @@ A side-effect of not having nonces at the protocol level is that it is not possi Now that we have a valid account contract, we need to write the typescript glue code that will take care of formatting and authenticating transactions so they can be processed by our contract, as well as deploying the contract during account setup. This takes the form of implementing the `AccountContract` interface from `@aztec/aztec.js`: -```typescript title="account-contract-interface" showLineNumbers +```typescript title="account-contract-interface" showLineNumbers /** * An account contract instance. Knows its artifact, deployment arguments, how to create * transaction execution requests out of function calls, and how to authorize actions. @@ -231,12 +231,12 @@ export interface AccountContract { getAuthWitnessProvider(address: CompleteAddress): AuthWitnessProvider; } ``` -> Source code: yarn-project/aztec.js/src/account/account_contract.ts#L10-L50 +> Source code: yarn-project/aztec.js/src/account/account_contract.ts#L10-L50 However, if you are using the default `AccountActions` module, then you can leverage the `DefaultAccountContract` class from `@aztec/accounts` and just implement the logic for generating an auth witness that matches the one you wrote in Noir: -```typescript title="account-contract" showLineNumbers +```typescript title="account-contract" showLineNumbers const PRIVATE_KEY = GrumpkinScalar.fromHexString('0xd35d743ac0dfe3d6dbe6be8c877cb524a00ab1e3d52d7bada095dfc8894ccfa'); /** Account contract implementation that authenticates txs using Schnorr signatures. */ @@ -266,7 +266,7 @@ class SchnorrHardcodedKeyAccountContract extends DefaultAccountContract { } } ``` -> Source code: yarn-project/end-to-end/src/guides/writing_an_account_contract.test.ts#L17-L46 +> Source code: yarn-project/end-to-end/src/guides/writing_an_account_contract.test.ts#L17-L46 As you can see in the snippet above, to fill in this base class, we need to define three things: @@ -287,7 +287,7 @@ Let's try creating a new account backed by our account contract, and interact wi To create and deploy the account, we will use the `AccountManager` class, which takes an instance of an Private Execution Environment (PXE), a [privacy private key](../../../../aztec/concepts/accounts/keys.md#incoming-viewing-keys), and an instance of our `AccountContract` class: -```typescript title="account-contract-deploy" showLineNumbers +```typescript title="account-contract-deploy" showLineNumbers const secretKey = Fr.random(); const account = await AccountManager.create(pxe, secretKey, new SchnorrHardcodedKeyAccountContract()); @@ -303,12 +303,12 @@ if (await account.isDeployable()) { const wallet = await account.getWallet(); const address = wallet.getAddress(); ``` -> Source code: yarn-project/end-to-end/src/guides/writing_an_account_contract.test.ts#L60-L75 +> Source code: yarn-project/end-to-end/src/guides/writing_an_account_contract.test.ts#L60-L75 Note that we used a funded wallet to deploy the account contract and pay for the transaction fee. The new account doesn't have any funds yet. We will continue using the funded wallet to deploy the token contract: -```typescript title="token-contract-deploy" showLineNumbers +```typescript title="token-contract-deploy" showLineNumbers const token = await TokenContract.deploy(fundedWallet, fundedWallet.getAddress(), 'TokenName', 'TokenSymbol', 18) .send() .deployed(); @@ -321,14 +321,14 @@ await token.methods.mint_to_private(from, address, mintAmount).send().wait(); const balance = await token.methods.balance_of_private(address).simulate(); logger.info(`Balance of wallet is now ${balance}`); ``` -> Source code: yarn-project/end-to-end/src/guides/writing_an_account_contract.test.ts#L78-L90 +> Source code: yarn-project/end-to-end/src/guides/writing_an_account_contract.test.ts#L78-L90 If we run this, we get `Balance of wallet is now 150`, which shows that the `mint` call was successfully executed for our account contract. To make sure that we are actually validating the provided signature in our account contract, we can try signing with a different key. To do this, we will set up a new `Account` instance pointing to the contract we already deployed but using a wrong signing key: -```typescript title="account-contract-fails" showLineNumbers +```typescript title="account-contract-fails" showLineNumbers const wrongKey = GrumpkinScalar.random(); const wrongAccountContract = new SchnorrHardcodedKeyAccountContract(wrongKey); const wrongAccount = await AccountManager.create(pxe, secretKey, wrongAccountContract, account.salt); @@ -341,7 +341,7 @@ try { logger.info(`Failed to send tx: ${err}`); } ``` -> Source code: yarn-project/end-to-end/src/guides/writing_an_account_contract.test.ts#L93-L105 +> Source code: yarn-project/end-to-end/src/guides/writing_an_account_contract.test.ts#L93-L105 Lo and behold, we get `Error: Assertion failed: 'verification == true'` when running the snippet above, pointing to the line in our account contract where we verify the Schnorr signature. @@ -350,7 +350,7 @@ Lo and behold, we get `Error: Assertion failed: 'verification == true'` when run ### Optional: Learn more about concepts mentioned here -- [ECDSA signer account contract (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/noir-projects/noir-contracts/contracts/ecdsa_account_contract/src/main.nr) -- [Schnorr signer account contract (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.3/noir-projects/noir-contracts/contracts/account/schnorr_account_contract) +- [ECDSA signer account contract (GitHub link)](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/noir-projects/noir-contracts/contracts/ecdsa_account_contract/src/main.nr) +- [Schnorr signer account contract (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.4/noir-projects/noir-contracts/contracts/account/schnorr_account_contract) - [Account abstraction](../../../../aztec/concepts/accounts/index.md#account-abstraction-aa) - [Authentication witness](../../../../aztec/concepts/advanced/authwit.md) diff --git a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/first_fees.md b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/first_fees.md index db8116b1b4aa..aa4bc295b6b3 100644 --- a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/first_fees.md +++ b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/first_fees.md @@ -194,7 +194,7 @@ aztec-wallet register-contract $SPONSORED_FPC_ADDRESS SponsoredFPC --salt 0 --fr aztec-wallet deploy-account --from main --payment method=fpc-sponsored,fpc=$SPONSORED_FPC_ADDRESS ``` -The equivalent using aztec.js - get sponsored fpc address (helper functions [here](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/yarn-project/aztec/src/sandbox/sponsored_fpc.ts)) and use payment method: +The equivalent using aztec.js - get sponsored fpc address (helper functions [here](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/yarn-project/aztec/src/sandbox/sponsored_fpc.ts)) and use payment method: ```javascript import { getSponsoredFPCInstance } from "../src/utils/sponsored_fpc.js"; // helper functions linked above @@ -333,7 +333,7 @@ aztec-wallet deploy-account --from accBFJ --payment method=fee_juice,claim The equivalent using aztec.js - bridge fee juice, (pass two txs), create and use payment method: -(See also the [aztec-wallet](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/yarn-project/cli-wallet/src/cmds/bridge_fee_juice.ts#L32) implementation to initialise a fee juice portal manager) +(See also the [aztec-wallet](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/yarn-project/cli-wallet/src/cmds/bridge_fee_juice.ts#L32) implementation to initialise a fee juice portal manager) ```javascript import { @@ -536,7 +536,7 @@ Please refer to the snippets in the sections above, and report any discrepancies - [`aztec` CLI tool](../../reference/environment_reference/cli_reference) - [`aztec-wallet` CLI tool](../../reference/environment_reference/cli_wallet_reference) -- [`aztec.js` source](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/yarn-project/aztec.js) +- [`aztec.js` source](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/yarn-project/aztec.js) - [Glossary](../../../glossary) - Search bar and AI above - Tags below :) diff --git a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/aztecjs-getting-started.md b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/aztecjs-getting-started.md index d68ab8f63658..c74c857db22c 100644 --- a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/aztecjs-getting-started.md +++ b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/aztecjs-getting-started.md @@ -15,7 +15,7 @@ This tutorial is for the sandbox and will need adjustments if deploying to testn ## Prerequisites -- A running Aztec sandbox at version 0.87.3. Install with `aztec-up 0.87.3`. +- A running Aztec sandbox at version 0.87.4. Install with `aztec-up 0.87.4`. ## Set up the project @@ -40,7 +40,7 @@ mkdir src 3. Add necessary yarn packages ```sh -yarn add @aztec/aztec.js@0.87.3 @aztec/accounts@0.87.3 @aztec/noir-contracts.js@0.87.3 typescript @types/node +yarn add @aztec/aztec.js@0.87.4 @aztec/accounts@0.87.4 @aztec/noir-contracts.js@0.87.4 typescript @types/node ``` :::note Match tool and dependency versions @@ -208,7 +208,7 @@ Great! The Sandbox is running and we are able to interact with it. The sandbox is preloaded with multiple accounts so you don't have to sit and create them. Let's load these accounts. Add this code to the `main()` function in `index.ts` below the code that's there: -```typescript title="load_accounts" showLineNumbers +```typescript title="load_accounts" showLineNumbers ////////////// LOAD SOME ACCOUNTS FROM THE SANDBOX ////////////// // The sandbox comes with a set of created accounts. Load them const accounts = await getDeployedTestAccountsWallets(pxe); @@ -219,7 +219,7 @@ const bob = bobWallet.getAddress(); logger.info(`Loaded alice's account at ${alice.toString()}`); logger.info(`Loaded bob's account at ${bob.toString()}`); ``` -> Source code: yarn-project/end-to-end/src/composed/e2e_sandbox_example.test.ts#L110-L120 +> Source code: yarn-project/end-to-end/src/composed/e2e_sandbox_example.test.ts#L110-L120 An explanation on accounts on Aztec can be found [here](../../../../aztec/concepts/accounts/index.md). @@ -228,14 +228,14 @@ An explanation on accounts on Aztec can be found [here](../../../../aztec/concep Now that we have our accounts loaded, let's move on to deploy our pre-compiled token smart contract. You can find the full code for the contract [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/master/noir-projects/noir-contracts/contracts/app/token_contract/src). Add this to `index.ts` below the code you added earlier: -```typescript title="Deployment" showLineNumbers +```typescript title="Deployment" showLineNumbers ////////////// DEPLOY OUR TOKEN CONTRACT ////////////// const initialSupply = 1_000_000n; const tokenContractAlice = await deployToken(aliceWallet, initialSupply, logger); ``` -> Source code: yarn-project/end-to-end/src/composed/e2e_sandbox_example.test.ts#L122-L128 +> Source code: yarn-project/end-to-end/src/composed/e2e_sandbox_example.test.ts#L122-L128 `yarn start` will now give something like this: @@ -263,7 +263,7 @@ A token contract wouldn't be very useful if you aren't able to query the balance Call the `balance_of_private` function using the following code (paste this): -```typescript title="Balance" showLineNumbers +```typescript title="Balance" showLineNumbers ////////////// QUERYING THE TOKEN BALANCE FOR EACH ACCOUNT ////////////// @@ -277,7 +277,7 @@ logger.info(`Alice's balance ${aliceBalance}`); let bobBalance = await tokenContractBob.methods.balance_of_private(bob).simulate(); logger.info(`Bob's balance ${bobBalance}`); ``` -> Source code: yarn-project/end-to-end/src/composed/e2e_sandbox_example.test.ts#L133-L147 +> Source code: yarn-project/end-to-end/src/composed/e2e_sandbox_example.test.ts#L133-L147 Running now should yield output: @@ -313,7 +313,7 @@ Now lets transfer some funds from Alice to Bob by calling the `transfer` functio Here is the Typescript code to call the `transfer` function, add this to your `index.ts` at the bottom of the `main` function: -```typescript title="Transfer" showLineNumbers +```typescript title="Transfer" showLineNumbers ////////////// TRANSFER FUNDS FROM ALICE TO BOB ////////////// // We will now transfer tokens from ALice to Bob @@ -328,7 +328,7 @@ logger.info(`Alice's balance ${aliceBalance}`); bobBalance = await tokenContractBob.methods.balance_of_private(bob).simulate(); logger.info(`Bob's balance ${bobBalance}`); ``` -> Source code: yarn-project/end-to-end/src/composed/e2e_sandbox_example.test.ts#L152-L166 +> Source code: yarn-project/end-to-end/src/composed/e2e_sandbox_example.test.ts#L152-L166 Our output should now look like this: @@ -356,7 +356,7 @@ This function starts as private to set up the creation of a [partial note](../.. Let's now use these functions to mint some tokens to Bob's account using Typescript, add this to `index.ts`: -```typescript title="Mint" showLineNumbers +```typescript title="Mint" showLineNumbers ////////////// MINT SOME MORE TOKENS TO BOB'S ACCOUNT ////////////// // Now mint some further funds for Bob @@ -374,7 +374,7 @@ logger.info(`Alice's balance ${aliceBalance}`); bobBalance = await tokenContractBob.methods.balance_of_private(bob).simulate(); logger.info(`Bob's balance ${bobBalance}`); ``` -> Source code: yarn-project/end-to-end/src/composed/e2e_sandbox_example.test.ts#L171-L188 +> Source code: yarn-project/end-to-end/src/composed/e2e_sandbox_example.test.ts#L171-L188 Our complete output should now be something like: diff --git a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/simple_dapp/0_project_setup.md b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/simple_dapp/0_project_setup.md index 3b424910dba6..7da115e8a025 100644 --- a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/simple_dapp/0_project_setup.md +++ b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/simple_dapp/0_project_setup.md @@ -12,10 +12,10 @@ We'll use [`yarn`](https://yarnpkg.com/) for managing our project and dependenci node -v ``` -and ensure that you are running sandbox version 0.87.3. +and ensure that you are running sandbox version 0.87.4. ```bash -aztec-up 0.87.3 +aztec-up 0.87.4 ``` 2. Create a new folder and initialize a new project. @@ -29,7 +29,7 @@ yarn init -yp 3. Add the `aztec.js` and `accounts` libraries as dependencies. Also add `noir-contracts.js` for quick use of example contracts: ```sh -yarn add @aztec/aztec.js@0.87.3 @aztec/accounts@0.87.3 @aztec/noir-contracts.js@0.87.3 +yarn add @aztec/aztec.js@0.87.4 @aztec/accounts@0.87.4 @aztec/noir-contracts.js@0.87.4 ``` and yarn config: diff --git a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/simple_dapp/1_pxe_service.md b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/simple_dapp/1_pxe_service.md index 7147f655bab0..aeda32a13965 100644 --- a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/simple_dapp/1_pxe_service.md +++ b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/simple_dapp/1_pxe_service.md @@ -19,7 +19,7 @@ To test the connection works, we'll request and print the node's chain id. Let's create our first file `src/index.mjs` with the following contents: -```javascript title="all" showLineNumbers +```javascript title="all" showLineNumbers import { createPXEClient } from '@aztec/aztec.js'; const { PXE_URL = 'http://localhost:8080' } = process.env; @@ -35,7 +35,7 @@ main().catch(err => { process.exit(1); }); ``` -> Source code: yarn-project/end-to-end/src/sample-dapp/connect.mjs#L1-L16 +> Source code: yarn-project/end-to-end/src/sample-dapp/connect.mjs#L1-L16 Make sure the [Sandbox is running](../../../../getting_started.md) and run the example @@ -59,13 +59,13 @@ Should the above fail due to a connection error, make sure the Sandbox is runnin In sandbox PXE comes with a set of pre-initialized accounts that you can use from your app. Let's try loading the accounts: -```javascript title="showAccounts" showLineNumbers +```javascript title="showAccounts" showLineNumbers async function showAccounts(pxe) { const accounts = await pxe.getRegisteredAccounts(); console.log(`User accounts:\n${accounts.map(a => a.address).join('\n')}`); } ``` -> Source code: yarn-project/end-to-end/src/sample-dapp/index.mjs#L12-L17 +> Source code: yarn-project/end-to-end/src/sample-dapp/index.mjs#L12-L17 Call the `showAccounts` function from `main`, run again the above, and you should see something like: diff --git a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/simple_dapp/2_contract_deployment.md b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/simple_dapp/2_contract_deployment.md index e2b8b08e5ebf..9995ad14c146 100644 --- a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/simple_dapp/2_contract_deployment.md +++ b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/simple_dapp/2_contract_deployment.md @@ -19,15 +19,15 @@ Then, open the `contracts/token/Nargo.toml` configuration file, and add the `azt ```toml [dependencies] -aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/aztec" } -authwit = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/authwit"} -uint_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/uint-note" } -compressed_string = {git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="noir-projects/aztec-nr/compressed-string"} +aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/aztec" } +authwit = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/authwit"} +uint_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/uint-note" } +compressed_string = {git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="noir-projects/aztec-nr/compressed-string"} ``` Last, copy-paste the code from the `Token` contract into `contracts/token/main.nr`: -```rust title="token_all" showLineNumbers +```rust title="token_all" showLineNumbers mod types; mod test; @@ -391,7 +391,9 @@ pub contract Token { } /// This function exists separately from `prepare_private_balance_increase` solely as an optimization as it allows - /// us to have it inlined in the `transfer_to_private` function which results in one fewer kernel iteration. + /// us to have it inlined in the `transfer_to_private` function which results in one fewer kernel iteration. Note + /// that in this case we don't pass `completer` as an argument to this function because in all the callsites we + /// want to use the message sender as the completer anyway. /// /// TODO(#9180): Consider adding macro support for functions callable both as an entrypoint and as an internal /// function. @@ -408,22 +410,9 @@ pub contract Token { context, to, from, + context.msg_sender(), ); - // We can't simply return the partial note because we won't be able to later on verify that it was created - // correctly (e.g. that the storage slot corresponds to the owner, and that we're using the balance set and not - // a different one) once this information is hidden in the partial note commitment. We also want to verify that - // only the caller of this function can complete the partial note. - - // We achieve the above by storing a flag in public storage under a slot index equal to its - // `validity_commitment`. This commitment contains all the necessary information to verify the completer and - // to validate the partial note. - let validity_commitment = partial_note.compute_validity_commitment(context.msg_sender()); - - Token::at(context.this_address()) - ._set_uint_partial_note_validity(validity_commitment) - .enqueue(context); - partial_note } @@ -483,17 +472,8 @@ pub contract Token { let from_balance = storage.public_balances.at(from_and_completer).read().sub(amount); storage.public_balances.at(from_and_completer).write(from_balance); - // We verify that the partial note we're completing is valid (i.e. completer is correct, it uses the correct - // state variable's storage slot, and it is internally consistent). We *could* clear the storage since each - // partial note should only be used once, but since the AVM offers no gas refunds for doing so this would just - // make the transaction be more expensive. We don't worry about the validity commitment being checked against - // multiple times because it is up to the caller to ensure that a partial note is used only once (see function - // docs of `finalize_transfer_to_private`). - assert( - context.storage_read(partial_note.compute_validity_commitment(from_and_completer)), - "Invalid partial note or completer", - ); - partial_note.complete(amount, context); + // We finalize the transfer by completing the partial note. + partial_note.complete(context, from_and_completer, amount); } /// Mints token `amount` to a private balance of `to`. Message sender has to have minter permissions (checked @@ -574,25 +554,8 @@ pub contract Token { let supply = storage.total_supply.read().add(amount); storage.total_supply.write(supply); - // We verify that the partial note we're completing is valid (i.e. it uses the correct state variable's storage - // slot, and it is internally consistent). We *could* clear the storage since each partial note should only be - // used once, but since the AVM offers no gas refunds for doing so this would just make the transaction be more - // expensive. - assert( - context.storage_read(partial_note.compute_validity_commitment(completer)), - "Invalid partial note or completer", - ); - partial_note.complete(amount, context); - } - - #[public] - #[internal] - fn _set_uint_partial_note_validity(validity_commitment: Field) { - // We store the partial note validity flag in a slot equal to its validity commitment. This is safe because - // the commitment is computed using a generator different from the one used to compute storage slots, so there - // can be no collisions. We could consider storing all pending partial notes in e.g. some array, but ultimately - // this is pointless: all we need to verify is that the note is valid. - context.storage_write(validity_commitment, true); + // We finalize the transfer by completing the partial note. + partial_note.complete(context, completer, amount); } /// Internal /// @@ -628,7 +591,7 @@ pub contract Token { } } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L1-L684 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L1-L647 ### Helper files @@ -637,11 +600,11 @@ pub contract Token { Remove the `mod test;` line from `contracts/token/src/main.nr` as we will not be using TXE tests in this tutorial. ::: -The `Token` contract also requires some helper files. You can view the files [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.3/noir-projects/noir-contracts/contracts/app/token_contract/src). Copy the `types.nr` and the `types` folder into `contracts/token/src`. +The `Token` contract also requires some helper files. You can view the files [here (GitHub link)](https://github.com/AztecProtocol/aztec-packages/tree/v0.87.4/noir-projects/noir-contracts/contracts/app/token_contract/src). Copy the `types.nr` and the `types` folder into `contracts/token/src`. Add this `balance_set.nr` file at `token/src/types/balance_set.nr`. -```rust title="balance_set" showLineNumbers +```rust title="balance_set" showLineNumbers use dep::aztec::{ context::{PrivateContext, UtilityContext}, note::{ @@ -773,7 +736,7 @@ pub fn preprocess_notes_min_sum( selected } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/types/balance_set.nr#L1-L136 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/types/balance_set.nr#L1-L136 ## Compile your contract diff --git a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/simple_dapp/3_contract_interaction.md b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/simple_dapp/3_contract_interaction.md index 8a990697b842..b390af92f7bd 100644 --- a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/simple_dapp/3_contract_interaction.md +++ b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/simple_dapp/3_contract_interaction.md @@ -8,13 +8,13 @@ In this section, we'll write the logic in our app that will interact with the co Let's start by showing our user's private balance for the token across their accounts. To do this, we can leverage the `balance_of_private` utility function of the token contract: -```rust title="balance_of_private" showLineNumbers +```rust title="balance_of_private" showLineNumbers #[utility] pub(crate) unconstrained fn balance_of_private(owner: AztecAddress) -> u128 { storage.balances.at(owner).balance_of() } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L676-L681 +> Source code: noir-projects/noir-contracts/contracts/app/token_contract/src/main.nr#L639-L644 :::info @@ -50,7 +50,7 @@ import { getToken } from './contracts.mjs'; and query the private balance for each of the user accounts. To query a function, without sending a transaction, use the `simulate` function of the method: -```javascript title="showPrivateBalances" showLineNumbers +```javascript title="showPrivateBalances" showLineNumbers async function showPrivateBalances(pxe) { const [owner] = await getInitialTestAccountsWallets(pxe); const token = await getToken(owner); @@ -64,7 +64,7 @@ async function showPrivateBalances(pxe) { } } ``` -> Source code: yarn-project/end-to-end/src/sample-dapp/index.mjs#L19-L32 +> Source code: yarn-project/end-to-end/src/sample-dapp/index.mjs#L19-L32 Call the function in `main` and run this with `node src/index.mjs` and you should now see the following output: @@ -79,7 +79,7 @@ Balance of 0x0e1f60e8566e2c6d32378bdcadb7c63696e853281be798c107266b8c3a88ea9b: 0 Before we can transfer tokens, we need to mint some tokens to our user accounts. Add the following function to `src/index.mjs`: -```javascript title="mintPrivateFunds" showLineNumbers +```javascript title="mintPrivateFunds" showLineNumbers async function mintPrivateFunds(pxe) { const [ownerWallet] = await getInitialTestAccountsWallets(pxe); const token = await getToken(ownerWallet); @@ -94,7 +94,7 @@ async function mintPrivateFunds(pxe) { await showPrivateBalances(pxe); } ``` -> Source code: yarn-project/end-to-end/src/sample-dapp/index.mjs#L34-L48 +> Source code: yarn-project/end-to-end/src/sample-dapp/index.mjs#L34-L48 Call the function in `main`, run the script and after printing the balances of each account it will then privately mint tokens. After that completes, you should then see 20 tokens in the balance of the first account. @@ -117,7 +117,7 @@ import { getInitialTestAccountsWallets } from "@aztec/accounts/testing"; We'll use one of these wallets to initialize the `TokenContract` instance that represents our private token contract, so every transaction sent through it will be sent through that wallet. -```javascript title="transferPrivateFunds" showLineNumbers +```javascript title="transferPrivateFunds" showLineNumbers async function transferPrivateFunds(pxe) { const [owner, recipient] = await getInitialTestAccountsWallets(pxe); const token = await getToken(owner); @@ -130,7 +130,7 @@ async function transferPrivateFunds(pxe) { await showPrivateBalances(pxe); } ``` -> Source code: yarn-project/end-to-end/src/sample-dapp/index.mjs#L50-L62 +> Source code: yarn-project/end-to-end/src/sample-dapp/index.mjs#L50-L62 Let's go step-by-step on this snippet. We first get wallets for two of the Sandbox accounts, and name them `owner` and `recipient`. Then, we initialize the private token `Contract` instance using the `owner` wallet, meaning that any transactions sent through it will have the `owner` as sender. @@ -162,7 +162,7 @@ At the time of this writing, there are no events emitted when new private notes While [private and public state](../../../../../aztec/concepts/storage/index.md) are fundamentally different, the API for working with private and public functions and state from `aztec.js` is equivalent. To query the balance in public tokens for our user accounts, we can just call the `balance_of_public` view function in the contract: -```javascript title="showPublicBalances" showLineNumbers +```javascript title="showPublicBalances" showLineNumbers async function showPublicBalances(pxe) { const [owner] = await getInitialTestAccountsWallets(pxe); const token = await getToken(owner); @@ -176,7 +176,7 @@ async function showPublicBalances(pxe) { } } ``` -> Source code: yarn-project/end-to-end/src/sample-dapp/index.mjs#L64-L77 +> Source code: yarn-project/end-to-end/src/sample-dapp/index.mjs#L64-L77 :::info @@ -186,7 +186,7 @@ Since this we are working with public balances, we can now query the balance for Here, since the token contract does not mint any initial funds upon deployment, the balances for all of our user's accounts will be zero. But we can send a transaction to mint tokens, using very similar code to the one for sending private funds: -```javascript title="mintPublicFunds" showLineNumbers +```javascript title="mintPublicFunds" showLineNumbers async function mintPublicFunds(pxe) { const [owner] = await getInitialTestAccountsWallets(pxe); const token = await getToken(owner); @@ -205,7 +205,7 @@ async function mintPublicFunds(pxe) { for (const log of textLogs) console.log(`Log emitted: ${log}`); } ``` -> Source code: yarn-project/end-to-end/src/sample-dapp/index.mjs#L79-L99 +> Source code: yarn-project/end-to-end/src/sample-dapp/index.mjs#L79-L99 And get the expected results: diff --git a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/simple_dapp/4_testing.md b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/simple_dapp/4_testing.md index 7e3e66a926c4..2c2dfff6b687 100644 --- a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/simple_dapp/4_testing.md +++ b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/simple_dapp/4_testing.md @@ -37,7 +37,7 @@ describe("token contract", () => { Let's set up our test suite. We'll make sure the Sandbox is running, create two fresh accounts to test with, and deploy an instance of our contract. `aztec.js` provides the helper functions we need to do this: -```javascript title="setup" showLineNumbers +```javascript title="setup" showLineNumbers let owner, recipient, token; beforeAll(async () => { @@ -50,7 +50,7 @@ beforeAll(async () => { await token.methods.mint_to_private(owner.getAddress(), owner.getAddress(), initialBalance).send().wait(); }, 120_000); ``` -> Source code: yarn-project/end-to-end/src/sample-dapp/index.test.mjs#L13-L25 +> Source code: yarn-project/end-to-end/src/sample-dapp/index.test.mjs#L13-L25 :::tip @@ -61,7 +61,7 @@ Instead of creating new accounts in our test suite, we can use the ones already Now that we have a working test environment, we can write our first test for exercising the `transfer` function on the token contract. We will use the same `aztec.js` methods we used when building our dapp: -```javascript title="test" showLineNumbers +```javascript title="test" showLineNumbers it('increases recipient funds on transfer', async () => { expect(await token.withWallet(recipient).methods.balance_of_private(recipient.getAddress()).simulate()).toEqual(0n); await token.methods.transfer(recipient.getAddress(), 20).send().wait(); @@ -70,7 +70,7 @@ it('increases recipient funds on transfer', async () => { ); }, 30_000); ``` -> Source code: yarn-project/end-to-end/src/sample-dapp/index.test.mjs#L27-L35 +> Source code: yarn-project/end-to-end/src/sample-dapp/index.test.mjs#L27-L35 In this example, we assert that the `recipient`'s balance is increased by the amount transferred. We could also test that the `owner`'s funds are decremented by the same amount, or that a transaction that attempts to send more funds than those available would fail. diff --git a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/simple_dapp/index.md b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/simple_dapp/index.md index 8827dab629b7..b70d9c3d7865 100644 --- a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/simple_dapp/index.md +++ b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/simple_dapp/index.md @@ -11,7 +11,7 @@ This tutorial is for the sandbox and will need adjustments if deploying to testn This tutorial will focus on environment setup, including creating accounts and deployments, as well as interacting with your contracts. It will not cover [how to write contracts in Noir](../../../../../aztec/smart_contracts_overview.md). -The full code for this tutorial is [available on the `aztec-packages` repository](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/yarn-project/end-to-end/src/sample-dapp). +The full code for this tutorial is [available on the `aztec-packages` repository](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/yarn-project/end-to-end/src/sample-dapp). ## Dependencies diff --git a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/token_bridge.md b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/token_bridge.md index 29523687a0ca..c7270e4c641f 100644 --- a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/token_bridge.md +++ b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/token_bridge.md @@ -20,7 +20,7 @@ The first half of this page reviews the process and contracts for bridging token - sending tokens from L2 back to L1 - withdrawing tokens from the L1 portal -This tutorial is compatible with the Aztec version `v0.87.3`. Install the correct version with `aztec-up -v 0.87.3`. Or if you'd like to use a different version, you can find the relevant tutorial by clicking the version dropdown at the top of the page. +This tutorial is compatible with the Aztec version `v0.87.4`. Install the correct version with `aztec-up -v 0.87.4`. Or if you'd like to use a different version, you can find the relevant tutorial by clicking the version dropdown at the top of the page. ## Components @@ -75,7 +75,7 @@ Note that because L1 is public, everyone can inspect and figure out the contentH #### `depositToAztecPublic` (TokenPortal.sol) -```solidity title="deposit_public" showLineNumbers +```solidity title="deposit_public" showLineNumbers /** * @notice Deposit funds into the portal and adds an L2 message which can only be consumed publicly on Aztec * @param _to - The aztec address of the recipient @@ -87,12 +87,12 @@ function depositToAztecPublic(bytes32 _to, uint256 _amount, bytes32 _secretHash) external returns (bytes32, uint256) ``` -> Source code: l1-contracts/test/portals/TokenPortal.sol#L55-L66 +> Source code: l1-contracts/test/portals/TokenPortal.sol#L55-L66 #### `depositToAztecPrivate` (TokenPortal.sol) -```solidity title="deposit_private" showLineNumbers +```solidity title="deposit_private" showLineNumbers /** * @notice Deposit funds into the portal and adds an L2 message which can only be consumed privately on Aztec * @param _amount - The amount to deposit @@ -103,7 +103,7 @@ function depositToAztecPrivate(uint256 _amount, bytes32 _secretHashForL2MessageC external returns (bytes32, uint256) ``` -> Source code: l1-contracts/test/portals/TokenPortal.sol#L89-L99 +> Source code: l1-contracts/test/portals/TokenPortal.sol#L89-L99 **So how do we privately consume the message on Aztec?** @@ -116,7 +116,7 @@ The previous code snippets moved funds to the bridge and created a L1->L2 messag This happens inside the `TokenBridge` contract on Aztec. -```rust title="claim_public" showLineNumbers +```rust title="claim_public" showLineNumbers // Consumes a L1->L2 message and calls the token contract to mint the appropriate amount publicly #[public] fn claim_public(to: AztecAddress, amount: u128, secret: Field, message_leaf_index: Field) { @@ -131,7 +131,7 @@ fn claim_public(to: AztecAddress, amount: u128, secret: Field, message_leaf_inde Token::at(config.token).mint_to_public(to, amount).call(&mut context); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_bridge_contract/src/main.nr#L57-L71 +> Source code: noir-projects/noir-contracts/contracts/app/token_bridge_contract/src/main.nr#L57-L71 What's happening here? @@ -154,7 +154,7 @@ For both the public and private flow, we use the same mechanism to determine the #### `exit_to_L1_public` (TokenBridge.nr) -```rust title="exit_to_l1_public" showLineNumbers +```rust title="exit_to_l1_public" showLineNumbers // Burns the appropriate amount of tokens and creates a L2 to L1 withdraw message publicly // Requires `msg.sender` to give approval to the bridge to burn tokens on their behalf using witness signatures #[public] @@ -174,14 +174,14 @@ fn exit_to_l1_public( Token::at(config.token).burn_public(context.msg_sender(), amount, nonce).call(&mut context); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_bridge_contract/src/main.nr#L73-L92 +> Source code: noir-projects/noir-contracts/contracts/app/token_bridge_contract/src/main.nr#L73-L92 #### `exit_to_L1_private` (TokenBridge.nr) This function works very similarly to the public version, except here we burn user’s private notes. -```rust title="exit_to_l1_private" showLineNumbers +```rust title="exit_to_l1_private" showLineNumbers // Burns the appropriate amount of tokens and creates a L2 to L1 withdraw message privately // Requires `msg.sender` (caller of the method) to give approval to the bridge to burn tokens on their behalf using witness signatures #[private] @@ -205,7 +205,7 @@ fn exit_to_l1_private( Token::at(token).burn_private(context.msg_sender(), amount, nonce).call(&mut context); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/token_bridge_contract/src/main.nr#L125-L150 +> Source code: noir-projects/noir-contracts/contracts/app/token_bridge_contract/src/main.nr#L125-L150 Since this is a private method, it can't read what token is publicly stored. So instead the user passes a token address, and `_assert_token_is_same()` checks that this user provided address is same as the one in storage. @@ -218,7 +218,7 @@ A user must sign an approval message to let the contract burn tokens on their be After the transaction is completed on L2, the portal must call the outbox to successfully transfer funds to the user on L1. Like with deposits, things can be complex here. For example, what happens if the transaction was done on L2 to burn tokens but can’t be withdrawn to L1? Then the funds are lost forever! How do we prevent this? -```solidity title="token_portal_withdraw" showLineNumbers +```solidity title="token_portal_withdraw" showLineNumbers /** * @notice Withdraw funds from the portal * @dev Second part of withdraw, must be initiated from L2 first as it will consume a message from outbox @@ -258,7 +258,7 @@ function withdraw( underlying.transfer(_recipient, _amount); } ``` -> Source code: l1-contracts/test/portals/TokenPortal.sol#L122-L161 +> Source code: l1-contracts/test/portals/TokenPortal.sol#L122-L161 #### `token_portal_withdraw` (TokenPortal.sol) @@ -273,7 +273,7 @@ We call this pattern _designed caller_ which enables a new paradigm **where we c Let's run through the entire process of depositing, minting and withdrawing tokens in Typescript, so you can see how it works in practice. -Make sure you are using version v0.87.3 of the sandbox. Install with `aztec-up 0.87.3`. +Make sure you are using version v0.87.4 of the sandbox. Install with `aztec-up 0.87.4`. ### Prerequisites @@ -288,7 +288,7 @@ mkdir token-bridge-tutorial cd token-bridge-tutorial yarn init -y echo "nodeLinker: node-modules" > .yarnrc.yml -yarn add @aztec/aztec.js@0.87.3 @aztec/noir-contracts.js@0.87.3 @aztec/l1-artifacts@0.87.3 @aztec/accounts@0.87.3 @aztec/ethereum@0.87.3 @types/node typescript@^5.0.4 viem@^2.22.8 tsx +yarn add @aztec/aztec.js@0.87.4 @aztec/noir-contracts.js@0.87.4 @aztec/l1-artifacts@0.87.4 @aztec/accounts@0.87.4 @aztec/ethereum@0.87.4 @types/node typescript@^5.0.4 viem@^2.22.8 tsx touch tsconfig.json touch index.ts ``` @@ -336,7 +336,7 @@ You can run the script we will build in `index.ts` at any point with `yarn start Add the following imports to your `index.ts`: -```typescript title="imports" showLineNumbers +```typescript title="imports" showLineNumbers import { getInitialTestAccountsWallets } from '@aztec/accounts/testing'; import { EthAddress, @@ -361,14 +361,14 @@ import { TokenBridgeContract } from '@aztec/noir-contracts.js/TokenBridge'; import { getContract } from 'viem'; ``` -> Source code: yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts#L2-L27 +> Source code: yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts#L2-L27 ### Utility functions Add the following utility functions to your `index.ts` below the imports: -```typescript title="utils" showLineNumbers +```typescript title="utils" showLineNumbers const MNEMONIC = 'test test test test test test test test test test test junk'; const { ETHEREUM_HOSTS = 'http://localhost:8545' } = process.env; @@ -413,7 +413,7 @@ async function addMinter(l1TokenContract: EthAddress, l1TokenHandler: EthAddress await contract.write.addMinter([l1TokenHandler.toString()]); } ``` -> Source code: yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts#L28-L72 +> Source code: yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts#L28-L72 ### Sandbox Setup @@ -452,18 +452,18 @@ Run the script with `yarn start` and you should see the L1 contract addresses pr Add the following code to `index.ts` to deploy the L2 token contract: -```typescript title="deploy-l2-token" showLineNumbers +```typescript title="deploy-l2-token" showLineNumbers const l2TokenContract = await TokenContract.deploy(ownerWallet, ownerAztecAddress, 'L2 Token', 'L2', 18) .send() .deployed(); logger.info(`L2 token contract deployed at ${l2TokenContract.address}`); ``` -> Source code: yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts#L91-L96 +> Source code: yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts#L91-L96 Add the following code to `index.ts` to deploy the L1 token contract and set up the `L1TokenManager` (a utility class to interact with the L1 token contract): -```typescript title="deploy-l1-token" showLineNumbers +```typescript title="deploy-l1-token" showLineNumbers const l1TokenContract = await deployTestERC20(); logger.info('erc20 contract deployed'); @@ -472,12 +472,12 @@ await addMinter(l1TokenContract, feeAssetHandler); const l1TokenManager = new L1TokenManager(l1TokenContract, feeAssetHandler, l1Client, logger); ``` -> Source code: yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts#L99-L107 +> Source code: yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts#L99-L107 Add the following code to `index.ts` to deploy the L1 portal contract: -```typescript title="deploy-portal" showLineNumbers +```typescript title="deploy-portal" showLineNumbers const l1PortalContractAddress = await deployTokenPortal(); logger.info('L1 portal contract deployed'); @@ -487,12 +487,12 @@ const l1Portal = getContract({ client: l1Client, }); ``` -> Source code: yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts#L110-L119 +> Source code: yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts#L110-L119 Add the following code to `index.ts` to deploy the L2 bridge contract: -```typescript title="deploy-l2-bridge" showLineNumbers +```typescript title="deploy-l2-bridge" showLineNumbers const l2BridgeContract = await TokenBridgeContract.deploy( ownerWallet, l2TokenContract.address, @@ -502,7 +502,7 @@ const l2BridgeContract = await TokenBridgeContract.deploy( .deployed(); logger.info(`L2 token bridge contract deployed at ${l2BridgeContract.address}`); ``` -> Source code: yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts#L121-L130 +> Source code: yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts#L121-L130 Run `yarn start` to confirm that all of the contracts are deployed. @@ -511,15 +511,15 @@ Run `yarn start` to confirm that all of the contracts are deployed. Add the following code to `index.ts` to authorize the L2 bridge contract to mint tokens on the L2 token contract: -```typescript title="authorize-l2-bridge" showLineNumbers +```typescript title="authorize-l2-bridge" showLineNumbers await l2TokenContract.methods.set_minter(l2BridgeContract.address, true).send().wait(); ``` -> Source code: yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts#L133-L135 +> Source code: yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts#L133-L135 Add the following code to `index.ts` to set up the L1 portal contract and `L1TokenPortalManager` (a utility class to interact with the L1 portal contract): -```typescript title="setup-portal" showLineNumbers +```typescript title="setup-portal" showLineNumbers await l1Portal.write.initialize( [l1ContractAddresses.registryAddress.toString(), l1TokenContract.toString(), l2BridgeContract.address.toString()], {}, @@ -535,14 +535,14 @@ const l1PortalManager = new L1TokenPortalManager( logger, ); ``` -> Source code: yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts#L138-L153 +> Source code: yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts#L138-L153 ### Bridge tokens Add the following code to `index.ts` to bridge tokens from L1 to L2: -```typescript title="l1-bridge-public" showLineNumbers +```typescript title="l1-bridge-public" showLineNumbers const claim = await l1PortalManager.bridgeTokensPublic(ownerAztecAddress, MINT_AMOUNT, true); // Do 2 unrleated actions because @@ -550,7 +550,7 @@ const claim = await l1PortalManager.bridgeTokensPublic(ownerAztecAddress, MINT_A await l2TokenContract.methods.mint_to_public(ownerAztecAddress, 0n).send().wait(); await l2TokenContract.methods.mint_to_public(ownerAztecAddress, 0n).send().wait(); ``` -> Source code: yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts#L155-L162 +> Source code: yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts#L155-L162 We have to send two additional transactions because the network must process 2 blocks for the message to be processed by the archiver. We need to progress by 2 because there is a 1 block lag between when the message is sent to Inbox and when the subtree containing the message is included in the block. Then when it's included it becomes available for consumption in the next block. @@ -559,7 +559,7 @@ We have to send two additional transactions because the network must process 2 b Add the following code to `index.ts` to claim the tokens publicly on Aztec: -```typescript title="claim" showLineNumbers +```typescript title="claim" showLineNumbers await l2BridgeContract.methods .claim_public(ownerAztecAddress, MINT_AMOUNT, claim.claimSecret, claim.messageLeafIndex) .send() @@ -567,7 +567,7 @@ await l2BridgeContract.methods const balance = await l2TokenContract.methods.balance_of_public(ownerAztecAddress).simulate(); logger.info(`Public L2 balance of ${ownerAztecAddress} is ${balance}`); ``` -> Source code: yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts#L165-L172 +> Source code: yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts#L165-L172 Run `yarn start` to confirm that tokens are claimed on Aztec. @@ -576,7 +576,7 @@ Run `yarn start` to confirm that tokens are claimed on Aztec. Add the following code to `index.ts` to start the withdraw the tokens to L1: -```typescript title="setup-withdrawal" showLineNumbers +```typescript title="setup-withdrawal" showLineNumbers const withdrawAmount = 9n; const nonce = Fr.random(); @@ -590,14 +590,14 @@ const authwit = await ownerWallet.setPublicAuthWit( ); await authwit.send().wait(); ``` -> Source code: yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts#L176-L189 +> Source code: yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts#L176-L189 We have to send a public authwit to allow the bridge contract to burn tokens on behalf of the user. Add the following code to `index.ts` to start the withdraw process on Aztec: -```typescript title="l2-withdraw" showLineNumbers +```typescript title="l2-withdraw" showLineNumbers const l2ToL1Message = await l1PortalManager.getL2ToL1MessageLeaf( withdrawAmount, EthAddress.fromString(ownerEthAddress), @@ -612,12 +612,12 @@ const l2TxReceipt = await l2BridgeContract.methods const newL2Balance = await l2TokenContract.methods.balance_of_public(ownerAztecAddress).simulate(); logger.info(`New L2 balance of ${ownerAztecAddress} is ${newL2Balance}`); ``` -> Source code: yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts#L191-L205 +> Source code: yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts#L191-L205 Add the following code to `index.ts` to complete the withdraw process on L1: -```typescript title="l1-withdraw" showLineNumbers +```typescript title="l1-withdraw" showLineNumbers const [l2ToL1MessageIndex, siblingPath] = await pxe.getL2ToL1MembershipWitness( await pxe.getBlockNumber(), l2ToL1Message, @@ -632,7 +632,7 @@ await l1PortalManager.withdrawFunds( const newL1Balance = await l1TokenManager.getL1TokenBalance(ownerEthAddress); logger.info(`New L1 balance of ${ownerEthAddress} is ${newL1Balance}`); ``` -> Source code: yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts#L207-L221 +> Source code: yarn-project/end-to-end/src/composed/e2e_token_bridge_tutorial_test.test.ts#L207-L221 Run `yarn start` to run the script and see the entire process in action. diff --git a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/uniswap/e2e_tests.md b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/uniswap/e2e_tests.md index eb8d157498cf..cddbba6cd30c 100644 --- a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/uniswap/e2e_tests.md +++ b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/uniswap/e2e_tests.md @@ -5,7 +5,7 @@ sidebar_position: 3 ## Private flow test -```typescript title="uniswap_private" showLineNumbers +```typescript title="uniswap_private" showLineNumbers it('should uniswap trade on L1 from L2 funds privately (swaps WETH -> DAI)', async () => { const wethL1BeforeBalance = await wethCrossChainHarness.getL1BalanceOf(ownerEthAddress); @@ -189,12 +189,12 @@ it('should uniswap trade on L1 from L2 funds privately (swaps WETH -> DAI)', asy logger.info('DAI balance after swap : ', daiL2BalanceAfterSwap.toString()); }); ``` -> Source code: yarn-project/end-to-end/src/shared/uniswap_l1_l2.ts#L174-L357 +> Source code: yarn-project/end-to-end/src/shared/uniswap_l1_l2.ts#L174-L357 ## Public flow test -```typescript title="uniswap_public" showLineNumbers +```typescript title="uniswap_public" showLineNumbers // it('should uniswap trade on L1 from L2 funds publicly (swaps WETH -> DAI)', async () => { // const wethL1BeforeBalance = await wethCrossChainHarness.getL1BalanceOf(ownerEthAddress); @@ -428,6 +428,6 @@ it('should uniswap trade on L1 from L2 funds privately (swaps WETH -> DAI)', asy // logger.info('DAI balance after swap : ', daiL2BalanceAfterSwap.toString()); // }); ``` -> Source code: yarn-project/end-to-end/src/shared/uniswap_l1_l2.ts#L360-L593 +> Source code: yarn-project/end-to-end/src/shared/uniswap_l1_l2.ts#L360-L593 diff --git a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/uniswap/l1_contract.md b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/uniswap/l1_contract.md index 328c225c3c21..b7cb097feebd 100644 --- a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/uniswap/l1_contract.md +++ b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/uniswap/l1_contract.md @@ -7,7 +7,7 @@ This page goes over the code in the L1 contract for Uniswap, which works alongsi ## Setup -```solidity title="setup" showLineNumbers +```solidity title="setup" showLineNumbers import {TokenPortal} from "./TokenPortal.sol"; import {ISwapRouter} from "../external/ISwapRouter.sol"; @@ -44,12 +44,12 @@ contract UniswapPortal { bytes32 contentHash; } ``` -> Source code: l1-contracts/test/portals/UniswapPortal.sol#L12-L48 +> Source code: l1-contracts/test/portals/UniswapPortal.sol#L12-L48 ## Public swap -```solidity title="solidity_uniswap_swap_public" showLineNumbers +```solidity title="solidity_uniswap_swap_public" showLineNumbers /** * @notice Exit with funds from L2, perform swap on L1 and deposit output asset to L2 again publicly * @dev `msg.value` indicates fee to submit message to inbox. Currently, anyone can call this method on your behalf. @@ -155,7 +155,7 @@ function swapPublic( ); } ``` -> Source code: l1-contracts/test/portals/UniswapPortal.sol#L50-L155 +> Source code: l1-contracts/test/portals/UniswapPortal.sol#L50-L155 1. It fetches the input and output tokens we are swapping. The Uniswap portal only needs to know the portal addresses of the input and output as they store the underlying ERC20 token address. @@ -177,7 +177,7 @@ You can find the corresponding function on the [L2 contracts page](./l2_contract This works very similarly to the public flow. -```solidity title="solidity_uniswap_swap_private" showLineNumbers +```solidity title="solidity_uniswap_swap_private" showLineNumbers /** * @notice Exit with funds from L2, perform swap on L1 and deposit output asset to L2 again privately * @dev `msg.value` indicates fee to submit message to inbox. Currently, anyone can call this method on your behalf. @@ -279,7 +279,7 @@ This works very similarly to the public flow. } } ``` -> Source code: l1-contracts/test/portals/UniswapPortal.sol#L157-L258 +> Source code: l1-contracts/test/portals/UniswapPortal.sol#L157-L258 You can find the corresponding function on the [L2 contracts page](./l2_contract.md#private-swap). diff --git a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/uniswap/l2_contract.md b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/uniswap/l2_contract.md index acba35542e6d..5db81bc8cadf 100644 --- a/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/uniswap/l2_contract.md +++ b/docs/versioned_docs/version-Latest/developers/tutorials/codealong/js_tutorials/uniswap/l2_contract.md @@ -9,7 +9,7 @@ This page goes over the code in the L2 contract for Uniswap, which works alongsi ### Setup and constructor -```rust title="uniswap_setup" showLineNumbers +```rust title="uniswap_setup" showLineNumbers mod util; // Demonstrates how to use portal contracts to swap on L1 Uniswap with funds on L2 @@ -44,13 +44,13 @@ pub contract Uniswap { storage.portal_address.initialize(portal_address); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/uniswap_contract/src/main.nr#L1-L35 +> Source code: noir-projects/noir-contracts/contracts/app/uniswap_contract/src/main.nr#L1-L35 We just need to store the portal address for the token that we want to swap. ### Public swap -```rust title="swap_public" showLineNumbers +```rust title="swap_public" showLineNumbers #[public] fn swap_public( sender: AztecAddress, @@ -124,7 +124,7 @@ fn swap_public( context.message_portal(storage.portal_address.read(), content_hash); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/uniswap_contract/src/main.nr#L37-L110 +> Source code: noir-projects/noir-contracts/contracts/app/uniswap_contract/src/main.nr#L37-L110 1. We check that `msg.sender()` has appropriate approval to call this on behalf of the sender by constructing an authwit message and checking if `from` has given the approval (read more about authwit [here](../../../../../aztec/concepts/advanced/authwit.md)). @@ -150,7 +150,7 @@ You can find the corresponding function on the [L1 contracts page](./l1_contract ### Private swap -```rust title="swap_private" showLineNumbers +```rust title="swap_private" showLineNumbers #[private] fn swap_private( input_asset: AztecAddress, // since private, we pass here and later assert that this is as expected by input_bridge @@ -222,7 +222,7 @@ fn swap_private( context.message_portal(storage.portal_address.read(), content_hash); } ``` -> Source code: noir-projects/noir-contracts/contracts/app/uniswap_contract/src/main.nr#L112-L183 +> Source code: noir-projects/noir-contracts/contracts/app/uniswap_contract/src/main.nr#L112-L183 This uses a util function `compute_swap_private_content_hash()` - find that [here](#utils) @@ -239,7 +239,7 @@ This flow works similarly to the public flow with a few notable changes: Both public and private swap functions call this function: -```rust title="authwit_uniswap_set" showLineNumbers +```rust title="authwit_uniswap_set" showLineNumbers // This helper method approves the bridge to burn this contract's funds and exits the input asset to L1 // Assumes contract already has funds. // Assume `token` relates to `token_bridge` (ie token_bridge.token == token) @@ -276,14 +276,14 @@ fn _approve_bridge_and_exit_input_asset_to_L1( .call(&mut context) } ``` -> Source code: noir-projects/noir-contracts/contracts/app/uniswap_contract/src/main.nr#L185-L221 +> Source code: noir-projects/noir-contracts/contracts/app/uniswap_contract/src/main.nr#L185-L221 ## Utils ### Compute content hash for public -```rust title="uniswap_public_content_hash" showLineNumbers +```rust title="uniswap_public_content_hash" showLineNumbers use dep::aztec::prelude::{AztecAddress, EthAddress}; use dep::aztec::protocol_types::{hash::sha256_to_field, traits::ToField}; @@ -341,14 +341,14 @@ pub fn compute_swap_public_content_hash( content_hash } ``` -> Source code: noir-projects/noir-contracts/contracts/app/uniswap_contract/src/util.nr#L1-L58 +> Source code: noir-projects/noir-contracts/contracts/app/uniswap_contract/src/util.nr#L1-L58 This method computes the L2 to L1 message content hash for the public. To find out how it is consumed on L1, view the [L1 contracts page](./l1_contract.md) ### Compute content hash for private -```rust title="compute_swap_private_content_hash" showLineNumbers +```rust title="compute_swap_private_content_hash" showLineNumbers // This method computes the L2 to L1 message content hash for the private // refer `l1-contracts/test/portals/UniswapPortal.sol` on how L2 to L1 message is expected pub fn compute_swap_private_content_hash( @@ -399,7 +399,7 @@ pub fn compute_swap_private_content_hash( content_hash } ``` -> Source code: noir-projects/noir-contracts/contracts/app/uniswap_contract/src/util.nr#L60-L110 +> Source code: noir-projects/noir-contracts/contracts/app/uniswap_contract/src/util.nr#L60-L110 This method computes the L2 to L1 message content hash for the private. To find out how it is consumed on L1, view the [L1 contracts page](./l1_contract.md). diff --git a/docs/versioned_docs/version-Latest/glossary.md b/docs/versioned_docs/version-Latest/glossary.md index a99ac042c050..2f705c5725ab 100644 --- a/docs/versioned_docs/version-Latest/glossary.md +++ b/docs/versioned_docs/version-Latest/glossary.md @@ -31,7 +31,7 @@ You can read more about `nargo` [here](#nargo). -Read more and review the source code [here](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.3/yarn-project/aztec.js). +Read more and review the source code [here](https://github.com/AztecProtocol/aztec-packages/blob/v0.87.4/yarn-project/aztec.js). ### Aztec.nr diff --git a/docs/versioned_docs/version-Latest/migration_notes.md b/docs/versioned_docs/version-Latest/migration_notes.md index 922b271bdd07..1816b212ebb4 100644 --- a/docs/versioned_docs/version-Latest/migration_notes.md +++ b/docs/versioned_docs/version-Latest/migration_notes.md @@ -7,7 +7,7 @@ tags: [migration, updating, sandbox] Aztec is in full-speed development. Literally every version breaks compatibility with the previous ones. This page attempts to target errors and difficulties you might encounter when upgrading, and how to resolve them. -## 0.87.3 +## 0.87.0 ## [Aztec.js/TS libraries] @@ -2417,7 +2417,7 @@ This will be further simplified in future versions (See [4496](https://github.co The prelude consists of -```rust title="prelude" showLineNumbers +```rust title="prelude" showLineNumbers pub use crate::{ context::{PrivateContext, PublicContext, ReturnsHash}, note::{ @@ -2439,7 +2439,7 @@ pub use dep::protocol_types::{ traits::{Deserialize, Serialize}, }; ``` -> Source code: noir-projects/aztec-nr/aztec/src/prelude.nr#L1-L22 +> Source code: noir-projects/aztec-nr/aztec/src/prelude.nr#L1-L22 ### `internal` is now a macro @@ -3077,7 +3077,7 @@ impl Storage { The `protocol_types` package is now being reexported from `aztec`. It can be accessed through `dep::aztec::protocol_types`. ```toml -aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="yarn-project/aztec-nr/aztec" } +aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="yarn-project/aztec-nr/aztec" } ``` ### [Aztec.nr] key type definition in Map @@ -3167,8 +3167,8 @@ const tokenBigInt = (await bridge.methods.token().simulate()).inner; ### [Aztec.nr] Add `protocol_types` to Nargo.toml ```toml -aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="yarn-project/aztec-nr/aztec" } -protocol_types = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.3", directory="yarn-project/noir-protocol-circuits/crates/types"} +aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="yarn-project/aztec-nr/aztec" } +protocol_types = { git="https://github.com/AztecProtocol/aztec-packages/", tag="v0.87.4", directory="yarn-project/noir-protocol-circuits/crates/types"} ``` ### [Aztec.nr] moving compute_address func to AztecAddress diff --git a/docs/versioned_docs/version-Latest/the_aztec_network/guides/run_nodes/cli_reference.md b/docs/versioned_docs/version-Latest/the_aztec_network/guides/run_nodes/cli_reference.md index 3efa5a9226b7..06336e8452d7 100644 --- a/docs/versioned_docs/version-Latest/the_aztec_network/guides/run_nodes/cli_reference.md +++ b/docs/versioned_docs/version-Latest/the_aztec_network/guides/run_nodes/cli_reference.md @@ -29,25 +29,11 @@ If two subsystems can contain the same configuration option, only one needs to b ::: ```bash - MISC + NETWORK - --network ($NETWORK) + --network ($NETWORK) Network to run Aztec on - --auto-update (default: disabled) ($AUTO_UPDATE) - Configure auto updates - - --auto-update-url ($AUTO_UPDATE_URL) - Configure where to get updates from - - SANDBOX - - --sandbox - Starts Aztec Sandbox - - --sandbox.noPXE [value] ($NO_PXE) - Do not expose PXE service on sandbox start - API --port (default: 8080) ($AZTEC_PORT) @@ -81,33 +67,33 @@ If two subsystems can contain the same configuration option, only one needs to b STORAGE - --data-directory ($DATA_DIRECTORY) + --data-directory ($DATA_DIRECTORY) Where to store data for services. If not set, will store temporarily - --data-store-map-size-kb ($DATA_STORE_MAP_SIZE_KB) + --data-store-map-size-kb ($DATA_STORE_MAP_SIZE_KB) The maximum possible size of the data store DB in KB. Can be overridden by component-specific options. L1 CONTRACT ADDRESSES - --rollup-address ($ROLLUP_CONTRACT_ADDRESS) + --rollup-address ($ROLLUP_CONTRACT_ADDRESS) The deployed L1 rollup contract address - --registry-address ($REGISTRY_CONTRACT_ADDRESS) + --registry-address ($REGISTRY_CONTRACT_ADDRESS) The deployed L1 registry contract address - --inbox-address ($INBOX_CONTRACT_ADDRESS) + --inbox-address ($INBOX_CONTRACT_ADDRESS) The deployed L1 -> L2 inbox contract address - --outbox-address ($OUTBOX_CONTRACT_ADDRESS) + --outbox-address ($OUTBOX_CONTRACT_ADDRESS) The deployed L2 -> L1 outbox contract address - --fee-juice-address ($FEE_JUICE_CONTRACT_ADDRESS) + --fee-juice-address ($FEE_JUICE_CONTRACT_ADDRESS) The deployed L1 Fee Juice contract address - --staking-asset-address ($STAKING_ASSET_CONTRACT_ADDRESS) + --staking-asset-address ($STAKING_ASSET_CONTRACT_ADDRESS) The deployed L1 Staking Asset contract address - --fee-juice-portal-address ($FEE_JUICE_PORTAL_CONTRACT_ADDRESS) + --fee-juice-portal-address ($FEE_JUICE_PORTAL_CONTRACT_ADDRESS) The deployed L1 Fee Juice portal contract address AZTEC NODE @@ -115,19 +101,19 @@ If two subsystems can contain the same configuration option, only one needs to b --node Starts Aztec Node with options - --node.archiverUrl ($ARCHIVER_URL) + --node.archiverUrl ($ARCHIVER_URL) URL for an archiver service - --node.deployAztecContracts ($DEPLOY_AZTEC_CONTRACTS) + --node.deployAztecContracts ($DEPLOY_AZTEC_CONTRACTS) Deploys L1 Aztec contracts before starting the node. Needs mnemonic or private key to be set. - --node.deployAztecContractsSalt ($DEPLOY_AZTEC_CONTRACTS_SALT) + --node.deployAztecContractsSalt ($DEPLOY_AZTEC_CONTRACTS_SALT) Numeric salt for deploying L1 Aztec contracts before starting the node. Needs mnemonic or private key to be set. Implies --node.deployAztecContracts. - --node.assumeProvenThroughBlockNumber ($ASSUME_PROVEN_THROUGH_BLOCK_NUMBER) + --node.assumeProvenThroughBlockNumber ($ASSUME_PROVEN_THROUGH_BLOCK_NUMBER) Cheats the rollup contract into assuming every block until this one is proven. Useful for speeding up bootstraps. - --node.publisherPrivateKey ($L1_PRIVATE_KEY) + --node.publisherPrivateKey ($L1_PRIVATE_KEY) Private key of account for publishing L1 contracts --node.worldStateBlockCheckIntervalMS (default: 100) ($WS_BLOCK_CHECK_INTERVAL_MS) @@ -136,18 +122,18 @@ If two subsystems can contain the same configuration option, only one needs to b --node.syncMode (default: snapshot) ($SYNC_MODE) Set sync mode to `full` to always sync via L1, `snapshot` to download a snapshot if there is no local data, `force-snapshot` to download even if there is local data. - --node.snapshotsUrl ($SYNC_SNAPSHOTS_URL) + --node.snapshotsUrl ($SYNC_SNAPSHOTS_URL) Base URL for downloading snapshots for snapshot sync. P2P SUBSYSTEM - --p2p-enabled [value] ($P2P_ENABLED) + --p2p-enabled [value] ($P2P_ENABLED) Enable P2P subsystem --p2p.blockCheckIntervalMS (default: 100) ($P2P_BLOCK_CHECK_INTERVAL_MS) The frequency in which to check for new L2 blocks. - --p2p.debugDisableColocationPenalty ($DEBUG_P2P_DISABLE_COLOCATION_PENALTY) + --p2p.debugDisableColocationPenalty ($DEBUG_P2P_DISABLE_COLOCATION_PENALTY) DEBUG: Disable colocation penalty - NEVER set to true in production --p2p.peerCheckIntervalMS (default: 30000) ($P2P_PEER_CHECK_INTERVAL_MS) @@ -160,35 +146,35 @@ If two subsystems can contain the same configuration option, only one needs to b The listen address. ipv4 address. --p2p.p2pPort (default: 40400) ($P2P_PORT) - The port for the P2P service. Defaults to 40400 + The port for the P2P service. - --p2p.p2pBroadcastPort ($P2P_BROADCAST_PORT) - The port to broadcast the P2P service on (included in the node's ENR). Defaults to P2P_PORT. - - --p2p.p2pIp ($P2P_IP) + --p2p.p2pIp ($P2P_IP) The IP address for the P2P service. ipv4 address. - --p2p.peerIdPrivateKey ($PEER_ID_PRIVATE_KEY) + --p2p.peerIdPrivateKey ($PEER_ID_PRIVATE_KEY) An optional peer id private key. If blank, will generate a random key. - --p2p.peerIdPrivateKeyPath ($PEER_ID_PRIVATE_KEY_PATH) - An optional path to store generated peer id private keys. If blank, will default to storing any generated keys in the root of the data directory. - --p2p.bootstrapNodes (default: ) ($BOOTSTRAP_NODES) A list of bootstrap peer ENRs to connect to. Separated by commas. - --p2p.bootstrapNodeEnrVersionCheck ($P2P_BOOTSTRAP_NODE_ENR_VERSION_CHECK) + --p2p.bootstrapNodeEnrVersionCheck ($P2P_BOOTSTRAP_NODE_ENR_VERSION_CHECK) Whether to check the version of the bootstrap node ENR. - --p2p.bootstrapNodesAsFullPeers ($P2P_BOOTSTRAP_NODES_AS_FULL_PEERS) + --p2p.bootstrapNodesAsFullPeers ($P2P_BOOTSTRAP_NODES_AS_FULL_PEERS) Whether to consider our configured bootnodes as full peers --p2p.maxPeerCount (default: 100) ($P2P_MAX_PEERS) The maximum number of peers to connect to. - --p2p.queryForIp ($P2P_QUERY_FOR_IP) + --p2p.queryForIp ($P2P_QUERY_FOR_IP) If announceUdpAddress or announceTcpAddress are not provided, query for the IP address of the machine. Default is false. + --p2p.keepProvenTxsInPoolFor ($P2P_TX_POOL_KEEP_PROVEN_FOR) + How many blocks have to pass after a block is proven before its txs are deleted (zero to delete immediately once proven) + + --p2p.keepAttestationsInPoolFor (default: 96) ($P2P_ATTESTATION_POOL_KEEP_FOR) + How many slots to keep attestations for. + --p2p.gossipsubInterval (default: 700) ($P2P_GOSSIPSUB_INTERVAL_MS) The interval of the gossipsub heartbeat to perform maintenance tasks. @@ -211,10 +197,7 @@ If two subsystems can contain the same configuration option, only one needs to b The number of gossipsub interval message cache windows to keep. --p2p.gossipsubMcacheGossip (default: 3) ($P2P_GOSSIPSUB_MCACHE_GOSSIP) - How many message cache windows to include when gossiping with other peers. - - --p2p.gossipsubSeenTTL (default: 1200000) ($P2P_GOSSIPSUB_SEEN_TTL) - How long to keep message IDs in the seen cache. + How many message cache windows to include when gossiping with other pears. --p2p.gossipsubTxTopicWeight (default: 1) ($P2P_GOSSIPSUB_TX_TOPIC_WEIGHT) The weight of the tx topic for the gossipsub protocol. @@ -234,19 +217,16 @@ If two subsystems can contain the same configuration option, only one needs to b --p2p.blockRequestBatchSize (default: 20) ($P2P_BLOCK_REQUEST_BATCH_SIZE) The number of blocks to fetch in a single batch. - --p2p.archivedTxLimit ($P2P_ARCHIVED_TX_LIMIT) + --p2p.archivedTxLimit ($P2P_ARCHIVED_TX_LIMIT) The number of transactions that will be archived. If the limit is set to 0 then archiving will be disabled. --p2p.trustedPeers (default: ) ($P2P_TRUSTED_PEERS) - A list of trusted peer ENRs that will always be persisted. Separated by commas. - - --p2p.privatePeers (default: ) ($P2P_PRIVATE_PEERS) - A list of private peer ENRs that will always be persisted and not be used for discovery. Separated by commas. + A list of trusted peers ENRs. Separated by commas. - --p2p.p2pStoreMapSizeKb ($P2P_STORE_MAP_SIZE_KB) + --p2p.p2pStoreMapSizeKb ($P2P_STORE_MAP_SIZE_KB) The maximum possible size of the P2P DB in KB. Overwrites the general dataStoreMapSizeKB. - --p2p.txPublicSetupAllowList ($TX_PUBLIC_SETUP_ALLOWLIST) + --p2p.txPublicSetupAllowList ($TX_PUBLIC_SETUP_ALLOWLIST) The list of functions calls allowed to run in setup --p2p.maxTxPoolSize (default: 100000000) ($P2P_MAX_TX_POOL_SIZE) @@ -258,18 +238,18 @@ If two subsystems can contain the same configuration option, only one needs to b --p2p.individualRequestTimeoutMs (default: 2000) ($P2P_REQRESP_INDIVIDUAL_REQUEST_TIMEOUT_MS) The timeout for an individual request response peer interaction. - --p2p.rollupVersion ($ROLLUP_VERSION) + --p2p.rollupVersion ($ROLLUP_VERSION) The version of the rollup. TELEMETRY - --tel.metricsCollectorUrl ($OTEL_EXPORTER_OTLP_METRICS_ENDPOINT) + --tel.metricsCollectorUrl ($OTEL_EXPORTER_OTLP_METRICS_ENDPOINT) The URL of the telemetry collector for metrics - --tel.tracesCollectorUrl ($OTEL_EXPORTER_OTLP_TRACES_ENDPOINT) + --tel.tracesCollectorUrl ($OTEL_EXPORTER_OTLP_TRACES_ENDPOINT) The URL of the telemetry collector for traces - --tel.logsCollectorUrl ($OTEL_EXPORTER_OTLP_LOGS_ENDPOINT) + --tel.logsCollectorUrl ($OTEL_EXPORTER_OTLP_LOGS_ENDPOINT) The URL of the telemetry collector for logs --tel.otelCollectIntervalMs (default: 60000) ($OTEL_COLLECT_INTERVAL_MS) @@ -289,31 +269,34 @@ If two subsystems can contain the same configuration option, only one needs to b --pxe.dataStoreMapSizeKB (default: 134217728) ($DATA_STORE_MAP_SIZE_KB) DB mapping size to be applied to all key/value stores - --pxe.rollupVersion ($ROLLUP_VERSION) + --pxe.rollupVersion ($ROLLUP_VERSION) The version of the rollup. + --pxe.l2StartingBlock (default: 1) ($PXE_L2_STARTING_BLOCK) + L2 block to start scanning from for new accounts + --pxe.l2BlockBatchSize (default: 200) ($PXE_L2_BLOCK_BATCH_SIZE) Maximum amount of blocks to pull from the stream in one request when synchronizing - --pxe.bbBinaryPath ($BB_BINARY_PATH) + --pxe.bbBinaryPath ($BB_BINARY_PATH) Path to the BB binary - --pxe.bbWorkingDirectory ($BB_WORKING_DIRECTORY) + --pxe.bbWorkingDirectory ($BB_WORKING_DIRECTORY) Working directory for the BB binary - --pxe.bbSkipCleanup ($BB_SKIP_CLEANUP) + --pxe.bbSkipCleanup ($BB_SKIP_CLEANUP) True to skip cleanup of temporary files for debugging purposes --pxe.proverEnabled (default: true) ($PXE_PROVER_ENABLED) Enable real proofs - --pxe.network ($NETWORK) + --pxe.network ($NETWORK) External Aztec network to connect to. e.g. devnet - --pxe.apiKey ($API_KEY) + --pxe.apiKey ($API_KEY) API Key required by the external network's node - --pxe.nodeUrl ($AZTEC_NODE_URL) + --pxe.nodeUrl ($AZTEC_NODE_URL) Custom Aztec Node URL to connect to ARCHIVER @@ -321,13 +304,10 @@ If two subsystems can contain the same configuration option, only one needs to b --archiver Starts Aztec Archiver with options - --archiver.blobSinkUrl ($BLOB_SINK_URL) + --archiver.blobSinkUrl ($BLOB_SINK_URL) The URL of the blob sink - --archiver.blobSinkMapSizeKb ($BLOB_SINK_MAP_SIZE_KB) - The maximum possible size of the blob sink DB in KB. Overwrites the general dataStoreMapSizeKB. - - --archiver.archiveApiUrl ($BLOB_SINK_ARCHIVE_API_URL) + --archiver.archiveApiUrl ($BLOB_SINK_ARCHIVE_API_URL) The URL of the archive API --archiver.archiverPollingIntervalMS (default: 500) ($ARCHIVER_POLLING_INTERVAL_MS) @@ -339,10 +319,10 @@ If two subsystems can contain the same configuration option, only one needs to b --archiver.maxLogs (default: 1000) ($ARCHIVER_MAX_LOGS) The max number of logs that can be obtained in 1 "getPublicLogs" call. - --archiver.archiverStoreMapSizeKb ($ARCHIVER_STORE_MAP_SIZE_KB) + --archiver.archiverStoreMapSizeKb ($ARCHIVER_STORE_MAP_SIZE_KB) The maximum possible size of the archiver DB in KB. Overwrites the general dataStoreMapSizeKB. - --archiver.rollupVersion ($ROLLUP_VERSION) + --archiver.rollupVersion ($ROLLUP_VERSION) The version of the rollup. --archiver.viemPollingIntervalMS (default: 1000) ($ARCHIVER_VIEM_POLLING_INTERVAL_MS) @@ -399,7 +379,7 @@ If two subsystems can contain the same configuration option, only one needs to b --archiver.priorityFeeRetryBumpPercentage (default: 50) ($L1_PRIORITY_FEE_RETRY_BUMP_PERCENTAGE) How much to increase priority fee by each retry attempt (percentage) - --archiver.fixedPriorityFeePerGas ($L1_FIXED_PRIORITY_FEE_PER_GAS) + --archiver.fixedPriorityFeePerGas ($L1_FIXED_PRIORITY_FEE_PER_GAS) Fixed priority fee per gas in Gwei. Overrides any priority fee bump percentage --archiver.maxAttempts (default: 3) ($L1_TX_MONITOR_MAX_ATTEMPTS) @@ -422,10 +402,10 @@ If two subsystems can contain the same configuration option, only one needs to b --sequencer Starts Aztec Sequencer with options - --sequencer.validatorPrivateKey ($VALIDATOR_PRIVATE_KEY) + --sequencer.validatorPrivateKey ($VALIDATOR_PRIVATE_KEY) The private key of the validator participating in attestation duties - --sequencer.disableValidator ($VALIDATOR_DISABLED) + --sequencer.disableValidator ($VALIDATOR_DISABLED) Do not run the validator --sequencer.attestationPollingIntervalMs (default: 200) ($VALIDATOR_ATTESTATIONS_POLLING_INTERVAL_MS) @@ -443,25 +423,22 @@ If two subsystems can contain the same configuration option, only one needs to b --sequencer.minTxsPerBlock (default: 1) ($SEQ_MIN_TX_PER_BLOCK) The minimum number of txs to include in a block. - --sequencer.publishTxsWithProposals ($SEQ_PUBLISH_TXS_WITH_PROPOSALS) - Whether to publish txs with proposals. - --sequencer.maxL2BlockGas (default: 10000000000) ($SEQ_MAX_L2_BLOCK_GAS) The maximum L2 block gas. --sequencer.maxDABlockGas (default: 10000000000) ($SEQ_MAX_DA_BLOCK_GAS) The maximum DA block gas. - --sequencer.coinbase ($COINBASE) + --sequencer.coinbase ($COINBASE) Recipient of block reward. - --sequencer.feeRecipient ($FEE_RECIPIENT) + --sequencer.feeRecipient ($FEE_RECIPIENT) Address to receive fees. - --sequencer.acvmWorkingDirectory ($ACVM_WORKING_DIRECTORY) + --sequencer.acvmWorkingDirectory ($ACVM_WORKING_DIRECTORY) The working directory to use for simulation/proving - --sequencer.acvmBinaryPath ($ACVM_BINARY_PATH) + --sequencer.acvmBinaryPath ($ACVM_BINARY_PATH) The path to the ACVM binary --sequencer.maxBlockSizeInBytes (default: 1048576) ($SEQ_MAX_BLOCK_SIZE_IN_BYTES) @@ -473,10 +450,10 @@ If two subsystems can contain the same configuration option, only one needs to b --sequencer.governanceProposerPayload (default: 0x0000000000000000000000000000000000000000) ($GOVERNANCE_PROPOSER_PAYLOAD_ADDRESS) The address of the payload for the governanceProposer - --sequencer.maxL1TxInclusionTimeIntoSlot ($SEQ_MAX_L1_TX_INCLUSION_TIME_INTO_SLOT) + --sequencer.maxL1TxInclusionTimeIntoSlot ($SEQ_MAX_L1_TX_INCLUSION_TIME_INTO_SLOT) How many seconds into an L1 slot we can still send a tx and get it mined. - --sequencer.txPublicSetupAllowList ($TX_PUBLIC_SETUP_ALLOWLIST) + --sequencer.txPublicSetupAllowList ($TX_PUBLIC_SETUP_ALLOWLIST) The list of functions calls allowed to run in setup --sequencer.viemPollingIntervalMS (default: 1000) ($L1_READER_VIEM_POLLING_INTERVAL_MS) @@ -506,7 +483,7 @@ If two subsystems can contain the same configuration option, only one needs to b --sequencer.priorityFeeRetryBumpPercentage (default: 50) ($L1_PRIORITY_FEE_RETRY_BUMP_PERCENTAGE) How much to increase priority fee by each retry attempt (percentage) - --sequencer.fixedPriorityFeePerGas ($L1_FIXED_PRIORITY_FEE_PER_GAS) + --sequencer.fixedPriorityFeePerGas ($L1_FIXED_PRIORITY_FEE_PER_GAS) Fixed priority fee per gas in Gwei. Overrides any priority fee bump percentage --sequencer.maxAttempts (default: 3) ($L1_TX_MONITOR_MAX_ATTEMPTS) @@ -527,9 +504,6 @@ If two subsystems can contain the same configuration option, only one needs to b --sequencer.blobSinkUrl ($BLOB_SINK_URL) The URL of the blob sink - --sequencer.blobSinkMapSizeKb ($BLOB_SINK_MAP_SIZE_KB) - The maximum possible size of the blob sink DB in KB. Overwrites the general dataStoreMapSizeKB. - --sequencer.archiveApiUrl ($BLOB_SINK_ARCHIVE_API_URL) The URL of the archive API @@ -556,12 +530,6 @@ If two subsystems can contain the same configuration option, only one needs to b --blobSink.port ($BLOB_SINK_PORT) The port to run the blob sink server on - --blobSink.blobSinkUrl ($BLOB_SINK_URL) - The URL of the blob sink - - --blobSink.blobSinkMapSizeKb ($BLOB_SINK_MAP_SIZE_KB) - The maximum possible size of the blob sink DB in KB. Overwrites the general dataStoreMapSizeKB. - --blobSink.archiveApiUrl ($BLOB_SINK_ARCHIVE_API_URL) The URL of the archive API @@ -618,21 +586,6 @@ If two subsystems can contain the same configuration option, only one needs to b --proverNode.worldStateDbMapSizeKb ($WS_DB_MAP_SIZE_KB) The maximum possible size of the world state DB in KB. Overwrites the general dataStoreMapSizeKB. - --proverNode.archiveTreeMapSizeKb ($ARCHIVE_TREE_MAP_SIZE_KB) - The maximum possible size of the world state archive tree in KB. Overwrites the general worldStateDbMapSizeKb. - - --proverNode.nullifierTreeMapSizeKb ($NULLIFIER_TREE_MAP_SIZE_KB) - The maximum possible size of the world state nullifier tree in KB. Overwrites the general worldStateDbMapSizeKb. - - --proverNode.noteHashTreeMapSizeKb ($NOTE_HASH_TREE_MAP_SIZE_KB) - The maximum possible size of the world state note hash tree in KB. Overwrites the general worldStateDbMapSizeKb. - - --proverNode.messageTreeMapSizeKb ($MESSAGE_TREE_MAP_SIZE_KB) - The maximum possible size of the world state message tree in KB. Overwrites the general worldStateDbMapSizeKb. - - --proverNode.publicDataTreeMapSizeKb ($PUBLIC_DATA_TREE_MAP_SIZE_KB) - The maximum possible size of the world state public data tree in KB. Overwrites the general worldStateDbMapSizeKb. - --proverNode.worldStateDataDirectory ($WS_DATA_DIRECTORY) Optional directory for the world state database @@ -648,8 +601,8 @@ If two subsystems can contain the same configuration option, only one needs to b --proverNode.publisherPrivateKey (default: 0x0000000000000000000000000000000000000000000000000000000000000000)($PROVER_PUBLISHER_PRIVATE_KEY) The private key to be used by the publisher. - --proverNode.proverCoordinationNodeUrls (default: ) ($PROVER_COORDINATION_NODE_URLS) - The URLs of the tx provider nodes + --proverNode.proverCoordinationNodeUrl ($PROVER_COORDINATION_NODE_URL) + The URL of the tx provider node --proverNode.proverNodeMaxPendingJobs (default: 10) ($PROVER_NODE_MAX_PENDING_JOBS) The maximum number of pending jobs for the prover node @@ -660,17 +613,14 @@ If two subsystems can contain the same configuration option, only one needs to b --proverNode.proverNodeMaxParallelBlocksPerEpoch (default: 32) ($PROVER_NODE_MAX_PARALLEL_BLOCKS_PER_EPOCH) The Maximum number of blocks to process in parallel while proving an epoch - --proverNode.proverNodeFailedEpochStore ($PROVER_NODE_FAILED_EPOCH_STORE) - File store where to upload node state when an epoch fails to be proven + --proverNode.txGatheringTimeoutMs (default: 60000) ($PROVER_NODE_TX_GATHERING_TIMEOUT_MS) + The maximum amount of time to wait for tx data to be available --proverNode.txGatheringIntervalMs (default: 1000) ($PROVER_NODE_TX_GATHERING_INTERVAL_MS) How often to check that tx data is available - --proverNode.txGatheringBatchSize (default: 10) ($PROVER_NODE_TX_GATHERING_BATCH_SIZE) - How many transactions to gather from a node in a single request - - --proverNode.txGatheringMaxParallelRequestsPerNode (default: 100) ($PROVER_NODE_TX_GATHERING_MAX_PARALLEL_REQUESTS_PER_NODE) - How many tx requests to make in parallel to each node + --proverNode.txGatheringMaxParallelRequests (default: 100) ($PROVER_NODE_TX_GATHERING_MAX_PARALLEL_REQUESTS) + How many txs to load up a time --proverNode.testAccounts ($TEST_ACCOUNTS) Whether to populate the genesis state with initial fee juice for the test accounts. @@ -684,12 +634,6 @@ If two subsystems can contain the same configuration option, only one needs to b --proverNode.snapshotsUrl ($SYNC_SNAPSHOTS_URL) Base URL for snapshots index. - --proverNode.autoUpdate (default: disabled) ($AUTO_UPDATE) - The auto update mode for this node - - --proverNode.autoUpdateUrl ($AUTO_UPDATE_URL) - Base URL to check for updates - PROVER BROKER --prover-broker @@ -759,123 +703,7 @@ If two subsystems can contain the same configuration option, only one needs to b --p2p-bootstrap Starts Aztec P2P Bootstrap with options - --p2pBootstrap.p2pBroadcastPort ($P2P_BROADCAST_PORT) - The port to broadcast the P2P service on (included in the node's ENR). Defaults to P2P_PORT. - - --p2pBootstrap.peerIdPrivateKeyPath ($PEER_ID_PRIVATE_KEY_PATH) - An optional path to store generated peer id private keys. If blank, will default to storing any generated keys in the root of the data directory. - --p2pBootstrap.dataStoreMapSizeKB (default: 134217728) ($DATA_STORE_MAP_SIZE_KB) DB mapping size to be applied to all key/value stores - BOT - - --bot - Starts Aztec Bot with options - - --bot.nodeUrl ($AZTEC_NODE_URL) - The URL to the Aztec node to check for tx pool status. - - --bot.nodeAdminUrl ($AZTEC_NODE_ADMIN_URL) - The URL to the Aztec node admin API to force-flush txs if configured. - - --bot.pxeUrl ($BOT_PXE_URL) - URL to the PXE for sending txs, or undefined if an in-proc PXE is used. - - --bot.l1Mnemonic ($BOT_L1_MNEMONIC) - The mnemonic for the account to bridge fee juice from L1. - - --bot.l1PrivateKey ($BOT_L1_PRIVATE_KEY) - The private key for the account to bridge fee juice from L1. - - --bot.senderPrivateKey ($BOT_PRIVATE_KEY) - Signing private key for the sender account. - - --bot.senderSalt ($BOT_ACCOUNT_SALT) - The salt to use to deploys the sender account. - - --bot.recipientEncryptionSecret (default: 0x00000000000000000000000000000000000000000000000000000000cafecafe)($BOT_RECIPIENT_ENCRYPTION_SECRET) - Encryption secret for a recipient account. - - --bot.tokenSalt (default: 0x0000000000000000000000000000000000000000000000000000000000000001)($BOT_TOKEN_SALT) - Salt for the token contract deployment. - - --bot.txIntervalSeconds (default: 60) ($BOT_TX_INTERVAL_SECONDS) - Every how many seconds should a new tx be sent. - - --bot.privateTransfersPerTx (default: 1) ($BOT_PRIVATE_TRANSFERS_PER_TX) - How many private token transfers are executed per tx. - - --bot.publicTransfersPerTx (default: 1) ($BOT_PUBLIC_TRANSFERS_PER_TX) - How many public token transfers are executed per tx. - - --bot.feePaymentMethod (default: fee_juice) ($BOT_FEE_PAYMENT_METHOD) - How to handle fee payments. (Options: fee_juice) - - --bot.noStart ($BOT_NO_START) - True to not automatically setup or start the bot on initialization. - - --bot.txMinedWaitSeconds (default: 180) ($BOT_TX_MINED_WAIT_SECONDS) - How long to wait for a tx to be mined before reporting an error. - - --bot.followChain (default: NONE) ($BOT_FOLLOW_CHAIN) - Which chain the bot follows - - --bot.maxPendingTxs (default: 128) ($BOT_MAX_PENDING_TXS) - Do not send a tx if the node's tx pool already has this many pending txs. - - --bot.flushSetupTransactions ($BOT_FLUSH_SETUP_TRANSACTIONS) - Make a request for the sequencer to build a block after each setup transaction. - - --bot.l2GasLimit ($BOT_L2_GAS_LIMIT) - L2 gas limit for the tx (empty to have the bot trigger an estimate gas). - - --bot.daGasLimit ($BOT_DA_GAS_LIMIT) - DA gas limit for the tx (empty to have the bot trigger an estimate gas). - - --bot.contract (default: TokenContract) ($BOT_TOKEN_CONTRACT) - Token contract to use - - --bot.maxConsecutiveErrors ($BOT_MAX_CONSECUTIVE_ERRORS) - The maximum number of consecutive errors before the bot shuts down - - --bot.stopWhenUnhealthy ($BOT_STOP_WHEN_UNHEALTHY) - Stops the bot if service becomes unhealthy - - --bot.ammTxs ($BOT_AMM_TXS) - Deploy an AMM and send swaps to it - - TXE - - --txe - Starts Aztec TXE with options - - FAUCET - - --faucet - Starts the Aztec faucet - - --faucet.apiServer (default: true) - Starts a simple HTTP server to access the faucet - - --faucet.apiServerPort (default: 8080) - The port on which to start the api server on - - --faucet.viemPollingIntervalMS (default: 1000) ($L1_READER_VIEM_POLLING_INTERVAL_MS) - The polling interval viem uses in ms - - --faucet.l1Mnemonic ($MNEMONIC) - The mnemonic for the faucet account - - --faucet.mnemonicAccountIndex ($FAUCET_MNEMONIC_ACCOUNT_INDEX) - The account to use - - --faucet.interval (default: 3600000) ($FAUCET_INTERVAL_MS) - How often the faucet can be dripped - - --faucet.ethAmount (default: 1.0) ($FAUCET_ETH_AMOUNT) - How much eth the faucet should drip per call - - --faucet.l1Assets ($FAUCET_L1_ASSETS) - Which other L1 assets the faucet is able to drip ```