diff --git a/circuits/cpp/src/aztec3/circuits/rollup/base/.test.cpp b/circuits/cpp/src/aztec3/circuits/rollup/base/.test.cpp index a5109cabf3b..dd2298537ac 100644 --- a/circuits/cpp/src/aztec3/circuits/rollup/base/.test.cpp +++ b/circuits/cpp/src/aztec3/circuits/rollup/base/.test.cpp @@ -258,7 +258,7 @@ TEST_F(base_rollup_tests, native_new_commitments_tree) // Then get sibling path so we can verify insert them into the tree. std::array, 2> kernel_data = { get_empty_kernel(), get_empty_kernel() }; - std::array new_commitments = { 0, 1, 2, 3, 4, 5, 6, 7 }; + std::array new_commitments = { 0, 1, 2, 3, 4, 5, 6, 7 }; for (uint8_t i = 0; i < 2; i++) { std::array kernel_commitments; for (uint8_t j = 0; j < MAX_NEW_COMMITMENTS_PER_TX; j++) { @@ -481,7 +481,7 @@ TEST_F(base_rollup_tests, native_nullifier_tree_regression) initial_values[7] = uint256_t("2bb9aa4a22a6ae7204f2c67abaab59cead6558cde4ee25ce3464704cb2e38136"); initial_values[8] = uint256_t("16a732095298ccca828c4d747813f8bd46e188079ed17904e2c9de50760833c8"); - std::array new_nullifiers = { 0 }; + std::array new_nullifiers = { 0 }; new_nullifiers[0] = uint256_t("16da4f27fb78de7e0db4c5a04b569bc46382c5f471da2f7d670beff1614e0118"), new_nullifiers[1] = uint256_t("26ab07ce103a55e29f11478eaa36cebd10c4834b143a7debcc7ef53bfdb547dd"); @@ -519,7 +519,7 @@ TEST_F(base_rollup_tests, native_nullifier_tree_regression) TEST_F(base_rollup_tests, nullifier_tree_regression_2) { // Regression test caught when testing the typescript nullifier tree implementation - std::array new_nullifiers = { 0 }; + std::array new_nullifiers = { 0 }; new_nullifiers[0] = uint256_t("2a7d956c1365d259646d2d85babe1abb793bb8789e98df7e2336a29a0c91fd01"); new_nullifiers[1] = uint256_t("236bf2d113f9ffee89df1a7a04890c9ad3583c6773eb9cdec484184f66abd4c6"); new_nullifiers[4] = uint256_t("2f5c8a1ee33c7104b244e22a3e481637cd501c9eae868cfab6b16e3b4ef3d635"); @@ -530,7 +530,7 @@ TEST_F(base_rollup_tests, nullifier_tree_regression_2) TEST_F(base_rollup_tests, nullifier_tree_regression_3) { - std::array new_nullifiers = { 0 }; + std::array new_nullifiers = { 0 }; new_nullifiers[0] = uint256_t("0740a17aa6437e71836d2adcdcb3f52879bb869cdd9c8fb8dc39a12846cd17f2"); new_nullifiers[1] = uint256_t("282e0e2f38310a7c7c98b636830b66f3276294560e26ef2499da10892f00af8f"); new_nullifiers[4] = uint256_t("0f117936e888bd3befb4435f4d65300d25609e95a3d1563f62ef7e58c294f578"); diff --git a/docs/docs/dev_docs/aztecjs/main.md b/docs/docs/dev_docs/aztecjs/main.md new file mode 100644 index 00000000000..b3e98d0d1da --- /dev/null +++ b/docs/docs/dev_docs/aztecjs/main.md @@ -0,0 +1,65 @@ +--- +title: Aztec.js +--- + +If you are looking for the API reference, go [here](../../apis/aztec-js/index.md). + +## Introduction + +Aztec.js is a library that provides APIs for managing accounts and interacting with contracts on the Aztec network. It communicates with the [Private eXecution Environment (PXE)](https://docs.aztec.network/apis/pxe/interfaces/PXE) through a `PXE` implementation, allowing developers to easily register new accounts, deploy contracts, view functions, and send transactions. + +## Usage + +### Create a new account + +```typescript +import { getSchnorrAccount } from "@aztec/aztec.js"; +import { GrumpkinPrivateKey } from "@aztec/types"; + +const encryptionPrivateKey = GrumpkinPrivateKey.random(); +const signingPrivateKey = GrumpkinPrivateKey.random(); +const wallet = getSchnorrAccount( + pxe, + encryptionPrivateKey, + signingPrivateKey +).waitDeploy(); +console.log(`New account deployed at ${wallet.getAddress()}`); +``` + +### Deploy a contract + +```typescript +import { Contract } from "@aztec/aztec.js"; + +const contract = await Contract.deploy(wallet, MyContractArtifact, [ + ...constructorArgs, +]) + .send() + .deployed(); +console.log(`Contract deployed at ${contract.address}`); +``` + +### Send a transaction + +```typescript +import { Contract } from "@aztec/aztec.js"; + +const contract = await Contract.at(contractAddress, MyContractArtifact, wallet); +const tx = await contract.methods + .transfer(amount, recipientAddress) + .send() + .wait(); +console.log( + `Transferred ${amount} to ${recipientAddress} on block ${tx.blockNumber}` +); +``` + +### Call a view function + +```typescript +import { Contract } from "@aztec/aztec.js"; + +const contract = await Contract.at(contractAddress, MyContractArtifact, wallet); +const balance = await contract.methods.getBalance(wallet.getAddress()).view(); +console.log(`Account balance is ${balance}`); +``` diff --git a/docs/docs/dev_docs/getting_started/blank_box.md b/docs/docs/dev_docs/cli/blank_box.md similarity index 94% rename from docs/docs/dev_docs/getting_started/blank_box.md rename to docs/docs/dev_docs/cli/blank_box.md index 70a8566db18..9dfb2f2d86c 100644 --- a/docs/docs/dev_docs/getting_started/blank_box.md +++ b/docs/docs/dev_docs/cli/blank_box.md @@ -16,7 +16,7 @@ There are also boxes that include a basic React interface (`blank-react`) and an ## Setup -See the Quickstart page for [requirements](./quickstart.md#requirements), starting the local [Sandbox environment](./quickstart.md#sandbox-installation) and [installing the CLI](./quickstart#cli-installation). +See the Quickstart page for [requirements](../getting_started/quickstart.md#requirements), starting the local [Sandbox environment](../getting_started/quickstart.md#sandbox-installation) and [installing the CLI](../getting_started/quickstart#cli-installation). Aztec Boxes use [yarn](https://classic.yarnpkg.com/) for package management, so if you want to follow along exactly, make sure you have it [installed](https://classic.yarnpkg.com/en/docs/install). @@ -68,7 +68,7 @@ yarn ### Start the Sandbox -See the Quickstart for [installing and starting the Sandbox](./quickstart.md#sandbox-installation). +See the Quickstart for [installing and starting the Sandbox](../getting_started/quickstart.md#sandbox-installation). ### Start the frontend diff --git a/docs/docs/dev_docs/cli/cli-commands.md b/docs/docs/dev_docs/cli/cli-commands.md new file mode 100644 index 00000000000..2d8c444ec12 --- /dev/null +++ b/docs/docs/dev_docs/cli/cli-commands.md @@ -0,0 +1,96 @@ +--- +title: CLI Commands +--- + +Here you will find a reference to the commands available in the Aztec CLI. + +## Installation + +This command will install the Aztec CLI. + +```bash +npm install -g @aztec/cli +``` + +## Creating Accounts + +The first thing we want to do is create a couple of accounts. We will use the `create-account` command which will generate a new private key for us, register the account on the sandbox, and deploy a simple account contract which [uses a single key for privacy and authentication](../../concepts/foundation/accounts/keys.md): + +#include_code create-account yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash + +Once the account is set up, the CLI returns the resulting address, its privacy key, and partial address. You can read more about these [here](../../concepts/foundation/accounts/keys.md#addresses-partial-addresses-and-public-keys). + +Save the Address and Private key as environment variables. We will be using them later. + +```bash +export ADDRESS=
+export PRIVATE_KEY= +``` + +Alternatively, we can also manually generate a private key and use it for creating the account, either via a `-k` option or by setting the `PRIVATE_KEY` environment variable. + +#include_code create-account-from-private-key yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash + +For all commands that require a user's private key, the CLI will look for the `PRIVATE_KEY` environment variable in absence of an optional argument. + +Let's double check that the accounts have been registered with the sandbox using the `get-accounts` command: + +#include_code get-accounts yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash + +You will see a that a number of accounts exist that we did not create. The Sandbox initializes itself with 3 default accounts. Save one of the printed accounts (not the one that you generated above) in an environment variable. We will use it later. + +```bash +export ADDRESS2= +``` + +## Deploying a Token Contract + +We will now deploy a token contract using the `deploy` command, and set an address of the admin via a constructor argument. You can find the contract we are deploying [here](https://github.com/AztecProtocol/aztec-packages/blob/master/yarn-project/noir-contracts/src/contracts/token_contract/src/main.nr) (or write it for yourself in [this tutorial!](../tutorials/writing_token_contract.md)) +Make sure to replace this address with one of the two you created earlier. + +#include_code deploy yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash + +Save the contract address as an environment variable. We will use it later. + +```bash +export CONTRACT_ADDRESS= +``` + +- `--args` - Arguments to the constructor of the contract. In this case we have set an address as admin. + +The CLI tells us that the contract was successfully deployed. We can use the `check-deploy` command to verify that a contract has been successfully deployed to that address: + +#include_code check-deploy yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash + +## Sending a Transaction + +We can now send a transaction to the network. We will mint funds in the public domain. +To form and submit the transaction we will use the `send` command of `aztec-cli`. +The `send` command expect the function name as the first unnamed argument and the following named arguments: + +- `--args` - The list of arguments to the function call. +- `--contract-artifact` - The artifact of the contract to call. +- `--contract-address` - The deployed address of the contract to call. +- `--private-key` - The private key of the sender. + +#include_code send yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash + +We called the [`mint_public`](https://github.com/AztecProtocol/aztec-packages/blob/87fa621347e55f82e36c70515c1824161eee5282/yarn-project/noir-contracts/src/contracts/token_contract/src/main.nr#L157C10-L157C10) function and provided it with the 2 arguments it expects: the recipient's address and the amount to be minted. Make sure to replace all addresses in this command with yours. + +The command output tells us the details of the transaction such as its hash and status. We can use this hash to query the receipt of the transaction at a later time: + +#include_code get-tx-receipt yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash + +## Calling an Unconstrained (View) Function + +Now that the `mint_public` tx has been settled we can call the `balance_of_public` unconstrained function: + +#include_code call yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash + +The `call` command calls a read-only method on a contract, one that will not generate a transaction to be sent to the network. The arguments here are: + +- `--args` - The address for which we want to retrieve the balance. +- `--contract-artifact` - The artifact of the contract we are calling. +- `--contract-address` - The address of the deployed contract + +As you can see from the result, this address has a public balance of 543, as expected. diff --git a/docs/docs/dev_docs/cli/main.md b/docs/docs/dev_docs/cli/main.md index 745fd4b216c..2c3a881eef8 100644 --- a/docs/docs/dev_docs/cli/main.md +++ b/docs/docs/dev_docs/cli/main.md @@ -1,144 +1,39 @@ --- -title: Aztec CLI +title: Sandbox and CLI --- -## Introduction +The Aztec Sandbox is an environment for local development on the Aztec Network. It's easy to get setup with just a single, simple command, and contains all the components needed to develop and test Aztec contracts and applications. The Aztec CLI will allow you to interact with the sandbox. -The Aztec CLI is a command-line tool allowing the user to interact directly with the Aztec Network. +## Components of the Aztec network -It aims to provide all of the functionality required to deploy and invoke contracts and query system state such as contract data, transactions and emitted logs. - -## Requirements - -You should have [node.js](https://nodejs.org/en/download) installed with version >= 18. - -To install the Aztec CLI run: - -```bash -npm install -g @aztec/cli -``` - -Or if you use yarn: - -```bash -yarn global add @aztec/cli -``` - -Then verify that it is installed with: - -```bash -aztec-cli -h -``` - -Once installed it is invoked via: - -`aztec-cli [options] [command]` - -## I have the Sandbox running, now what? - -Lets first establish that we are able to communicate with the Sandbox. Most commands will require the url to the Sandbox, which defaults in the CLI to `http://localhost:8080`. You can override this as an option with each command or by setting `PXE_URL` environment variable. - -To test communication with the Sandbox, let's run the command: - -#include_code block-number yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash - -You should see the current block number (1) printed to the screen! - -## Contracts - -We have shipped a number of example contracts in the `@aztec/noir-contracts` npm package. This is included with the cli by default so you are able to use these contracts to test with. To get a list of the names of the contracts run: - -#include_code example-contracts yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash - -You can see all of our example contracts in the monorepo [here](https://github.com/AztecProtocol/aztec-packages/tree/master/yarn-project/noir-contracts/src/contracts). - -In the following sections there will be commands that require contracts as options. You can either specify the full directory path to the contract artifact, or you can use the name of one of these examples as the option value. This will become clearer later on. - -## Creating Accounts - -The first thing we want to do is create a couple of accounts. We will use the `create-account` command which will generate a new private key for us, register the account on the sandbox, and deploy a simple account contract which [uses a single key for privacy and authentication](../../concepts/foundation/accounts/keys.md): - -#include_code create-account yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash +Aztec's Layer 2 network is a fully programmable combined private/public ZK rollup. To achieve this, the network contains the following primary components: -Once the account is set up, the CLI returns the resulting address, its privacy key, and partial address. You can read more about these [here](../../concepts/foundation/accounts/keys.md#addresses-partial-addresses-and-public-keys). +- Aztec Node - Aggregates all of the 'backend' services necessary for the building and publishing of rollups. This packages is currently in development and much of the functionality is mocked. +- [Private Execution Environment (PXE)](https://github.com/AztecProtocol/aztec-packages/tree/master/yarn-project/pxe) - Normally residing with the end client, this decrypts and stores a client's private state, executes simulations and submits transactions to the Aztec Node. +- [Aztec.js](https://github.com/AztecProtocol/aztec-packages/tree/master/yarn-project/aztec.js) - Aztec's client library for interacting with the PXE (think Ethers.js). See the getting started guide [here](../getting_started/aztecjs-getting-started.md). -Save the Address and Private key as environment variables. We will be using them later. +All of this is included in the Sandbox, with the exception of Aztec.js which you can use to interact with it. -```bash -export ADDRESS=
-export PRIVATE_KEY= -``` +With the help of Aztec.js you will be able to: -Alternatively, we can also manually generate a private key and use it for creating the account, either via a `-k` option or by setting the `PRIVATE_KEY` environment variable. +- Create an account +- Deploy a contract +- Call view methods on contracts +- Simulate the calling of contract functions +- Send transactions to the network +- Be notified when transactions settle +- Query chain state such as chain id, block number etc. -#include_code create-account-from-private-key yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash +## What's in the Sandbox? -For all commands that require a user's private key, the CLI will look for the `PRIVATE_KEY` environment variable in absence of an optional argument. +The sandbox contains a local Ethereum instance running [Anvil](https://book.getfoundry.sh/anvil/), a local instance of the Aztec rollup, an aztec private execution client for handling user transactions and state, and, if using Docker, an [Otterscan](https://github.com/otterscan/otterscan) block explorer for the local Ethereum network. -Let's double check that the accounts have been registered with the sandbox using the `get-accounts` command: +These provide a self contained environment which deploys Aztec on a local (empty) Ethereum network, creates 3 smart contract wallet accounts on the rollup, and allows transactions to be processed on the local Aztec sequencer. -#include_code get-accounts yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash +The current sandbox does not generate or verify proofs, but provides a working end to end developer flow for writing and interacting with Aztec.nr smart contracts. -You will see a that a number of accounts exist that we did not create. The Sandbox initializes itself with 3 default accounts. Save one of the printed accounts (not the one that you generated above) in an environment variable. We will use it later. +## Aztec CLI -```bash -export ADDRESS2= -``` +The Aztec CLI is a command-line tool allowing the user to interact directly with the Aztec network and sandbox. -## Deploying a Token Contract - -We will now deploy a token contract using the `deploy` command, and set an address of the admin via a constructor argument. -Make sure to replace this address with one of the two you created earlier. - -#include_code deploy yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash - -Save the contract address as an environment variable. We will use it later. - -```bash -export CONTRACT_ADDRESS= -``` - -- `--args` - Arguments to the constructor of the contract. In this case we have set an address as admin. - -The CLI tells us that the contract was successfully deployed. We can use the `check-deploy` command to verify that a contract has been successfully deployed to that address: - -#include_code check-deploy yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash - -## Sending a Transaction - -We can now send a transaction to the network. We will mint funds in the public domain. -To form and submit the transaction we will use the `send` command of `aztec-cli`. -The `send` command expect the function name as the first unnamed argument and the following named arguments: - -- `--args` - The list of arguments to the function call. -- `--contract-artifact` - The artifact of the contract to call. -- `--contract-address` - The deployed address of the contract to call. -- `--private-key` - The private key of the sender. - -#include_code send yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash - -We called the `mint_public` function and provided it with the 2 arguments it expects: the recipient's address and the amount to be minted. Make sure to replace all addresses in this command with yours. - -The command output tells us the details of the transaction such as its hash and status. We can use this hash to query the receipt of the transaction at a later time: - -#include_code get-tx-receipt yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash - -## Calling an Unconstrained (View) Function - -Now that the `mint_public` tx has been settled we can call the `balance_of_public` unconstrained function: - -#include_code call yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash - -The `call` command calls a read-only method on a contract, one that will not generate a transaction to be sent to the network. The arguments here are: - -- `--args` - The address for which we want to retrieve the balance. -- `--contract-artifact` - The artifact of the contract we are calling. -- `--contract-address` - The address of the deployed contract - -As you can see from the result, this address has a public balance of 543, as expected. - -## Compute Function Selector -`aztec-cli --compute-selector ` gives the function selector. - -## Inspect Contract -`aztec-cli --compute-selector ` gives the list of all callable functions along with their function signature and selector. \ No newline at end of file +It aims to provide all of the functionality required to deploy and invoke contracts and query system state such as contract data, transactions and emitted logs. diff --git a/docs/docs/dev_docs/cli/sandbox-reference.md b/docs/docs/dev_docs/cli/sandbox-reference.md new file mode 100644 index 00000000000..f9292e44a6e --- /dev/null +++ b/docs/docs/dev_docs/cli/sandbox-reference.md @@ -0,0 +1,96 @@ +--- +title: Sandbox Reference +--- + +Here you will find a reference to everything available within the Sandbox. + +## Installation + +You can run the Sandbox using either Docker or npm. + +### With Docker + +```bash +/bin/bash -c "$(curl -fsSL 'https://sandbox.aztec.network')" +``` + +This will attempt to run the Sandbox on ` localhost:8080`. You can change the port defined in `./.aztec/docker-compose.yml`. Running the command again will overwrite any changes made to the `docker-compose.yml`. + +To install a specific version of the sandbox, you can set the environment variable `SANDBOX_VERSION` + +```bash +SANDBOX_VERSION= /bin/bash -c "$(curl -fsSL 'https://sandbox.aztec.network')" +``` + +NOTE: The sandbox version should be the same as your `@aztec/cli` package to ensure compatibility. + +### With npm + +You can download and run the Sandbox package directly if you have nodejs 18 or higher installed. + +You will also need an Ethereum node like Anvil or Hardhat running locally on port 8545. + +```bash +npx @aztec/aztec-sandbox +``` + +## Running + +The installation command will run the sandbox, and once installed you can run like so: + +```bash +cd ~/.aztec && docker-compose up +``` + +## Otterscan + +If you have set up the Sandbox with Docker, you will also have Otterscan. + +You can see Ethereum Layer 1 activity through the local Otterscan on `http://localhost:5100`. This is especially useful for dapps that use L1-L2 messaging through [portal contracts](../contracts/portals/main.md). + +## Cheat Codes + +To help with testing, the sandbox is shipped with a set of cheatcodes. + +Cheatcodes allow you to change the time of the Aztec block, load certain state or more easily manipulate Ethereum instead of having to write dedicated RPC calls to anvil or hardhat. + +You can find the cheat code reference [here](../testing/cheat_codes.md). + +## Contracts + +We have shipped a number of example contracts in the `@aztec/noir-contracts` [npm package](https://www.npmjs.com/package/@aztec/noir-contracts). This is included with the cli by default so you are able to use these contracts to test with. To get a list of the names of the contracts run: + +```bash title="example-contracts" showLineNumbers +% aztec-cli example-contracts +BenchmarkingContractArtifact +CardGameContractArtifact +ChildContractArtifact +DocsExampleContractArtifact +EasyPrivateTokenContractArtifact +EcdsaAccountContractArtifact +EscrowContractArtifact +ImportTestContractArtifact +LendingContractArtifact +ParentContractArtifact +PendingCommitmentsContractArtifact +PokeableTokenContractArtifact +PriceFeedContractArtifact +SchnorrAccountContractArtifact +SchnorrHardcodedAccountContractArtifact +SchnorrSingleKeyAccountContractArtifact +StatefulTestContractArtifact +TestContractArtifact +TokenBridgeContractArtifact +TokenContractArtifact +UniswapContractArtifact +``` + +> Source code: /yarn-project/end-to-end/src/cli_docs_sandbox.test.ts#L95-L118 + +You can see all of our example contracts in the monorepo [here](https://github.com/AztecProtocol/aztec-packages/tree/master/yarn-project/noir-contracts/src/contracts). + +## Boxes + +The sandbox is shipped with full-stack Aztec project templates, with example Aztec.nr contracts, testing scripts, and web interfaces. + +You can read more information about how to use boxes [here](./blank_box.md) diff --git a/docs/docs/dev_docs/getting_started/updating.md b/docs/docs/dev_docs/cli/updating.md similarity index 82% rename from docs/docs/dev_docs/getting_started/updating.md rename to docs/docs/dev_docs/cli/updating.md index cb0662ca63c..ff65aacebaf 100644 --- a/docs/docs/dev_docs/getting_started/updating.md +++ b/docs/docs/dev_docs/cli/updating.md @@ -2,7 +2,39 @@ title: Updating --- +## Quick Reference + +- Aztec Sandbox + +```shell + /bin/bash -c "$(curl -fsSL 'https://sandbox.aztec.network')" +``` + +- Aztec CLI + +```shell +npm install -g @aztec/cli +``` + +- nargo + +```shell +noirup +``` + +- Aztec.nr + +```toml +#nargo.toml +[dependencies] +aztec = { git="https://github.com/AztecProtocol/aztec-packages", tag="#include_aztec_version", directory="yarn-project/aztec-nr/aztec" } +value_note = { git="https://github.com/AztecProtocol/aztec-packages", tag="#include_aztec_version", directory="yarn-project/aztec-nr/value-note" } +``` + +Read on to learn about versioning and other commands. + There are 4 components whose versions need to be kept compatible: + 1. Aztec Sandbox, 2. Aztec CLI, 3. Noir compiler `nargo`, @@ -12,7 +44,9 @@ Aztec Sandbox, Aztec CLI and `aztec.nr` are using the same versioning scheme and The Noir compiler `nargo` has its own versioning scheme and its version must match the compatible nargo version specified in Sandbox. ## Updating Aztec Sandbox + To update the sandbox to the latest version, simply run the curl command we used for installation again: + ```shell /bin/bash -c "$(curl -fsSL 'https://sandbox.aztec.network')" ``` @@ -23,6 +57,7 @@ If you would like to use a fixed version of the sandbox, you can export the `SAN If you are unsure what version to use go to [aztec-packages repository](https://github.com/AztecProtocol/aztec-packages/releases) and choose the `aztec-packages` release based on the changelog. Then set the `SANDBOX_VERSION` environmental variable to the version you want to use. E.g.: + ```shell export SANDBOX_VERSION=#include_aztec_short_version ``` @@ -30,6 +65,7 @@ export SANDBOX_VERSION=#include_aztec_short_version Now when you run the curl command it will use the version you specified. To verify that it's the case check the console output of the curl command. You should see the following line: + ``` Setting up Aztec Sandbox v#include_aztec_short_version (nargo #include_noir_version), please stand by... ``` @@ -38,35 +74,46 @@ Alternatively you can open a new terminal and use aztec-cli to get the version. #include_code node-info yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash +This will return something like this: + +#include_code node-info yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash + The sandbox version should be the same as the one we chose by setting the `SANDBOX_VERSION` environmental variable. ## Updating Aztec CLI + If the latest version was used when updating the sandbox then we can simply run the following command to update the CLI: + ```shell npm install -g @aztec/cli ``` If a specific version was set for the sandbox then we need to install the CLI with the same version: + ```shell npm install -g @aztec/cli@$SANDBOX_VERSION ``` E.g.: + ```shell npm install -g @aztec/cli@#include_aztec_short_version ``` ## Updating Noir compiler + Now we need to update the Noir compiler `nargo` to the version compatible with the sandbox. Use `aztec-cli` to get it: #include_code node-info yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash Then we install the `Compatible Nargo Version` with (replace `COMPATIBLE_NARGO_VERSION` with the version from the previous command): + ```shell noirup -v COMPATIBLE_NARGO_VERSION ``` -## Updating Noir framework +## Updating Aztec.nr packages + Finally we need to update the Noir framework for Aztec contracts. We need to install a version compatible with our `nargo` and Sandbox. @@ -82,7 +129,8 @@ E.g.: +value_note = { git="https://github.com/AztecProtocol/aztec-packages", tag="#include_aztec_version", directory="yarn-project/aztec-nr/value-note" } ``` -Go to the project directory and try compiling it with `aztec-cli`` to verify that the update was successful: +Go to the project directory and try compiling it with `aztec-cli` to verify that the update was successful: + ```shell cd /your/project/root aztec-cli compile ./ diff --git a/docs/docs/dev_docs/contracts/compiling.md b/docs/docs/dev_docs/contracts/compiling.md index 78a871a76c1..8ac693510cc 100644 --- a/docs/docs/dev_docs/contracts/compiling.md +++ b/docs/docs/dev_docs/contracts/compiling.md @@ -123,13 +123,13 @@ export class TokenContract extends ContractBase { nonce: FieldLike, ) => ContractFunctionInteraction) & Pick; - + ... }; } ``` -Read more about interacting with contracts using `aztec.js` [here](../getting_started/sandbox.md). +Read more about interacting with contracts using `aztec.js` [here](../getting_started/aztecjs-getting-started.md). ### Aztec.nr interfaces @@ -158,7 +158,7 @@ impl TokenPrivateContextInterface { address, } } - + pub fn burn( self, context: &mut PrivateContext, @@ -173,7 +173,7 @@ impl TokenPrivateContextInterface { context.call_private_function(self.address, 0xd4fcc96e, serialized_args) } - + pub fn burn_public( self, @@ -190,7 +190,7 @@ impl TokenPrivateContextInterface { context.call_public_function(self.address, 0xb0e964d5, serialized_args) } ... - + } impl TokenPublicContextInterface { @@ -199,7 +199,7 @@ impl TokenPublicContextInterface { address, } } - + pub fn burn_public( self, context: PublicContext, @@ -214,7 +214,7 @@ impl TokenPublicContextInterface { context.call_public_function(self.address, 0xb0e964d5, serialized_args) } - + pub fn mint_private( self, @@ -229,7 +229,7 @@ impl TokenPublicContextInterface { context.call_public_function(self.address, 0x10763932, serialized_args) } - + } ``` diff --git a/docs/docs/dev_docs/contracts/deploying.md b/docs/docs/dev_docs/contracts/deploying.md index 07c0f00586c..6830a1fc314 100644 --- a/docs/docs/dev_docs/contracts/deploying.md +++ b/docs/docs/dev_docs/contracts/deploying.md @@ -3,14 +3,14 @@ Once you have [compiled](./compiling.md) your contracts you can proceed to deploying them using the aztec-cli or using aztec.js which is a Typescript client to interact with the sandbox. ## Prerequisites + - aztec-cli installed (go to [CLI main section](../cli/main.md) for installation instructions) - contract artifacts ready (go to [Compiling contracts section](./compiling.md) for instructions on how to compile contracts) -- aztec-sandbox running (go to [Sandbox section](../getting_started/sandbox.md) for instructions on how to install and run the sandbox) +- aztec-sandbox running (go to [Sandbox section](../getting_started/quickstart.md) for instructions on how to install and run the sandbox) ## Deploy -Contracts can be deployed using the `aztec-cli` or using the `aztec.js` library. - +Contracts can be deployed using the `aztec-cli` or using the `aztec.js` library. import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; @@ -28,28 +28,43 @@ aztec-cli deploy /path/to/contract/artifact.json Pre-requisite - Generate type-safe typescript classes for your contract when compiling using the `@aztec/noir-compiler` package. You can install the package by running `npm install @aztec/noir-compiler`. ```ts -import { readFileSync, writeFileSync } from 'fs'; -import { compileUsingNargo, generateTypescriptContractInterface} from '@aztec/noir-compiler'; - -const compiled: ContractArtifact[] = await compileUsingNargo(projectPathToContractFolder); +import { readFileSync, writeFileSync } from "fs"; +import { + compileUsingNargo, + generateTypescriptContractInterface, +} from "@aztec/noir-compiler"; + +const compiled: ContractArtifact[] = await compileUsingNargo( + projectPathToContractFolder +); const abiImportPath = "../target/Example.json"; -writeFileSync(tsInterfaceDestFilePath, generateTypescriptContractInterface(compiled[0], abiImportPath)); +writeFileSync( + tsInterfaceDestFilePath, + generateTypescriptContractInterface(compiled[0], abiImportPath) +); ``` + This would create a typescript file like `Example.ts` in the path specified. More details in the [compiling page](./compiling.md) Now you can import it to easily deploy and interact with the contract. + ```ts -import { ExampleContract } from './Example.js'; +import { ExampleContract } from "./Example.js"; const tx = ExampleContract.deploy(pxe).send(); await tx.wait({ interval: 0.5 }); const receipt = await tx.getReceipt(); -const exampleContract = await ExampleContract.at(receipt.contractAddress!, myWallet); +const exampleContract = await ExampleContract.at( + receipt.contractAddress!, + myWallet +); ``` + ### Deploy Arguments + There are several optional arguments that can be passed: @@ -57,13 +72,14 @@ There are several optional arguments that can be passed: `aztec-cli deploy` takes 1 mandatory argument which is the path to the contract artifact file in a JSON format (e.g. `contracts/target/PrivateToken.json`). Alternatively you can pass the name of an example contract as exported by `@aztec/noir-contracts` (run `aztec-cli example-contracts` to see the full list of contracts available). The command also takes the following optional arguments: + - `-args ` (default: `[]`): Arguments to pass to the contract constructor. - `--rpc-url ` (default: `http://localhost:8080`): URL of the PXE to connect to. - `--public-key ` (default: `undefined`): Optional encryption public key for this contract. -Set this only if this contract is expected to receive private notes (in such a case the public key is used during the note encryption). + Set this only if this contract is expected to receive private notes (in such a case the public key is used during the note encryption). - `--salt ` (default: random value): Hexadecimal string used when computing the contract address of the contract being deployed. -By default is set to a random value. -Set it, if you need a deterministic contract address (same functionality as Ethereum's `CREATE2` opcode). + By default is set to a random value. + Set it, if you need a deterministic contract address (same functionality as Ethereum's `CREATE2` opcode). @@ -72,15 +88,16 @@ The `deploy(...)` method is generated automatically with the typescript class re Its arguments are `PXE` client and contract constructor arguments. Additionally the `.send()` method can have a few optional arguments too, which are specified in an optional object: + - `portalContract?: EthAddress`: The L1 portal address to link the contract to. See the section on [Portals to learn more about them](./portals/main.md). -- `contractAddressSalt?: Fr`: A salt which is one of the inputs when computing a contract address of the contract to be deployed. -By default is set to a random value. -Set it, if you need a deterministic contract address (same functionality as Ethereum's `CREATE2` opcode). +- `contractAddressSalt?: Fr`: A salt which is one of the inputs when computing a contract address of the contract to be deployed. + By default is set to a random value. + Set it, if you need a deterministic contract address (same functionality as Ethereum's `CREATE2` opcode). ```ts -const tx = ExampleContract.deploy(pxe).send({ - portalContract: EthAddress.from("0x1234..."), - contractAddressSalt: new Fr(3n), +const tx = ExampleContract.deploy(pxe).send({ + portalContract: EthAddress.from("0x1234..."), + contractAddressSalt: new Fr(3n), }); ``` @@ -88,6 +105,7 @@ const tx = ExampleContract.deploy(pxe).send({ ### Deploying token contract + To give you a more complete example we will deploy a `Token` contract whose artifacts are included in the `@aztec/noir-contracts` package. The contract has `admin` as a constructor argument. @@ -104,7 +122,9 @@ aztec-cli deploy TokenContractArtifact --args 0x147392a39e593189902458f4303bc6e0 ```ts -const admin = AztecAddress.from("0x147392a39e593189902458f4303bc6e0a39128c5a1c1612f76527a162d36d529"); +const admin = AztecAddress.from( + "0x147392a39e593189902458f4303bc6e0a39128c5a1c1612f76527a162d36d529" +); // TokenContract is the TS interface that is automatically generated when compiling the contract with the `-ts` flag. const contract = await TokenContract.deploy(wallet, admin).send().deployed(); logger(`Contract deployed at ${contract.address}`); @@ -114,6 +134,7 @@ logger(`Contract deployed at ${contract.address}`); If everything went as expected you should see the following output (with a different address): + > Contract deployed at `0x151de6120ae6628129ee852c5fc7bcbc8531055f76d4347cdc86003bbea96906` If we pass the salt as an argument: @@ -129,7 +150,9 @@ aztec-cli deploy TokenContractArtifact --args 0x147392a39e593189902458f4303bc6e0 ```ts -const contract = await TokenContract.deploy(wallet, admin).send({ contractAddressSalt: Fr.fromString("0x123") }).deployed(); +const contract = await TokenContract.deploy(wallet, admin) + .send({ contractAddressSalt: Fr.fromString("0x123") }) + .deployed(); ``` diff --git a/docs/docs/dev_docs/contracts/setup.md b/docs/docs/dev_docs/contracts/setup.md index 1cce9766f89..ead7eedb8c0 100644 --- a/docs/docs/dev_docs/contracts/setup.md +++ b/docs/docs/dev_docs/contracts/setup.md @@ -22,13 +22,13 @@ Nargo is Noir's build tool. On your terminal, run: #### Aztec Sandbox -You need to setup the [Aztec sandbox](../getting_started/sandbox.md). +You need to setup the [Aztec sandbox](../getting_started/quickstart.md). ## Set up for aztec.nr contracts -1. Inside the yarn project you created from the [Sandbox page](../getting_started/sandbox.md), create a sub-folder where the contracts will reside. +1. Inside the yarn project you created from the [Sanbox page](../getting_started/quickstart.md), create a sub-folder where the contracts will reside. ```bash mkdir contracts diff --git a/docs/docs/dev_docs/getting_started/sandbox.md b/docs/docs/dev_docs/getting_started/aztecjs-getting-started.md similarity index 72% rename from docs/docs/dev_docs/getting_started/sandbox.md rename to docs/docs/dev_docs/getting_started/aztecjs-getting-started.md index 6bc905d2d15..e7be7d00720 100644 --- a/docs/docs/dev_docs/getting_started/sandbox.md +++ b/docs/docs/dev_docs/getting_started/aztecjs-getting-started.md @@ -1,78 +1,28 @@ --- -title: Aztec Sandbox +title: Getting Started with Aztec.js --- import Image from "@theme/IdealImage"; -## Introduction +In this guide, we will retrieving the Sandbox and deploy a pre-written contract to it using Aztec.js. -The Aztec Sandbox aims to provide a local development system against which you can build and test Aztec.nr contracts in a fast, safe, and free environment. - -:::info -For a quickstart checkout [the Quickstart section](./quickstart.md) -::: - -Here we will walkthrough the process of retrieving the Sandbox, installing the client libraries and using it to deploy and use a fully token contract on the Aztec network using Aztec.js. - -You can find the [complete tutorial code here](https://github.com/AztecProtocol/dev-rel/tree/main/tutorials/sandbox-tutorial/token). +This guide assumes you have followed the [quickstart](./quickstart.md). ## Prerequisites -- Node.js >= v18 -- Docker and Docker Compose (Docker Desktop under WSL2 on windows) - -That's it... - -## Install the Sandbox - -In your terminal: - -```sh -/bin/bash -c "$(curl -fsSL 'https://sandbox.aztec.network')" -``` - -It will download and execute a script invoking docker compose with 2 containers: - -- Anvil -- Aztec Sandbox - -3 ports will need to be opened on your system in order for you to interact with the sandbox. -The first port is for Anvil, it defaults to 8545 and can be overridden by specifying a value in the environment variable `SANDBOX_ANVIL_PORT`. -The second one is sandbox Aztec Node port, it defaults to 8079 and can be overridden by specifying a value in the environment variable `SANDBOX_AZTEC_NODE_PORT`. -The third is the sandbox PXE port. -It defaults to value 8080 but can be overridden with environment variable `SANDBOX_PXE_PORT`. - -Within a few seconds the Sandbox should be up and running! - - - -:::info -To start anvil in a fork mode set `FORK_URL` and `FORK_BLOCK_NUMBER` environment variables before running the script. -You can do so by running: -```sh -export FORK_URL=https://mainnet.infura.io/v3/your-infura-key -export FORK_BLOCK_NUMBER=13300000 -``` -If `FORK_BLOCK_NUMBER` is not set, it defaults to genesis block number. -::: +- A running [Aztec sandbox](./quickstart.md) -## Project setup +## Set up the project We will deploy a pre-compiled token contract, and send tokens privately, using the Sandbox. :::info -If you don't want to follow along and copy pasting step-by-step, the full code repository is available [here](https://github.com/AztecProtocol/dev-rel/tree/main/tutorials/sandbox-tutorial/token) +Find the full code [here](https://github.com/AztecProtocol/dev-rel/tree/main/tutorials/sandbox-tutorial/token) ::: -We will create a `yarn` project called `token` (although npm works fine too). If you are familiar with setting up Javascript/Typescript projects then you can skip to step 6. - -1. Ensure node version is 18 or higher by running - -```sh -node -v -``` +We will create a `yarn` project called `token` (although `npm` works fine too). -2. Initialize a yarn project +1. Initialize a yarn project ```sh mkdir token @@ -80,19 +30,19 @@ cd token yarn init -yp ``` -3. Create a `src` folder inside your new `token` directory: +2. Create a `src` folder inside your new `token` directory: ```sh mkdir src ``` -4. Add necessary yarn packages (and optionally add typescript too) +3. Add necessary yarn packages (and optionally add typescript too) ```sh yarn add @aztec/aztec.js @aztec/noir-contracts typescript @types/node ``` -5. [Optional] If creating a typescript file, add a `tsconfig.json` file into the project root, here is an example: +4. [Optional] If creating a typescript file, add a `tsconfig.json` file into the project root, here is an example: ```json { @@ -120,7 +70,7 @@ yarn add @aztec/aztec.js @aztec/noir-contracts typescript @types/node } ``` -6. Update `package.json` - Add a `scripts` section to `package.json` and set `"type": "module"`: +5. Update `package.json` - Add a `scripts` section to `package.json` and set `"type": "module"`: ```json { @@ -146,7 +96,7 @@ yarn add @aztec/aztec.js @aztec/noir-contracts typescript @types/node } ``` -7. Create an `index.ts` file in the `src` directory with the following sandbox connection setup: +6. Create an `index.ts` file in the `src` directory with the following sandbox connection setup: ```ts #include_code imports /yarn-project/end-to-end/src/e2e_sandbox_example.test.ts raw @@ -158,7 +108,7 @@ async function main() { main(); ``` -8. Finally, run the package: +7. Finally, run the package: In the project root, run @@ -166,7 +116,7 @@ In the project root, run yarn start ``` -A successful run should show: +A successful run should show something like this: ``` token Aztec Sandbox Info { @@ -199,9 +149,9 @@ A successful run should show: Great! The Sandbox is running and we are able to interact with it. -## Accounts +## Load accounts -The sandbox is preloaded with multiple accounts so you don't have to sit and create them. Let's load these accounts +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: #include_code load_accounts /yarn-project/end-to-end/src/e2e_sandbox_example.test.ts typescript @@ -209,15 +159,13 @@ An explanation on accounts on Aztec can be found [here](../../concepts/foundatio If you want more accounts, you can find instructions in the [Account creation section](../wallets/creating_schnorr_accounts.md). -## Token Contract Deployment - -Writing a contract from scratch is beyond the scope of this page. Feel free to look at the [Token contract tutorial](../tutorials/writing_token_contract.md) or the section on aztec-noir contracts [here](../contracts/main.md) +## Deploy a contract -Now that we have our accounts loaded, let's move on to deploy our pre-compiled token contract. Add this to `index.ts` below the code you added earlier: +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](https://github.com/AztecProtocol/aztec-packages/tree/master/yarn-project/noir-contracts/src/contracts/token_contract/src). Add this to `index.ts` below the code you added earlier: #include_code Deployment /yarn-project/end-to-end/src/e2e_sandbox_example.test.ts typescript -`yarn start` will now give the following output: +`yarn start` will now give something like this: ``` token Aztec Sandbox Info { @@ -264,14 +212,10 @@ We can break this down as follows: 6. Alice mints 1,000,000 tokens to be claimed by herself in private. 7. Alice redeems the tokens privately. -## Viewing the balance of an account +## View the balance of an account A token contract wouldn't be very useful if you aren't able to query the balance of an account. As part of the deployment, tokens were minted to Alice. We can now call the contract's `balance_of_private()` function to retrieve the balances of the accounts. -Here is the `balance_of_private` code from the contract (do not to paste it into `index.ts`): - -#include_code balance_of_private /yarn-project/noir-contracts/src/contracts/token_contract/src/main.nr rust - Call the `balance_of_private` function using the following code (paste this): #include_code Balance /yarn-project/end-to-end/src/e2e_sandbox_example.test.ts typescript @@ -324,11 +268,11 @@ No transaction is submitted as a result but a user's state can be queried. We can see that each account has the expected balance of tokens. -### Diagram of calling an unconstrained (view) function +### Calling an unconstrained (view) function Unconstrained function call -## Creating and submitting transactions +## Create and submit a transaction Now lets transfer some funds from Alice to Bob by calling the `transfer` function on the contract. This function takes 4 arguments: @@ -337,10 +281,6 @@ Now lets transfer some funds from Alice to Bob by calling the `transfer` functio 3. The quantity of tokens to be transferred. 4. The nonce for the [authentication witness](../../concepts//foundation/accounts/main.md#authorizing-actions), or 0 if msg.sender equal sender. -Here is the Noir code for the `transfer` function (don't paste this into `index.ts`): - -#include_code transfer /yarn-project/noir-contracts/src/contracts/token_contract/src/main.nr rust - Here is the Typescript code to call the `transfer` function, add this to your `index.ts` at the bottom of the `main` function: #include_code Transfer /yarn-project/end-to-end/src/e2e_sandbox_example.test.ts typescript @@ -397,24 +337,15 @@ This function takes: 1. A quantity of tokens to be minted. 2. A secret hash. -Here is the Noir code: - -#include_code mint_private /yarn-project/noir-contracts/src/contracts/token_contract/src/main.nr rust - -This function is public and it inserts a new note into the note hash tree and increases the total token supply by the amount minted. - -To make the note spendable the note has to be redeemed. -A user can do that by calling the `redeem_shield` function: - -#include_code redeem_shield /yarn-project/noir-contracts/src/contracts/token_contract/src/main.nr rust +This function is public and it inserts a new note into the private data tree and increases the total token supply by the amount minted. -Notice that this function is private and that it takes a secret as an input argument. +To make the note spendable the note has to be redeemed. A user can do that by calling the `redeem_shield` function. Let's now use these functions to mint some tokens to Bob's account using Typescript, add this to `index.ts`: #include_code Mint /yarn-project/end-to-end/src/e2e_sandbox_example.test.ts typescript -Our complete output should now be: +Our complete output should now be something like: ``` token Aztec Sandbox Info { @@ -459,16 +390,8 @@ Our complete output should now be: token Bob's balance 10543 +43ms ``` -That's it! We have successfully deployed a token contract to an instance of the Aztec network and mined private state-transitioning transactions. We have also queried the resulting state all via the interfaces provided by the contract. - -You can find the [complete tutorial code here](https://github.com/AztecProtocol/dev-rel/tree/main/tutorials/sandbox-tutorial/token). - -### Diagram of sending a transaction - -Sending a transaction +That's it! We have successfully deployed a token contract to an instance of the Aztec network and mined private state-transitioning transactions. We have also queried the resulting state all via the interfaces provided by the contract. To see exactly what has happened here, you can learn about the transaction flow [here](../../concepts/foundation/transactions.md). ## Next Steps -Here we showed how to interact with the sandbox, but didn't go into details on how to write your own contract or any relevant setup needed for it. - -You can find more information about writing Aztec contracts [here](../contracts/main.md) on syntax, compiling, deploying and interacting with how to start writing contracts. +Learn more about writing Aztec.nr contracts in the [Aztec.nr getting started guide](./aztecnr-getting-started.md). diff --git a/docs/docs/dev_docs/getting_started/aztecnr-getting-started.md b/docs/docs/dev_docs/getting_started/aztecnr-getting-started.md new file mode 100644 index 00000000000..02ab3114dde --- /dev/null +++ b/docs/docs/dev_docs/getting_started/aztecnr-getting-started.md @@ -0,0 +1,255 @@ +--- +title: Getting Started with Aztec.nr +--- + +In this guide, we will create our first Aztec.nr smart contract. We will build a simple private counter. This contract will get you started with the basic setup and syntax of Aztec.nr, but doesn't showcase the awesome stuff Aztec is capable of. + +If you already have some experience with Noir and want to build a cooler contract that utilizes both private and public state, you might want to check out the [token contract tutorial instead](../tutorials/writing_token_contract.md). + +## Prerequisites + +- You have followed the [quickstart](./quickstart.md) +- Running Aztec Sandbox + +## Install nargo + +`Aztec.nr` is a framework built on top of [Noir](https://noir-lang.org), a zero-knowledge DSL. Nargo is the build tool for Noir, similar to cargo for Rust. We need it for compiling our smart contracts. + + + +You can check it has been installed correctly by running: + +```bash +aztec-cli get-node-info +``` + +It should print something similar to: + +```bash +➜ ~ aztec-cli get-node-info + +Node Info: + +Version: 1 +Chain Id: 31337 +Rollup Address: 0xcf7ed3acca5a467e9e704c703e8d87f634fb0fc9 +Client: pxe@0.7.5 +Compatible Nargo Version: 0.16.0-aztec.0 +``` + +## Set up a project + +Create a new directory called `aztec-private-counter` + +```bash +mkdir aztec-private-counter +``` + +then create a `contracts` folder inside where our Aztec.nr contract will live: + +```bash +cd aztec-private-counter +mkdir contracts +``` + +Inside `contracts`, create a new Noir project using nargo: + +```bash +cd contracts +nargo new counter --contract +``` + +The `contract` flag will create a contract nargo project rather than using vanilla Noir. + +Your file structure should look like this: + +```bash +aztec-private-counter +|-contracts +| |--counter +| | |--src +| | | |--main.nr +| | |Nargo.toml +``` + +The file `main.nr` will soon turn into our smart contract! + +Your `Nargo.toml` file should look something like this: + +```toml +[package] +name = "counter" +type = "contract" +authors = [""] +compiler_version = "0.16.0" + +[dependencies] +``` + +Add the following dependencies under `[dependencies]`: + +```toml +aztec = { git="https://github.com/AztecProtocol/aztec-packages", tag="#include_aztec_version", directory="yarn-project/aztec-nr/aztec" } +value_note = { git="https://github.com/AztecProtocol/aztec-packages", tag="#include_aztec_version", directory="yarn-project/aztec-nr/value-note"} +easy_private_state = { git="https://github.com/AztecProtocol/aztec-packages", tag="#include_aztec_version", directory="yarn-project/aztec-nr/easy-private-state"} +``` + +## Define the functions + +Go to `main.nr` and replace the code with this contract initialization: + +```rust +contract Counter { +} +``` + +This defines a contract called `Counter`. + +## Imports + +We need to define some imports. + +Write this within your contract at the top + +#include_code imports /yarn-project/noir-contracts/src/contracts/counter_contract/src/main.nr rust + +`context::{PrivateContext, Context}` + +Context gives us access to the environment information such as `msg.sender`. We are also importing `PrivateContext` to access necessary information for our private functions. We’ll be using it in the next step. + +`map::Map` + +Map is a private state variable that functions like a dictionary, relating Fields to other state variables. You can learn more about it [here](../contracts/syntax/main.md). + +`value_note` + +Notes are fundamental to how Aztec manages privacy. A note is a privacy-preserving representation of an amount of tokens associated with an address, while encrypting the amount and owner. In this contract, we are using the `value_note` library. This is a type of note interface for storing a single Field, eg a balance - or, in our case, a counter. + +We are also using `balance_utils` from this import, a useful library that allows us to utilize value notes as if they are simple balances. + +`EasyPrivateUint` + +This allows us to store our counter in a way that acts as an integer, abstracting the note logic. + +## Implement a Storage struct + +In this step, we will initiate a `Storage` struct to store balances in a private way. The vast majority Aztec.nr smart contracts will need this. + +#include_code storage_struct /yarn-project/noir-contracts/src/contracts/counter_contract/src/main.nr rust + +We are only storing one variable - `counts` as a `Map` of `EasyPrivateUint`. This means our `count` will act as a private integer, and we can map it to an address. + +#include_code storage_init /yarn-project/noir-contracts/src/contracts/counter_contract/src/main.nr rust + +This `init` method is creating and initializing a `Storage` instance. This instance includes a `Map` named `counters`. Each entry in this `Map` represents an account's counter. + +## Keep the counter private + +Now we’ve got a mechanism for storing our private state, we can start using it to ensure the privacy of balances. + +Let’s create a `constructor` method to run on deployment that assigns an initial supply of tokens to a specified owner. In the constructor we created in the first step, write this: + +#include_code constructor /yarn-project/noir-contracts/src/contracts/counter_contract/src/main.nr rust + +This function accesses the counts from storage. Then it assigns the passed initial counter to the `owner`'s counter privately using `at().add()`. + +We have annotated this and other functions with `#[aztec(private)]` which are ABI macros so the compiler understands it will handle private inputs. Learn more about functions and annotations [here](../contracts/syntax/functions.md). + +## Incrementing our counter + +Now let’s implement the `increment` functio we defined in the first step. + +#include_code increment /yarn-project/noir-contracts/src/contracts/counter_contract/src/main.nr rust + +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. + +## Prevent double spending + +Because our counters are private, the network can't directly verify if a note was spent or not, which could lead to double-spending. To solve this, we use a nullifier - a unique identifier generated from each spent note and its owner. Although this isn't really an issue in this simple smart contract, Aztec requires a contract that has any private functions to include this function. + +Add a new function into your contract as shown below: + +#include_code nullifier /yarn-project/noir-contracts/src/contracts/counter_contract/src/main.nr rust + +Here, we're computing both the note hash and the nullifier. The nullifier computation uses Aztec’s `compute_note_hash_and_nullifier` function, which takes details about the note's attributes eg contract address, nonce, storage slot, and preimage. + +## Getting a counter + +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: + +#include_code get_counter /yarn-project/noir-contracts/src/contracts/counter_contract/src/main.nr rust + +This function is `unconstrained` which allows us to fetch data from storage without 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. + +## Test with the CLI + +Now we've written a simple Aztec.nr smart contract, it's time to ensure everything works by testing with the CLI. + +### Compile the smart contract + +In the root of the `nargo` project, run this: + +```bash +aztec-cli compile . +``` + +This will compile the smart contract and create a `target` folder with a `.json` artifact inside. + +### Deploy + +You can use the previously generated artificat to deploy the smart contract. Our constructor takes two arguments - `initial_counter` and `owner` so let's make sure to pass those in. + +`initial_counter` can be any uint. In this guide we'll pick 100, but you can pick anything. + +For the `owner` you can get the account addresses in your sandbox by running: + +```bash +aztec-cli get-accounts +``` + +This will return something like this: + +```bash +➜ counter aztec-cli get-accounts +Accounts found: + +Address: 0x25048e8c1b7dea68053d597ac2d920637c99523651edfb123d0632da785970d0 +Public Key: 0x27c20118733174347b8082f578a7d8fb84b3ad38be293715eee8119ee5cd8a6d0d6b7d8124b37359663e75bcd2756f544a93b821a06f8e33fba68cc8029794d9 +Partial Address: 0x077fed6015ea2e4aabfd566b16d9528e79dc0f1d8573716a3f4de1f02962e8c9 + +Address: 0x115f123bbc6cc6af9890055821cfba23a7c4e8832377a32ccb719a1ba3a86483 +Public Key: 0x08145e8e8d46f51cda8d4c9cad81920236366abeafb8d387002bad879a3e87a81570b04ac829e4c007141d856d5a36d3b9c464e0f3c1c99cdbadaa6bb93f3257 +Partial Address: 0x092908a7140034c7add7f2fac103abc41bedd5474cf09b1c9c16e5331282de77 + +Address: 0x0402655a1134f3f248e9f2032c27b26d2c3ab57eaab3189541895c13f3622eba +Public Key: 0x13e6151ea8e7386a5e7c4c5221047bf73d0b1b7a2ad14d22b7f73e57c1fa00c614bc6da69da1b581b09ee6cdc195e5d58ae4dce01b63bbb744e58f03855a94dd +Partial Address: 0x211edeb823ef3e042e91f338d0d83d0c90606dba16f678c701d8bb64e64e2be5 +``` + +Use one of these `address`es as the `owner`. You can either copy it or export. + +To deploy the counter contract, [ensure the sandbox is running](../cli/sandbox-reference.md) and run this in the root of your nargo project: + +```bash +aztec-cli deploy target/Counter.json --args 100 0x25048e8c1b7dea68053d597ac2d920637c99523651edfb123d0632da785970d0 +``` + +You can also test the functions by applying what you learned in the [quickstart](./quickstart.md). + +Congratulations, you have now written, compiled, and deployed your first Aztec.nr smart contract! + +## What's next? + +Now you can explore. + +**Interested in learning more about how Aztec works under the hood?** + +Understand the high level architecture [here](../../concepts/foundation/main.md). + +**Want to write more advanced smart contracts?** + +Follow the token contract tutorial [here](../tutorials/writing_token_contract.md). + +**Ready to dive into Aztec and Ethereum cross-chain communication?** + +Read the [Portals page](../../concepts/foundation/communication/cross_chain_calls.md) and learn how to practically implement portals in the [token bridge tutorial](../tutorials/token_portal/main.md). diff --git a/docs/docs/dev_docs/getting_started/main.md b/docs/docs/dev_docs/getting_started/main.md index 20ef05de9d5..cfa7fa20c2e 100644 --- a/docs/docs/dev_docs/getting_started/main.md +++ b/docs/docs/dev_docs/getting_started/main.md @@ -2,6 +2,14 @@ title: Getting Started --- +In this section, you will + +1. Set up the Aztec sandbox and deploy a sample first contract with the CLI +2. Deploy and interact with a contract using Aztec.js +3. Write your first smart contract in Aztec.nr + +The whole section should take you less than 60 minutes. + import DocCardList from '@theme/DocCardList'; diff --git a/docs/docs/dev_docs/getting_started/quickstart.md b/docs/docs/dev_docs/getting_started/quickstart.md index b31f4cccd18..4c9625f6320 100644 --- a/docs/docs/dev_docs/getting_started/quickstart.md +++ b/docs/docs/dev_docs/getting_started/quickstart.md @@ -2,92 +2,41 @@ title: Quickstart --- -Get started with the Aztec Sandbox. +In this guide, you will -## Introduction +1. Set up the Aztec sandbox locally +2. Install the Aztec CLI +3. Use the CLI to deploy an example contract that comes with the sandbox +4. Use the CLI to interact with the contract you just deployed -The Aztec Sandbox is an environment for local development on the Aztec Network. It's easy to get setup with just a single, simple command, and contains all the components needed to develop and test Aztec contracts and applications. +... in less than 10 minutes. -This is a 1 page introduction to getting started with running the sandbox, and interacting with it via the CLI. We will go over how to deploy a token contract to the sandbox, mint tokens and transfer them between accounts. You will find more in depth information on the following pages in this Getting Started section. - -### Background - -Aztec's Layer 2 network is a fully programmable combined private/public ZK rollup. To achieve this, the network contains the following primary components: - -- Aztec Node - Aggregates all of the 'backend' services necessary for the building and publishing of rollups. This packages is currently in development and much of the functionality is mocked. -- [Private Execution Environment (PXE)](https://github.com/AztecProtocol/aztec-packages/tree/master/yarn-project/pxe) - Normally residing with the end client, this decrypts and stores a client's private state, executes simulations and submits transactions to the Aztec Node. -- [Aztec.js](https://github.com/AztecProtocol/aztec-packages/tree/master/yarn-project/aztec.js) - Aztec's client library for interacting with the PXE (think Ethers.js). See the getting started guide [here](./sandbox.md). - -All of this is included in the Sandbox, with the exception of Aztec.js which you can use to interact with it. - -With the help of Aztec.js you will be able to: - -- Create an account -- Deploy a contract -- Call view methods on contracts -- Simulate the calling of contract functions -- Send transactions to the network -- Be notified when transactions settle -- Query chain state such as chain id, block number etc. - -This quickstart walks you through installing the Sandbox, deploying your first Noir contract, and verifying its execution! - -## Sandbox Contents - -The sandbox contains a local ethereum instance running [Anvil](https://book.getfoundry.sh/anvil/), a local instance of the Aztec rollup, an aztec private execution client for handling user transactions and state, and, if using Docker, an [Otterscan](https://github.com/otterscan/otterscan) block explorer for the local ethereum network. - -These provide a self contained environment which deploys Aztec on a local (empty) ethereum network, creates 3 smart contract wallet accounts on the rollup, and allows transactions to be processed on the local Aztec sequencer. - -The current sandbox does not generate or verify proofs, but provides a working end to end developer flow for writing and interacting with Aztec.nr smart contracts. - -## Requirements +## Prerequisites - Node.js >= v18 (recommend installing with [nvm](https://github.com/nvm-sh/nvm)) - Docker and Docker Compose (Docker Desktop under WSL2 on windows) -## Sandbox Installation - -You can run the Sandbox using either Docker or npm. +## Install the Sandbox -### With Docker +You can run the Sandbox using either Docker or npm. In this guide we will use Docker, but you can learn more about alternative installation methods [here](../cli/sandbox-reference.md). -To install and start the Sandbox paste the line below in a macOS Terminal or Linux shell prompt. You will need to have Docker installed and running on your machine. +To install the latest Sandbox version, run: ```bash /bin/bash -c "$(curl -fsSL 'https://sandbox.aztec.network')" ``` -This will attempt to run the Sandbox on localhost:8080, so you will have to make sure nothing else is running on that port or change the port defined in `./.aztec/docker-compose.yml`. Running the command again will overwrite any changes made to the docker-compose.yml. - -To install a specific version of the sandbox, you can set the environment variable `SANDBOX_VERSION` - -```bash -SANDBOX_VERSION= /bin/bash -c "$(curl -fsSL 'https://sandbox.aztec.network')" -``` - -NOTE: If `SANDBOX_VERSION` is not defined, the script will pull the latest release of the sandbox. The sandbox version should be the same as your `@aztec/cli` package to ensure compatibility. - -Once docker is up, you can see ethereum layer 1 activity through the local [otterscan](http://localhost:5100). This is especially useful for dapps that use L1-L2 messaging through [portal contracts](../contracts/portals/main.md). - -### With npm - -You can download and run the Sandbox package directly if you have nodejs 18 or higher installed. - -You will also need an Ethereum node like Anvil or Hardhat running locally on port 8545. - -```bash -npx @aztec/aztec-sandbox -``` +This will attempt to run the Sandbox on ` localhost:8080`, so you will have to make sure nothing else is running on that port or change the port defined in `./.aztec/docker-compose.yml`. Running the command again will overwrite any changes made to the `docker-compose.yml`. -## CLI Installation +## Install the CLI -To interact with the sandbox now that it's running locally, install the [Aztec CLI](https://www.npmjs.com/package/@aztec/cli): +To interact with the Sandbox now that it's running locally, install the [Aztec CLI](https://www.npmjs.com/package/@aztec/cli): ```bash npm install -g @aztec/cli ``` -## Deploying a contract +## Deploy a contract using the CLI The sandbox is preloaded with multiple accounts. Let's assign them to shell variables. Run the following in your terminal, so we can refer to the accounts as $ALICE and $BOB from now on: @@ -97,17 +46,17 @@ The default accounts that come with sandbox will likely change over time. Save t #include_code declare-accounts yarn-project/end-to-end/src/guides/up_quick_start.sh bash -Start by deploying a token contract. After it is deployed, we check that the deployment succeeded, export the deployment address to use in future commands and then call the `_initialize` function. For more detail on how the token contract works, see the [token contract tutorial](../tutorials/writing_token_contract.md). +Start by deploying a token contract. After it is deployed, we check that the deployment succeeded, and export the deployment address to use in future commands. For more detail on how the token contract works, see the [token contract tutorial](../tutorials/writing_token_contract.md). #include_code deploy yarn-project/end-to-end/src/guides/up_quick_start.sh bash Note that the deployed contract address is exported, so we can use it as `$CONTRACT` later on. -## Calling a contract +## Call a contract with the CLI Alice is set up as the contract admin and token minter in the `_initialize` function. Let's get Alice some private tokens. -We need to export the `SECRET` and `SECRET_HASH` values in order to privately mint tokens. Private tokens are claimable by anyone with the pre-image to a provided hash, see more about how the token contract works in the [token contract tutorial](../tutorials/writing_token_contract.md). After the tokens have been minted, the notes will have to added to the PXE to be consumed by private functions. Once added, Alice can claim them with the `redeem_shield` function. After this, Alice should have 1000 tokens in their private balance. +We need to export the `SECRET` and `SECRET_HASH` values in order to privately mint tokens. Private tokens are claimable by anyone with the pre-image to a provided hash, see more about how the token contract works in the [token contract tutorial](../tutorials/writing_token_contract.md). After the tokens have been minted, the notes will have to added to the [Private Execution Environment](../../apis/pxe/interfaces/PXE) (PXE) to be consumed by private functions. Once added, Alice can claim them with the `redeem_shield` function. After this, Alice should have 1000 tokens in their private balance. #include_code mint-private yarn-project/end-to-end/src/guides/up_quick_start.sh bash @@ -119,11 +68,8 @@ Alice and Bob should have 500 tokens. Congratulations! You are all set up with the Aztec sandbox! -## Great, but what can I do with it? +## What's next? -Aztec's Layer 2 network is a fully programmable combined private/public ZK rollup. To achieve this, the network contains the following primary components: +To start writing your first Aztec.nr smart contract, go to the [next page](aztecnr-getting-started.md). -- Aztec Node - Aggregates all of the 'backend' services necessary for the building and publishing of rollups. -- Private Execution Environment (PXE) - Normally residing with the end client, this decrypts and stores a client's private state, executes simulations and submits transactions to the Aztec Node. -- [Aztec.js](./sandbox) - Aztec's client library for interacting with the PXE (think Ethers.js). -- [Aztec.nr](../contracts/main.md) - Aztec's smart contract framework +You can also dig more into the sandbox and CLI [here](../cli/main.md). diff --git a/docs/docs/dev_docs/tutorials/testing.md b/docs/docs/dev_docs/tutorials/testing.md index bc6275ea0ee..aca41afc899 100644 --- a/docs/docs/dev_docs/tutorials/testing.md +++ b/docs/docs/dev_docs/tutorials/testing.md @@ -8,7 +8,7 @@ We will be using typescript to write our tests, and rely on the [`aztec.js`](htt ## A simple example -Let's start with a simple example for a test using the [Sandbox](../getting_started/sandbox.md#install-the-sandbox). We will create two accounts and deploy a token contract in a setup step, and then issue a transfer from one user to another. +Let's start with a simple example for a test using the [Sandbox](../cli/sandbox-reference.md). We will create two accounts and deploy a token contract in a setup step, and then issue a transfer from one user to another. #include_code sandbox-example /yarn-project/end-to-end/src/guides/dapp_testing.test.ts typescript diff --git a/docs/docs/dev_docs/tutorials/writing_dapp/main.md b/docs/docs/dev_docs/tutorials/writing_dapp/main.md index e62d4730127..95cedf910bb 100644 --- a/docs/docs/dev_docs/tutorials/writing_dapp/main.md +++ b/docs/docs/dev_docs/tutorials/writing_dapp/main.md @@ -12,7 +12,7 @@ The full code for this tutorial is [available on the `aztec-packages` repository - Linux or OSX environment - [NodeJS](https://nodejs.org/) 18 or higher -- [Aztec Sandbox](../../getting_started/sandbox.md) +- [Aztec Sandbox](../../getting_started/quickstart.md) - [Aztec CLI](../../cli/main.md) - [Nargo](../../contracts/setup.md) for building contracts diff --git a/docs/docs/dev_docs/tutorials/writing_dapp/pxe_service.md b/docs/docs/dev_docs/tutorials/writing_dapp/pxe_service.md index 9d75d1f4a98..38a54700c6a 100644 --- a/docs/docs/dev_docs/tutorials/writing_dapp/pxe_service.md +++ b/docs/docs/dev_docs/tutorials/writing_dapp/pxe_service.md @@ -4,7 +4,7 @@ PXE is a component of the Aztec Protocol that provides a private execution envir As an app developer, the [PXE](https://github.com/AztecProtocol/aztec-packages/tree/master/yarn-project/pxe) interface provides you with access to the user's accounts and their private state, as well as a connection to the network for accessing public global state. -During the Sandbox phase, this role is fulfilled by the [Aztec Sandbox](../../getting_started/sandbox.md), which runs a local PXE and an Aztec Node, both connected to a local Ethereum development node like Anvil. +During the Sandbox phase, this role is fulfilled by the [Aztec Sandbox](../../cli/sandbox-reference.md), which runs a local PXE and an Aztec Node, both connected to a local Ethereum development node like Anvil. The Sandbox also includes a set of pre-initialized accounts that you can use from your app. In this section, we'll connect to the Sandbox from our project. diff --git a/docs/docs/dev_docs/wallets/creating_schnorr_accounts.md b/docs/docs/dev_docs/wallets/creating_schnorr_accounts.md index 7b0a43c0a54..d3bda7700f1 100644 --- a/docs/docs/dev_docs/wallets/creating_schnorr_accounts.md +++ b/docs/docs/dev_docs/wallets/creating_schnorr_accounts.md @@ -13,7 +13,7 @@ An in-depth explaining about accounts on aztec can be found [here](../../concept ## Pre-requisites -Have a running Sandbox and a repository that interacts with it as explained [here](../getting_started/sandbox.md). +Have a running Sandbox and a repository that interacts with it as explained [here](../getting_started/quickstart.md). Let's assume you have a file `src/index.ts` from the example used in the Sandbox page. diff --git a/docs/docs/intro.md b/docs/docs/intro.md index f7dce2c8e8f..f6f5757ad43 100644 --- a/docs/docs/intro.md +++ b/docs/docs/intro.md @@ -41,9 +41,9 @@ Plus: ## Play -[Write a private smart contract today](./dev_docs/getting_started/quickstart). +Visit the [getting started](./dev_docs/getting_started/main) section for an introduction. -[Deploy to the Aztec Sandbox today](./dev_docs/getting_started/sandbox) +Go to the [Tutorials](./dev_docs/tutorials/main.md) section to dive into some more advanced walkthroughs. --- diff --git a/docs/netlify.toml b/docs/netlify.toml index 11f2bc45c62..6c21eafd525 100644 --- a/docs/netlify.toml +++ b/docs/netlify.toml @@ -166,6 +166,17 @@ from = "/dev_docs/contracts/syntax/state_variables" to = "/dev_docs/contracts/syntax/storage" +[[redirects]] + from = "/dev_docs/getting_started/sandbox" + to = "/dev_docs/getting_started/quickstart" + +[[redirects]] + from = "/dev_docs/getting_started/blank_box" + to = "/dev_docs/cli/blank_box" + +[[redirects]] + from = "/dev_docs/getting_started/updating" + to = "/dev_docs/cli/updating" [[redirects]] from = "/misc/aztec-connect-sunset" diff --git a/docs/sidebars.js b/docs/sidebars.js index 2e35c1d1e7d..ad1f4cc3832 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -198,9 +198,8 @@ const sidebars = { }, items: [ "dev_docs/getting_started/quickstart", - "dev_docs/getting_started/sandbox", - "dev_docs/getting_started/blank_box", - "dev_docs/getting_started/updating", + "dev_docs/getting_started/aztecjs-getting-started", + "dev_docs/getting_started/aztecnr-getting-started", ], }, @@ -267,6 +266,15 @@ const sidebars = { ], }, + { + label: "Aztec Sandbox and CLI", + type: "category", + link: { + type: "doc", + id: "dev_docs/cli/main", + }, + items: ["dev_docs/cli/cli-commands", "dev_docs/cli/sandbox-reference"], + }, { label: "Aztec.nr Contracts", type: "category", @@ -351,7 +359,17 @@ const sidebars = { ], }, - "dev_docs/cli/main", + { + label: "Aztec.js", + type: "doc", + id: "dev_docs/aztecjs/main", + }, + + { + label: "Updating", + type: "doc", + id: "dev_docs/cli/updating", + }, { label: "Testing", diff --git a/yarn-project/end-to-end/src/cli_docs_sandbox.test.ts b/yarn-project/end-to-end/src/cli_docs_sandbox.test.ts index 551a6806001..ad10e117ee4 100644 --- a/yarn-project/end-to-end/src/cli_docs_sandbox.test.ts +++ b/yarn-project/end-to-end/src/cli_docs_sandbox.test.ts @@ -96,6 +96,7 @@ Rollup Address: 0x0dcd1bf9a1b36ce34237eeafef220932846bcd82 BenchmarkingContractArtifact CardGameContractArtifact ChildContractArtifact +CounterContractArtifact DocsExampleContractArtifact EasyPrivateTokenContractArtifact EcdsaAccountContractArtifact diff --git a/yarn-project/noir-contracts/Nargo.toml b/yarn-project/noir-contracts/Nargo.toml index 8e491e4117f..9e72509a592 100644 --- a/yarn-project/noir-contracts/Nargo.toml +++ b/yarn-project/noir-contracts/Nargo.toml @@ -1,8 +1,9 @@ [workspace] members = [ - "src/contracts/benchmarking_contract", - "src/contracts/card_game_contract", - "src/contracts/child_contract", + "src/contracts/benchmarking_contract", + "src/contracts/card_game_contract", + "src/contracts/child_contract", + "src/contracts/counter_contract", "src/contracts/docs_example_contract", "src/contracts/easy_private_token_contract", "src/contracts/ecdsa_account_contract", diff --git a/yarn-project/noir-contracts/src/contracts/counter_contract/Nargo.toml b/yarn-project/noir-contracts/src/contracts/counter_contract/Nargo.toml new file mode 100644 index 00000000000..9c973675fe1 --- /dev/null +++ b/yarn-project/noir-contracts/src/contracts/counter_contract/Nargo.toml @@ -0,0 +1,10 @@ +[package] +name = "counter_contract" +authors = [""] +compiler_version = ">=0.18.0" +type = "contract" + +[dependencies] +aztec = { path = "../../../../aztec-nr/aztec" } +value_note = { path = "../../../../aztec-nr/value-note" } +easy_private_state = { path = "../../../../aztec-nr/easy-private-state"} \ No newline at end of file diff --git a/yarn-project/noir-contracts/src/contracts/counter_contract/src/main.nr b/yarn-project/noir-contracts/src/contracts/counter_contract/src/main.nr new file mode 100644 index 00000000000..18836e71827 --- /dev/null +++ b/yarn-project/noir-contracts/src/contracts/counter_contract/src/main.nr @@ -0,0 +1,79 @@ +contract Counter { +// docs:start:imports + use dep::aztec::{ + context::{PrivateContext, Context}, + note::{ + note_header::NoteHeader, + utils as note_utils, + }, + state_vars::map::Map, + }; + use dep::value_note::{ + balance_utils, + value_note::{ + ValueNoteMethods, + VALUE_NOTE_LEN, + }, + }; + use dep::easy_private_state::easy_private_state::EasyPrivateUint; +// docs:end:imports + +// docs:start:storage_struct + + struct Storage { + counters: Map, + } + +// docs:end:storage_struct + +// docs:start:storage_init + impl Storage { + fn init(context: Context) -> pub Self { + Storage { + counters: Map::new( + context, + 1, + |context, slot| { + EasyPrivateUint::new(context, slot) + }, + ), + } + } + } +// docs:end:storage_init + +// docs:start:constructor + #[aztec(private)] + fn constructor(headstart: u120, owner: Field) { + let counters = storage.counters; + counters.at(owner).add(headstart, owner); + } +// docs:end:constructor + +// docs:start:increment + #[aztec(private)] + fn increment(owner: Field) { + let counters = storage.counters; + counters.at(owner).add(1, owner); + } +// docs:end:increment + +// docs:start:get_counter + unconstrained fn get_counter(owner: Field) -> Field { + let counters = storage.counters; + balance_utils::get_balance(counters.at(owner).set) + } +// docs:end:get_counter + +// docs:start:nullifier + unconstrained fn compute_note_hash_and_nullifier( + contract_address: Field, + nonce: Field, + storage_slot: Field, + preimage: [Field; VALUE_NOTE_LEN], + ) -> [Field; 4] { + let note_header = NoteHeader::new(contract_address, nonce, storage_slot); + note_utils::compute_note_hash_and_nullifier(ValueNoteMethods, note_header, preimage) + } +// docs:end:nullifier +} \ No newline at end of file