diff --git a/.circleci/config.yml b/.circleci/config.yml index ae14946c3d81..336474a6a7a8 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -671,17 +671,6 @@ jobs: name: "Build" command: build ethereum - rollup-provider: - machine: - image: ubuntu-2004:202010-01 - resource_class: large - steps: - - *checkout - - *setup_env - - run: - name: "Build" - command: build rollup-provider - e2e-2-rpc-servers: machine: image: ubuntu-2004:202010-01 @@ -1315,8 +1304,6 @@ workflows: when: equal: [system, << pipeline.parameters.workflow >>] jobs: - - build-docs: *defaults - # Barretenberg - barretenberg-x86_64-linux-gcc: *defaults - barretenberg-x86_64-linux-clang: *defaults @@ -1409,7 +1396,8 @@ workflows: - l1-contracts - noir-contracts-build <<: *defaults - + + - build-docs: *yarn_project - aztec-js: *yarn_project - end-to-end: *yarn_project - ethereum: *yarn_project @@ -1430,7 +1418,6 @@ workflows: - sequencer-client: *yarn_project - types: *yarn_project - circuits-js: *yarn_project - - rollup-provider: *yarn_project - aztec-sandbox-base: *yarn_project - canary: *yarn_project @@ -1471,7 +1458,6 @@ workflows: - sequencer-client - types - circuits-js - - rollup-provider - aztec-sandbox-ecr-manifest - canary <<: *defaults diff --git a/barretenberg/cpp/src/barretenberg/bb/main.cpp b/barretenberg/cpp/src/barretenberg/bb/main.cpp index 2eae122b471f..72f0a95990c7 100644 --- a/barretenberg/cpp/src/barretenberg/bb/main.cpp +++ b/barretenberg/cpp/src/barretenberg/bb/main.cpp @@ -332,6 +332,14 @@ int main(int argc, char* argv[]) std::string vk_path = getOption(args, "-k", "./target/vk"); CRS_PATH = getOption(args, "-c", "./crs"); bool recursive = flagPresent(args, "-r") || flagPresent(args, "--recursive"); + + // Skip CRS initialization for any command which doesn't require the CRS. + if (command == "info") { + std::string output_path = getOption(args, "-o", "info.json"); + acvmInfo(output_path); + return 0; + } + init(); if (command == "prove_and_verify") { @@ -355,9 +363,6 @@ int main(int argc, char* argv[]) } else if (command == "vk_as_fields") { std::string output_path = getOption(args, "-o", vk_path + "_fields.json"); vkAsFields(vk_path, output_path); - } else if (command == "info") { - std::string output_path = getOption(args, "-o", "info.json"); - acvmInfo(output_path); } else { std::cerr << "Unknown command: " << command << "\n"; return 1; diff --git a/build_manifest.json b/build_manifest.json index 9379e39a965b..e142a8150068 100644 --- a/build_manifest.json +++ b/build_manifest.json @@ -220,10 +220,6 @@ "buildDir": "yarn-project", "projectDir": "yarn-project/prover-client" }, - "rollup-provider": { - "buildDir": "yarn-project", - "projectDir": "yarn-project/rollup-provider" - }, "aztec-node": { "buildDir": "yarn-project", "projectDir": "yarn-project/aztec-node" @@ -240,4 +236,4 @@ "buildDir": "yarn-project", "projectDir": "yarn-project/world-state" } -} \ No newline at end of file +} diff --git a/circuits/cpp/src/aztec3/circuits/apps/.test.cpp b/circuits/cpp/src/aztec3/circuits/apps/.test.cpp index d2bbc2cbd9db..9d841a0cebc5 100644 --- a/circuits/cpp/src/aztec3/circuits/apps/.test.cpp +++ b/circuits/cpp/src/aztec3/circuits/apps/.test.cpp @@ -208,7 +208,7 @@ TEST_F(state_var_tests, circuit_utxo_of_default_private_note_fr) .creator_address = msg_sender, .memo = 1234 }); - exec_ctx.finalise(); + exec_ctx.finalize(); // Here, we test that the shared_ptr of a note, stored within the exec_ctx, works. TODO: put this in its own little // test, instead of this ever-growing beast test. @@ -270,7 +270,7 @@ TEST_F(state_var_tests, circuit_utxo_set_of_default_private_notes_fr) .memo = 1234, }); - exec_ctx.finalise(); + exec_ctx.finalize(); // Here, we test that the shared_ptr of a note, stored within the exec_ctx, works. TODO: put this in its own little // test, instead of this ever-growing beast test. @@ -318,7 +318,7 @@ TEST_F(state_var_tests, circuit_initialise_utxo_of_default_singleton_private_not my_utxo.initialise({ .value = 100, .owner = owner_of_initialised_note }); - exec_ctx.finalise(); + exec_ctx.finalize(); // Here, we test that the shared_ptr of a note, stored within the exec_ctx, works. TODO: put this in its own little // test, instead of this ever-growing beast test. @@ -367,7 +367,7 @@ TEST_F(state_var_tests, circuit_modify_utxo_of_default_singleton_private_note_fr .owner = msg_sender, }); - exec_ctx.finalise(); + exec_ctx.finalize(); // Here, we test that the shared_ptr of a note, stored within the exec_ctx, works. TODO: put this in its own little // test, instead of this ever-growing beast test. diff --git a/circuits/cpp/src/aztec3/circuits/apps/function_execution_context.hpp b/circuits/cpp/src/aztec3/circuits/apps/function_execution_context.hpp index ad1b597f4ba1..ab48743b1192 100644 --- a/circuits/cpp/src/aztec3/circuits/apps/function_execution_context.hpp +++ b/circuits/cpp/src/aztec3/circuits/apps/function_execution_context.hpp @@ -67,7 +67,7 @@ template class FunctionExecutionContext { PrivateCircuitPublicInputs final_private_circuit_public_inputs{}; - bool is_finalised = false; + bool is_finalized = false; public: FunctionExecutionContext(Builder& builder, OracleWrapperInterface& oracle) @@ -101,8 +101,8 @@ template class FunctionExecutionContext { PrivateCircuitPublicInputs get_final_private_circuit_public_inputs() { // For safety, only return this if the circuit is complete. - if (!is_finalised) { - throw_or_abort("You need to call exec_ctx.finalise() in your circuit first."); + if (!is_finalized) { + throw_or_abort("You need to call exec_ctx.finalize() in your circuit first."); } return final_private_circuit_public_inputs; } @@ -287,7 +287,7 @@ template class FunctionExecutionContext { * TODO: Might need some refactoring. Roles between: Opcodes modifying exec_ctx members; and the exec_ctx directly * modifying its members, are somewhat blurred at the moment. */ - void finalise_utxos() + void finalize_utxos() { // Copy some vectors, as we can't control whether they'll be pushed-to further, when we call Note methods. auto new_nullifiers_copy = new_nullifiers; @@ -319,16 +319,16 @@ template class FunctionExecutionContext { std::copy(new_nonces.begin(), new_nonces.end(), std::back_inserter(new_nullifiers)); } - void finalise() + void finalize() { - finalise_utxos(); + finalize_utxos(); private_circuit_public_inputs.set_commitments(new_commitments); private_circuit_public_inputs.set_nullifiers(new_nullifiers); private_circuit_public_inputs.set_nullified_commitments(nullified_commitments); private_circuit_public_inputs.set_public(builder); final_private_circuit_public_inputs = private_circuit_public_inputs.remove_optionality().template to_native_type(); - is_finalised = true; + is_finalized = true; } }; diff --git a/circuits/cpp/src/aztec3/circuits/apps/test_apps/basic_contract_deployment/basic_contract_deployment.cpp b/circuits/cpp/src/aztec3/circuits/apps/test_apps/basic_contract_deployment/basic_contract_deployment.cpp index 2aff1c41490f..5a9e39fe27f3 100644 --- a/circuits/cpp/src/aztec3/circuits/apps/test_apps/basic_contract_deployment/basic_contract_deployment.cpp +++ b/circuits/cpp/src/aztec3/circuits/apps/test_apps/basic_contract_deployment/basic_contract_deployment.cpp @@ -43,7 +43,7 @@ OptionalPrivateCircuitPublicInputs constructor(FunctionExecutionContext& exe auto& public_inputs = exec_ctx.private_circuit_public_inputs; public_inputs.args_hash = compute_var_args_hash({ arg0, arg1, arg2 }); - exec_ctx.finalise(); + exec_ctx.finalize(); // info("public inputs: ", public_inputs); diff --git a/circuits/cpp/src/aztec3/circuits/apps/test_apps/escrow/deposit.cpp b/circuits/cpp/src/aztec3/circuits/apps/test_apps/escrow/deposit.cpp index 59d2ccb50d63..61703be8a8ca 100644 --- a/circuits/cpp/src/aztec3/circuits/apps/test_apps/escrow/deposit.cpp +++ b/circuits/cpp/src/aztec3/circuits/apps/test_apps/escrow/deposit.cpp @@ -55,7 +55,7 @@ OptionalPrivateCircuitPublicInputs deposit(FunctionExecutionContext& exec_ct auto& public_inputs = exec_ctx.private_circuit_public_inputs; public_inputs.args_hash = compute_var_args_hash({ amount, asset_id, memo }); - exec_ctx.finalise(); + exec_ctx.finalize(); // info("public inputs: ", public_inputs); diff --git a/circuits/cpp/src/aztec3/circuits/apps/test_apps/escrow/transfer.cpp b/circuits/cpp/src/aztec3/circuits/apps/test_apps/escrow/transfer.cpp index 51e1a0be733c..241fa2f5de19 100644 --- a/circuits/cpp/src/aztec3/circuits/apps/test_apps/escrow/transfer.cpp +++ b/circuits/cpp/src/aztec3/circuits/apps/test_apps/escrow/transfer.cpp @@ -95,7 +95,7 @@ OptionalPrivateCircuitPublicInputs transfer(FunctionExecutionContext& exec_c /// TODO: merkle membership check // public_inputs.historic_private_data_tree_root - exec_ctx.finalise(); + exec_ctx.finalize(); // info("public inputs: ", public_inputs); diff --git a/circuits/cpp/src/aztec3/circuits/apps/test_apps/escrow/withdraw.cpp b/circuits/cpp/src/aztec3/circuits/apps/test_apps/escrow/withdraw.cpp index fdba8ab35e1e..1e586bc242cd 100644 --- a/circuits/cpp/src/aztec3/circuits/apps/test_apps/escrow/withdraw.cpp +++ b/circuits/cpp/src/aztec3/circuits/apps/test_apps/escrow/withdraw.cpp @@ -83,7 +83,7 @@ OptionalPrivateCircuitPublicInputs withdraw(FunctionExecutionContext& exec_c auto& public_inputs = exec_ctx.private_circuit_public_inputs; public_inputs.args_hash = compute_var_args_hash({ amount, asset_id, memo, l1_withdrawal_address, fee }); - exec_ctx.finalise(); + exec_ctx.finalize(); /// TODO: merkle membership check // public_inputs.historic_private_data_tree_root diff --git a/circuits/cpp/src/aztec3/circuits/apps/test_apps/private_to_private_function_call/function_1_1.cpp b/circuits/cpp/src/aztec3/circuits/apps/test_apps/private_to_private_function_call/function_1_1.cpp index 4377da64a9b5..13507d6b83c3 100644 --- a/circuits/cpp/src/aztec3/circuits/apps/test_apps/private_to_private_function_call/function_1_1.cpp +++ b/circuits/cpp/src/aztec3/circuits/apps/test_apps/private_to_private_function_call/function_1_1.cpp @@ -80,7 +80,7 @@ void function_1_1(FunctionExecutionContext& exec_ctx, std::vector const& auto& public_inputs = exec_ctx.private_circuit_public_inputs; public_inputs.args_hash = compute_var_args_hash({ a, b, c }); - exec_ctx.finalise(); + exec_ctx.finalize(); }; } // namespace aztec3::circuits::apps::test_apps::private_to_private_function_call \ No newline at end of file diff --git a/circuits/cpp/src/aztec3/circuits/apps/test_apps/private_to_private_function_call/function_2_1.cpp b/circuits/cpp/src/aztec3/circuits/apps/test_apps/private_to_private_function_call/function_2_1.cpp index ac424411667e..ba5f5197e594 100644 --- a/circuits/cpp/src/aztec3/circuits/apps/test_apps/private_to_private_function_call/function_2_1.cpp +++ b/circuits/cpp/src/aztec3/circuits/apps/test_apps/private_to_private_function_call/function_2_1.cpp @@ -63,7 +63,7 @@ void function_2_1(FunctionExecutionContext& exec_ctx, std::vector const& public_inputs.return_values[0] = product; - exec_ctx.finalise(); + exec_ctx.finalize(); // info("public inputs: ", public_inputs); diff --git a/docs/Dockerfile b/docs/Dockerfile index 572658476eb6..eb5071dc4f22 100644 --- a/docs/Dockerfile +++ b/docs/Dockerfile @@ -1,10 +1,14 @@ -FROM node:18-alpine -RUN apk update +FROM 278380418400.dkr.ecr.eu-west-2.amazonaws.com/yarn-project-base AS builder WORKDIR /usr/src COPY . . +WORKDIR /usr/src/yarn-project + +RUN yarn build + WORKDIR /usr/src/docs -RUN yarn && yarn build \ No newline at end of file +RUN yarn && yarn build + diff --git a/docs/README.md b/docs/README.md index 625823e2be1c..d07cc7f39814 100644 --- a/docs/README.md +++ b/docs/README.md @@ -56,10 +56,12 @@ Most changes are reflected live without having to restart the server. $ yarn build ``` -This command generates static content into the `build` directory and can be served using any static contents hosting service. +This command generates static content into the `build` directory and can be served using any static contents hosting service. When run on Netlify, it will also build the typescript projects needed for extracting type information via typedoc. -## #include_code macro +## Macros + +### `#include_code` You can embed code snippets into a `.md`/`.mdx` file from code which lives elsewhere in the repo. - In your markdown file: @@ -119,7 +121,26 @@ You can embed code snippets into a `.md`/`.mdx` file from code which lives elsew - `#include_code hello path/from/repo/root/to/file.ts typescript noTitle,noLineNumbers,noSourceLink` - Ironically, we can't show you a rendering of these examples, because this README.md file doesn't support the `#include_code` macro! +> See [here](./src/components/GithubCode/index.js) for another way to include code, although this approach is flakier, so the above `#include_code` macro is preferred. + +### `#include_aztec_version` + +This macros will be replaced inline with the current aztec packages tag, which is `aztec-packages-v0.7.10` at the time of these writing. This value is sourced from `.release-please-manifest.json` on the project root. -### Another way to include code. +Alternatively, you can also use the `AztecPackagesVersion()` js function, which you need to import explicitly: + +``` +import { AztecPackagesVersion } from "@site/src/components/Version"; +<>{AztecPackagesVersion()} +``` -See [here](./src/components/GithubCode/index.js), although this approach is flakier, so the above `#include_code` macro is preferred. \ No newline at end of file + ### `#include_noir_version` + +This macros will be replaced inline with the required nargo version, which is `0.11.1-aztec.0` at the time of these writing. This value is sourced from `yarn-project/noir-compiler/src/noir-version.json`. + +Alternatively, you can also use the `NoirVersion()` js function, which you need to import explicitly: + +``` +import { NoirVersion } from "@site/src/components/Version"; +<>{NoirVersion()} +``` diff --git a/docs/docs/.gitignore b/docs/docs/.gitignore new file mode 100644 index 000000000000..6fa7731468dd --- /dev/null +++ b/docs/docs/.gitignore @@ -0,0 +1 @@ +/apis diff --git a/docs/docs/about_aztec/overview.mdx b/docs/docs/about_aztec/overview.mdx index 8c291ba3747b..0e38c8a1dbd4 100644 --- a/docs/docs/about_aztec/overview.mdx +++ b/docs/docs/about_aztec/overview.mdx @@ -52,7 +52,7 @@ Contributors to Aztec uphold many of the values of the Ethereum community -- bui Noir is a domain specific programming language for writing zero knowledge circuits. On Aztec a smart contract is a collection of circuits that developers write using Noir. -You can find more information and resources for learning about Noir smart contracts on [this page](../dev_docs/getting_started/noir_contracts.md). +You can find more information and resources for learning about Noir smart contracts on [this page](../dev_docs/contracts/main.md). ## Cryptography diff --git a/docs/docs/concepts/advanced/contract_creation.md b/docs/docs/concepts/advanced/contract_creation.md index 2b9f66499eaa..9e054f5eacb7 100644 --- a/docs/docs/concepts/advanced/contract_creation.md +++ b/docs/docs/concepts/advanced/contract_creation.md @@ -327,4 +327,4 @@ Adds initial public state variables to the public data tree. ## Further reading -To see how to deploy a contract in practice, check out the [dapp development tutorial](../../dev_docs/dapps/tutorials/main.md). +To see how to deploy a contract in practice, check out the [dapp development tutorial](../../dev_docs/tutorials/writing_dapp/main.md). diff --git a/docs/docs/concepts/advanced/data_structures/indexed_merkle_tree.md b/docs/docs/concepts/advanced/data_structures/indexed_merkle_tree.md index 5e61e570052c..927a4e6a3876 100644 --- a/docs/docs/concepts/advanced/data_structures/indexed_merkle_tree.md +++ b/docs/docs/concepts/advanced/data_structures/indexed_merkle_tree.md @@ -9,6 +9,10 @@ import Disclaimer from "../../../misc/common/\_disclaimer.mdx"; ## Indexed Merkle Trees +This article will introduce the concept of an indexed merkle tree, and how it can be used to improve the performance of nullifier trees in circuits. The content was also covered in a presentation for the [Privacy + Scaling Explorations team at the Ethereum Foundation](https://pse.dev/). + + + #### Primer on Nullifier Trees Currently the only feasible way to get privacy in public blockchains is via a UTXO model. In this model, state is stored in encrypted UTXO's in merkle trees. However, to maintain privacy, state can not be updated. The very act of performing an update leaks information. In order to simulate "updating" the state, we "destroy" old UTXO's and create new ones for each state update. Resulting in a merkle tree that is append-only. diff --git a/docs/docs/concepts/foundation/communication/cross_chain_calls.md b/docs/docs/concepts/foundation/communication/cross_chain_calls.md index 4daf9672a056..86554a820901 100644 --- a/docs/docs/concepts/foundation/communication/cross_chain_calls.md +++ b/docs/docs/concepts/foundation/communication/cross_chain_calls.md @@ -77,7 +77,7 @@ The L2 -> L1 pending messages set only exist logically, as it is practically unn ### Rollup Contract -The rollup contract has a few very important responsibilities. The contract must keep track of the _L2 rollup state root_, perform _state transitions_ and ensure that the data is available for anyone else to synchronise to the current state. +The rollup contract has a few very important responsibilities. The contract must keep track of the _L2 rollup state root_, perform _state transitions_ and ensure that the data is available for anyone else to synchronize to the current state. To ensure that _state transitions_ are performed correctly, the contract will derive public inputs for the **rollup circuit** based on the input data, and then use a _verifier_ contract to validate that inputs correctly transition the current state to the next. All data needed for the public inputs to the circuit must be from the rollup block, ensuring that the block is available. For a valid proof, the _rollup state root_ is updated and it will emit an _event_ to make it easy for anyone to find the data by event spotting. diff --git a/docs/docs/dev_docs/cli/cli.md b/docs/docs/dev_docs/cli/cli.md deleted file mode 100644 index 4e238b9e1d3f..000000000000 --- a/docs/docs/dev_docs/cli/cli.md +++ /dev/null @@ -1,144 +0,0 @@ ---- -title: CLI Tutorial ---- - -## Introduction - -The Aztec CLI is a tool designed to enable a user to interact with the Aztec Network. - -This tutorial will use the Aztec Sandbox so you should first set it up by following [the Aztec Sandbox instructions](../getting_started/quickstart.md). - -## Requirements - -You should also 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 -``` - -## 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 `AZTEC_RPC_HOST` 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 abi, 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 - -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 initialises 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 the private token contract using the `deploy` command, minting 1000000 initial tokens to address `0x175310d40cd3412477db1c2a2188efd586b63d6830115fbb46c592a6303dbf6c`. 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= -``` - -:::info -If you use a different address in the constructor above, you will get an error when running the deployment. This is because you need to register an account in the sandbox before it can receive private notes. When you create a new account, it gets automatically registered. Alternatively, you can register an account you do not own along with its public key using the `register-recipient` command. -::: - -This command takes 1 mandatory positional argument which is the path to the contract ABI 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 takes a few optional arguments while the most important one is: - -- `--args` - Arguments to the constructor of the contract. In this case we have minted 1000000 initial tokens to the aztec address 0x20d3321707d53cebb168568e25c5c62a853ae1f0766d965e00d6f6c4eb05d599. - -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 - -## Calling a View Method - -When we deployed the token contract, an initial supply of tokens was minted to the address provided in the constructor. We can now query the `getBalance()` method on the contract to retrieve the balance of that address. Make sure to replace the `contract-address` with the deployment address you got from the previous command, and the `args` with the account you used in the constructor. - -#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-abi` - The abi 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 balance of 1000000, as expected. When using the Sandbox, you are able to query the balance of any account that has been created in the system, even the accounts created by default. You may wonder why this is, as you haven't provided the private keys for these accounts. The Sandbox contains a component known as the AztecRPCServer. When an account is created, this component stores the provided encryption private key and is able to read the account's private state meaning that the Sandbox can report the balance of any of it's accounts. More information about the account model can be found [here](../../concepts/foundation/accounts/main.md). - -## Sending a Transaction - -We can now send a transaction to the network. We will transfer funds from the owner of the initial minted tokens to our other account. For this we will use the `send` command, which expects as arguments the quantity of tokens to be transferred, the sender's address, and the recipient's address. Make sure to replace all addresses in this command with the ones for your run. - -#include_code send yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash - -We called the `transfer` function of the contract and provided these arguments: - -- `--args` - The list of arguments to the function call. -- `--contract-abi` - The abi of the contract to call. -- `--contract-address` - The deployed address of the contract to call. -- `--private-key` - The private key of the sender - -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 - -Let's now call `getBalance()` on each of our accounts and we should see updated values: - -#include_code calls yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash diff --git a/docs/docs/dev_docs/cli/main.md b/docs/docs/dev_docs/cli/main.md index 1236ed75bf5d..363677b4c2e1 100644 --- a/docs/docs/dev_docs/cli/main.md +++ b/docs/docs/dev_docs/cli/main.md @@ -2,7 +2,7 @@ title: Aztec CLI --- -## What is the Aztec CLI? +## Introduction The Aztec CLI is a command-line tool allowing the user to interact directly with the Aztec Network. @@ -10,14 +10,139 @@ It aims to provide all of the functionality required to deploy and invoke contra ## Requirements -The Aztec CLI is provided as an npm package containing an installed binary. It can be installed by using: +You should have [node.js](https://nodejs.org/en/download) installed with version >= 18. -`yarn global add @aztec/cli` +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]` -## Getting Started +## 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 `AZTEC_RPC_HOST` 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 abi, 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 + +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 the private token contract using the `deploy` command, minting 1000000 initial tokens to address `0x175310d40cd3412477db1c2a2188efd586b63d6830115fbb46c592a6303dbf6c`. 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= +``` + +:::info +If you use a different address in the constructor above, you will get an error when running the deployment. This is because you need to register an account in the sandbox before it can receive private notes. When you create a new account, it gets automatically registered. Alternatively, you can register an account you do not own along with its public key using the `register-recipient` command. +::: + +This command takes 1 mandatory positional argument which is the path to the contract ABI 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 takes a few optional arguments while the most important one is: + +- `--args` - Arguments to the constructor of the contract. In this case we have minted 1000000 initial tokens to the aztec address 0x20d3321707d53cebb168568e25c5c62a853ae1f0766d965e00d6f6c4eb05d599. + +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 + +## Calling a View Method + +When we deployed the token contract, an initial supply of tokens was minted to the address provided in the constructor. We can now query the `getBalance()` method on the contract to retrieve the balance of that address. Make sure to replace the `contract-address` with the deployment address you got from the previous command, and the `args` with the account you used in the constructor. + +#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-abi` - The abi 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 balance of 1000000, as expected. When using the Sandbox, you are able to query the balance of any account that has been created in the system, even the accounts created by default. You may wonder why this is, as you haven't provided the private keys for these accounts. The Sandbox contains a component known as the AztecRPCServer. When an account is created, this component stores the provided encryption private key and is able to read the account's private state meaning that the Sandbox can report the balance of any of it's accounts. More information about the account model can be found [here](../../concepts/foundation/accounts/main.md). + +## Sending a Transaction + +We can now send a transaction to the network. We will transfer funds from the owner of the initial minted tokens to our other account. For this we will use the `send` command, which expects as arguments the quantity of tokens to be transferred, the sender's address, and the recipient's address. Make sure to replace all addresses in this command with the ones for your run. + +#include_code send yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash + +We called the `transfer` function of the contract and provided these arguments: + +- `--args` - The list of arguments to the function call. +- `--contract-abi` - The abi of the contract to call. +- `--contract-address` - The deployed address of the contract to call. +- `--private-key` - The private key of the sender + +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 + +Let's now call `getBalance()` on each of our accounts and we should see updated values: -To get up and running with the Aztec CLI head over to the [getting start page](./cli.md). +#include_code calls yarn-project/end-to-end/src/cli_docs_sandbox.test.ts bash diff --git a/docs/docs/dev_docs/contracts/common_errors.md b/docs/docs/dev_docs/contracts/common_errors.md index ce96e27ed09d..cefaa8535fbe 100644 --- a/docs/docs/dev_docs/contracts/common_errors.md +++ b/docs/docs/dev_docs/contracts/common_errors.md @@ -1,9 +1,53 @@ -# Errors - -List common errors. +# Common Errors There are two kinds of errors: errors in an Aztec.nr contract, and errors spat out by an Aztec Sandbox node! +This section will provide an overview of the errors you might encounter, and how to fix them. + +### Assertion Error + +This error is thrown when a condition is not met. + +This is what the error typically looks like: +``` +Simulation error: Assertion failed: Balance too low 'sum == amount' +``` + +To address the error. find the line in the contract that is throwing the error and investigate why the condition is not met. + +### Unknown Contract Error +This error occurs when you are trying to interact with a smart contract via an Aztec RPC Server that does not have the necessary information to execute a transaction. + +This is what the error typically looks like: +``` +Unknown contract 0x1d206be10b873b78b875259e1a8c39e2212e2f181d2fd0b0407446487deba522: add it to Aztec RPC server by calling server.addContracts(...) +``` + +To execute a transaction, the Aztec RPC Server needs to know the complete address of a contract, portal address (if portal is used) and contract artifacts. + +To address the error, add the contract to the Aztec RPC Server by calling `server.addContracts(...)`. + +### Unknown Complete Address Error +This error occurs when your contract is trying to get a public key via the `get_public_key` oracle call, but the Aztec RPC Server does not have the Complete Address (Complete Address contains the public key). + +This is what the error typically looks like: +``` +Simulation error: Unknown complete address for address 0x0d179a5f9bd4505f7dfb8ca37d64e0bd0cd31b5cb018e252fd647bdf88959b95. Add the information to Aztec RPC server by calling server.registerRecipient(...) or server.registerAccount(...) +``` + +Your contract typically needs a public key when it wants to send a note to a recipient because the public key is used to encrypt notes. + +:::info +Manually adding the recipient to the Aztec RPC Server should not be required in case the recipient contract has already been deployed and the Aztec RPC Server is fully synced. +This is because this information is submitted on-chain when the recipient contract is deployed. +::: + +### Unknown account +This error occurs when your contract is trying to get a secret via the `get_secret` oracle call, but the Aztec RPC Server does not have the secret for the public key. -Maybe even auto-generate error docs, based on error codes in our codebase. +This is what the error typically looks like: +``` +Could not process note because of "Error: Unknown account.". Skipping note... +``` -Make sure descriptions of errors relate to the end user experience. An error like 'SegFault' is useless to a contract developer! \ No newline at end of file +This error might occurr when you register an account only as a recipient and not as an account. +To address the error, register the account by calling `server.registerAccount(...)`. \ No newline at end of file diff --git a/docs/docs/dev_docs/contracts/compiling.md b/docs/docs/dev_docs/contracts/compiling.md index 071a7b56bec3..ac14588acfbd 100644 --- a/docs/docs/dev_docs/contracts/compiling.md +++ b/docs/docs/dev_docs/contracts/compiling.md @@ -102,25 +102,25 @@ impl PrivateTokenPrivateContextInterface { fn mint( self, context: &mut PrivateContext, amount: Field, owner: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 2]; - serialised_args[0] = amount; - serialised_args[1] = owner; + let mut serialized_args = [0; 2]; + serialized_args[0] = amount; + serialized_args[1] = owner; // 0x1dc9c3c0 is the function selector for `mint(field,field)` - context.call_private_function(self.address, 0x1dc9c3c0, serialised_args) + context.call_private_function(self.address, 0x1dc9c3c0, serialized_args) } fn transfer( self, context: &mut PrivateContext, amount: Field, sender: Field, recipient: Field ) -> [Field; RETURN_VALUES_LENGTH] { - let mut serialised_args = [0; 3]; - serialised_args[0] = amount; - serialised_args[1] = sender; - serialised_args[2] = recipient; + let mut serialized_args = [0; 3]; + serialized_args[0] = amount; + serialized_args[1] = sender; + serialized_args[2] = recipient; // 0xdcd4c318 is the function selector for `transfer(field,field,field)` - context.call_private_function(self.address, 0xdcd4c318, serialised_args) + context.call_private_function(self.address, 0xdcd4c318, serialized_args) } } ``` @@ -145,7 +145,7 @@ The compiler exposes the following functions: ## Next steps -Once you have compiled your contracts, you can use the generated artifacts via the `Contract` class in the `aztec.js` package to deploy and interact with them, or rely on the type-safe typescript classes directly. Alternatively, use the CLI [to deploy](../../dev_docs/cli/cli.md#deploying-a-token-contract) and [interact](../../dev_docs/cli/cli.md#sending-a-transaction) with them. +Once you have compiled your contracts, you can use the generated artifacts via the `Contract` class in the `aztec.js` package to deploy and interact with them, or rely on the type-safe typescript classes directly. Alternatively, use the CLI [to deploy](../../dev_docs/cli/main.md#deploying-a-token-contract) and [interact](../../dev_docs/cli/main.md#sending-a-transaction) with them. import Disclaimer from "../../misc/common/\_disclaimer.mdx"; diff --git a/docs/docs/dev_docs/contracts/deploying.md b/docs/docs/dev_docs/contracts/deploying.md index 7b2fd05163ee..a2e5795a8f9c 100644 --- a/docs/docs/dev_docs/contracts/deploying.md +++ b/docs/docs/dev_docs/contracts/deploying.md @@ -4,8 +4,8 @@ Once you have [compiled](./compiling.md) your contracts you can proceed to deplo ## Prerequisites - aztec-cli installed (go to [CLI main section](../cli/main.md) for installation instructions) -- contract artifacts ready (go to [Compiling contracts section](../contracts/compiling.md) for instructions on how to compile contracts) -- aztec-sandbox running (go to [Sandbox section](../sandbox/main.md) for instructions on how to install and run the sandbox) +- 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) ## Deploy diff --git a/docs/docs/dev_docs/contracts/layout.md b/docs/docs/dev_docs/contracts/layout.md index 50832159f1aa..c7943e6d8173 100644 --- a/docs/docs/dev_docs/contracts/layout.md +++ b/docs/docs/dev_docs/contracts/layout.md @@ -35,4 +35,4 @@ Here's a common layout for a basic Aztec.nr Contract project: ``` - See the vanilla Noir docs for [more info on packages](https://noir-lang.org/modules_packages_crates/crates_and_packages). -- You can review the structure of a complete contract in the token contract tutorial [here](../getting_started/token_contract_tutorial.md). +- You can review the structure of a complete contract in the token contract tutorial [here](../tutorials/writing_token_contract.md). diff --git a/docs/docs/dev_docs/contracts/main.md b/docs/docs/dev_docs/contracts/main.md index e6c83b59bae8..24eb96e379c9 100644 --- a/docs/docs/dev_docs/contracts/main.md +++ b/docs/docs/dev_docs/contracts/main.md @@ -20,15 +20,20 @@ An **Aztec smart contract** is a smart contract with **private** state variables ## Install Noir -To write an Aztec.nr contract, you need to write Noir, and to write Noir, you need to [install Nargo](https://noir-lang.org/getting_started/nargo_installation). +To write an Aztec.nr contract, you need to write Noir, which requires a build tool called Nargo: + + +:::info +For those coming from vanilla Noir, the nargo version used for aztec.nr is tracked seaprately to nargo for vanilla noir, so be sure to use the nargo version shown above +::: ## Install Noir tooling There are a number of tools to make writing Aztec.nr contracts more pleasant. See [here](https://github.com/noir-lang/awesome-noir#get-coding). -## Quickstart +## Tutorials -See the [contracts quickstart](../getting_started/noir_contracts.md) for more info on getting set up to write contracts. +See the [Standard Token Contract tutorial](../tutorials/writing_token_contract.md) for more info on getting set up to write contracts. ## Learn more diff --git a/docs/docs/dev_docs/contracts/setup.md b/docs/docs/dev_docs/contracts/setup.md new file mode 100644 index 000000000000..0501e90195e3 --- /dev/null +++ b/docs/docs/dev_docs/contracts/setup.md @@ -0,0 +1,95 @@ +--- +title: Setup +--- + +import { AztecPackagesVersion } from "@site/src/components/Version"; + +## Introduction + +This guide explains the set up required to write a contract using the Aztec.nr library. + +:::info Prerequisite reading +If you haven't read about [Aztec.nr](./main.md), we recommend going there first. +::: + +### Dependencies + +#### `nargo` + +Nargo is Noir's build tool. On your terminal, run: + + + +#### Aztec Sandbox + +You need to setup the [Aztec sandbox](../getting_started/sandbox.md). + + + +## Set up for aztec.nr contracts + +1. Inside the yarn project you created from the [Sanbox page](../getting_started/sandbox.md), create a sub-folder where the contracts will reside. + +```bash +mkdir contracts +``` + +All contract projects will reside within this folder. Note that contracts don't actually have to live here and this is just a style choice. + +2. Next, create a noir project using nargo by running the following in the terminal from the `contracts` folder + +```bash +cd contracts +nargo new --contract example_contract +``` + +This creates `example_contract` directory within contracts which is a noir project with: + +- a Nargo.toml (which is the manifest file of the project) at `example_contract/Nargo.toml`. +- a main.nr file (the file where our contract will reside) at `example_contract/src/main.nr`. + +Your folder should look like: + +```tree +. +|-contracts +| |--example_contract +| | |--src +| | | |--main.nr +| | |--Nargo.toml +|-src +| |--index.ts +``` + +Before writing the contracts, we must add the aztec.nr library. This adds smart contract utility functions for interacting with the Aztec network. + +3. Finally, add relevant aztec-nr dependencies that you might use such as `aztec.nr`, `value_note` and `safe_math` libraries. + +Open Nargo.toml that is in the `contracts/example_contract` folder, and add the dependency section as follows + +```toml +[package] +name = "example_contract" +authors = [""] +compiler_version = "0.1" +type = "contract" + +[dependencies] +# Framework import +aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="yarn-project/aztec-nr/aztec" } + +# Utility dependencies +value_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="yarn-project/aztec-nr/value-note"} +safe_math = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="yarn-project/aztec-nr/safe-math"} +``` + +:::info +Note: currently the dependency name **_MUST_** be `aztec`. The framework expects this namespace to be available when compiling into contracts. This limitation may be removed in the future. +::: + +You are now ready to write your own contracts! + +## Next Steps + +- Read up about how to [write a contract](./syntax/main.md) OR +- Follow a [tutorial](../tutorials/main.md) diff --git a/docs/docs/dev_docs/contracts/syntax/functions.md b/docs/docs/dev_docs/contracts/syntax/functions.md index 93e2f0a58872..da39abcdef82 100644 --- a/docs/docs/dev_docs/contracts/syntax/functions.md +++ b/docs/docs/dev_docs/contracts/syntax/functions.md @@ -38,7 +38,7 @@ While `staticcall` and `delegatecall` both have flags in the call context, they ## `constructor` - A special `constructor` function MUST be declared within a contract's scope. -- A constructor doesn't have a name, because its purpose is clear: to initialise contract state. +- A constructor doesn't have a name, because its purpose is clear: to initialize contract state. - In Aztec terminology, a constructor is always a '`private` function' (i.e. it cannot be a `public` function, in the current version of the sandbox it cannot call public functions either). - A constructor behaves almost identically to any other function. It's just important for Aztec to be able to identify this function as special: it may only be called once, and will not be deployed as part of the contract. diff --git a/docs/docs/dev_docs/contracts/syntax/main.md b/docs/docs/dev_docs/contracts/syntax/main.md index c89e97a1a2db..59c7d8a7f7ba 100644 --- a/docs/docs/dev_docs/contracts/syntax/main.md +++ b/docs/docs/dev_docs/contracts/syntax/main.md @@ -1,4 +1,5 @@ import DocCardList from '@theme/DocCardList'; +import { AztecPackagesVersion } from "@site/src/components/Version"; # Aztec.nr Syntax @@ -16,27 +17,6 @@ Aztec.nr contains abstractions which remove the need to understand the low-level - secrets - Functions for communicating with [Ethereum L1](../portals/main.md) -To import Aztec.nr into your Aztec contract project, simply include it as a dependency. For example: - -import { AztecPackagesVersion } from "@site/src/components/Version"; - -{`[package] -name = "token_contract" -authors = [""] -compiler_version = "0.1" -type = "contract" - -[dependencies] -# Framework import -aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="${AztecPackagesVersion()}", directory="yarn-project/aztec-nr/aztec" } - -# Utility dependencies -value_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="${AztecPackagesVersion()}", directory="yarn-project/aztec-nr/value-note"} -safe_math = { git="https://github.com/AztecProtocol/aztec-packages/", tag="${AztecPackagesVersion()}", directory="yarn-project/aztec-nr/safe-math"} -`} - -:::info -Note: currently the dependency name ***MUST*** be `aztec`. The framework expects this namespace to be available when compiling into contracts. This limitation may be removed in the future. -::: +To setup a aztec-nr project, follow the [setup instructions](../setup.md) diff --git a/docs/docs/dev_docs/contracts/syntax/state_variables.md b/docs/docs/dev_docs/contracts/syntax/state_variables.md index c9868cc47bfb..830d35388240 100644 --- a/docs/docs/dev_docs/contracts/syntax/state_variables.md +++ b/docs/docs/dev_docs/contracts/syntax/state_variables.md @@ -2,9 +2,9 @@ title: State Variables --- -State variables come in two flavours: [**public** state](#publicstatet-t_serialised_len) and [**private** state](#private-state-variables). +State variables come in two flavours: [**public** state](#publicstatet-t_serialized_len) and [**private** state](#private-state-variables). -## `PublicState` +## `PublicState` Public state is persistent state that is _publicly visible_ to anyone in the world. @@ -12,7 +12,7 @@ For developers coming from other blockchain ecosystems (such as Ethereum), this Aztec public state follows an account-based model. That is, each state occupies a leaf in an account-based merkle tree: the public state tree. See [here](/concepts/advanced/data_structures/trees#public-state-tree) for more of the technical details. -The `PublicState` struct serves as a wrapper around conventional Noir types `T`, allowing these types to be written to and read from the public state tree. +The `PublicState` struct serves as a wrapper around conventional Noir types `T`, allowing these types to be written to and read from the public state tree. ### `::new` @@ -22,13 +22,13 @@ In the following example, we define a public state with a boolean type: #include_code state_vars-PublicState /yarn-project/noir-contracts/src/contracts/docs_example_contract/src/main.nr rust -The BoolSerialisationMethods is part of the Aztec stdlib: +The BoolSerializationMethods is part of the Aztec stdlib: #include_code state_vars-PublicStateBoolImport /yarn-project/noir-contracts/src/contracts/docs_example_contract/src/main.nr rust -It contains methods that instruct its PublicState wrapper how to serialise and deserialise a boolean to and from a Field, which is the data type being saved in the public state tree. +It contains methods that instruct its PublicState wrapper how to serialize and deserialize a boolean to and from a Field, which is the data type being saved in the public state tree. -The Aztec stdlib provides serialization methods for various common types. Check [here](https://github.com/AztecProtocol/aztec-packages/blob/master/yarn-project/aztec-nr/aztec/src/types/type_serialisation) for the complete list. +The Aztec stdlib provides serialization methods for various common types. Check [here](https://github.com/AztecProtocol/aztec-packages/blob/master/yarn-project/aztec-nr/aztec/src/types/type_serialization) for the complete list. ### Custom types @@ -36,17 +36,17 @@ It's possible to create a public state for any types. Simply define methods that The methods should be implemented in a struct that conforms to the following interface: -#include_code TypeSerialisationInterface /yarn-project/aztec-nr/aztec/src/types/type_serialisation.nr rust +#include_code TypeSerializationInterface /yarn-project/aztec-nr/aztec/src/types/type_serialization.nr rust For example, to create a public state for the following type: #include_code state_vars-CustomStruct /yarn-project/noir-contracts/src/contracts/docs_example_contract/src/types/queen.nr rust -First, define how to serialise and deserialise the custom type: +First, define how to serialize and deserialize the custom type: #include_code state_vars-PublicStateCustomStruct /yarn-project/noir-contracts/src/contracts/docs_example_contract/src/types/queen.nr rust -And then initialise the PublicState with it: +And then initialize the PublicState with it: #include_code state_vars-PublicStateCustomStruct /yarn-project/noir-contracts/src/contracts/docs_example_contract/src/main.nr rust @@ -66,7 +66,7 @@ Every public state can be read before its value is written. The default value is The currently-stored value of a private state variable can be overwritten with `.write()`. -Due to the way public states are [declared](#new), a public state knows how to serialise a given value and store it in the protocol's public state tree. +Due to the way public states are [declared](#new), a public state knows how to serialize a given value and store it in the protocol's public state tree. We can pass the associated type directly to the `write()` method: @@ -133,7 +133,7 @@ The interplay between a private state variable and its notes can be confusing. H ## `Singleton` -Singleton is a private state variable that is unique in a way. When a Singleton is initialised, a note is created to represent its value. And the way to update the value is to destroy the current note, and create a new one with the updated value. +Singleton is a private state variable that is unique in a way. When a Singleton is initialized, a note is created to represent its value. And the way to update the value is to destroy the current note, and create a new one with the updated value. ### `::new` @@ -141,15 +141,15 @@ Here we define a Singleton for storing a `CardNote`: #include_code state_vars-Singleton /yarn-project/noir-contracts/src/contracts/docs_example_contract/src/main.nr rust -### `.initialise` +### `.initialize` -The initial value of a Singleton is set via calling `initialise`: +The initial value of a Singleton is set via calling `initialize`: #include_code state_vars-SingletonInit /yarn-project/noir-contracts/src/contracts/docs_example_contract/src/actions.nr rust -When this function is called, a nullifier of the storage slot is created, preventing this Singleton from being initialised again. +When this function is called, a nullifier of the storage slot is created, preventing this Singleton from being initialized again. -Unlike public states, which have a default initial value of `0` (or many zeros, in the case of a struct, array or map), a private state (of type `Singleton`, `ImmutableSingleton` or `Set`) does not have a default initial value. The `initialise` method (or `insert`, in the case of a `Set`) must be called. +Unlike public states, which have a default initial value of `0` (or many zeros, in the case of a struct, array or map), a private state (of type `Singleton`, `ImmutableSingleton` or `Set`) does not have a default initial value. The `initialize` method (or `insert`, in the case of a `Set`) must be called. ### `.replace` @@ -179,9 +179,9 @@ In the following example, we define an ImmutableSingleton that utilises the `Rul #include_code state_vars-ImmutableSingleton /yarn-project/noir-contracts/src/contracts/docs_example_contract/src/main.nr rust -### `.initialise` +### `.initialize` -Set the initial value of an ImmutableSingleton by calling the `initialise` method: +Set the initial value of an ImmutableSingleton by calling the `initialize` method: #include_code state_vars-ImmutableSingletonInit /yarn-project/noir-contracts/src/contracts/docs_example_contract/src/actions.nr rust @@ -195,7 +195,7 @@ Use this method to retrieve the value of an initialized ImmutableSingleton: Unlike a [`singleton`](#get_note-1), the `get_note` function for an ImmutableSingleton doesn't destroy the current note in the background. This means that multiple accounts can concurrently call this function to read the value. -This function will throw if the ImmutableSingleton hasn't been initialised. +This function will throw if the ImmutableSingleton hasn't been initialized. ## `Set` @@ -269,11 +269,11 @@ Several methods are available on `NoteGetterOptions` to construct the options in #### `fn new() -> NoteGetterOptions` -This function initialises a `NoteGetterOptions` that simply returns the maximum number of notes allowed in a call. +This function initializes a `NoteGetterOptions` that simply returns the maximum number of notes allowed in a call. #### `fn with_filter(filter, filter_args) -> NoteGetterOptions` -This function initialises a `NoteGetterOptions` with a [`filter`](#filter-fn-optionnote-max_read_requests_per_call-filter_args---optionnote-max_read_requests_per_call) and [`filter_args`](#filter_args-filter_args). +This function initializes a `NoteGetterOptions` with a [`filter`](#filter-fn-optionnote-max_read_requests_per_call-filter_args---optionnote-max_read_requests_per_call) and [`filter_args`](#filter_args-filter_args). #### `.select` @@ -347,7 +347,7 @@ The `NoteViewerOptions` is essentially similar to the [`NoteGetterOptions`](#not ## `Map` -`Map` is a state variable that maps a `Field` to another state variable, which can be [`PublicState`](#publicstatet-t_serialised_len), all the [private state variables](#private-state-variables), and even another Map. +`Map` is a state variable that maps a `Field` to another state variable, which can be [`PublicState`](#publicstatet-t_serialized_len), all the [private state variables](#private-state-variables), and even another Map. > `Map` can map from `Field` or any native Noir type which is convertible to `Field`. diff --git a/docs/docs/dev_docs/contracts/workflow.md b/docs/docs/dev_docs/contracts/workflow.md index eb4641cbc8d1..f0d9bbe1b9d1 100644 --- a/docs/docs/dev_docs/contracts/workflow.md +++ b/docs/docs/dev_docs/contracts/workflow.md @@ -2,6 +2,9 @@ title: Contract Workflow --- +## Setup +[Set up your project](./setup.md) + ## Write [Write a contract](./syntax/main.md). diff --git a/docs/docs/dev_docs/getting_started/noir_contracts.md b/docs/docs/dev_docs/getting_started/noir_contracts.md deleted file mode 100644 index 65adc75609fd..000000000000 --- a/docs/docs/dev_docs/getting_started/noir_contracts.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -title: Aztec.nr Contracts Quickstart ---- - -## Introduction - -This guide explains the set up required to write a contract using the Aztec.nr library; then deploy it to the sandbox. Aztec.nr is a library on top of [Noir](https://noir-lang.org/) that can be used to write smart contracts for Aztec. Since Noir files use the `.nr` extension, we are calling this library "Aztec.nr". - -:::info Prerequisite reading -If you haven't read [Aztec Sandbox](./sandbox.md), we recommend going there first. -::: - -### Dependencies - -#### `nargo` - -Nargo is Noir's build tool. On your terminal, run: - - - -#### Aztec Sandbox - -You need to setup the [Aztec sandbox](./sandbox.md). - - - -## Set up for aztec.nr contracts - -1. Inside the yarn project you created from the [Aztec.js](./sandbox.md) page, create a sub-folder where the contracts will reside. - -```bash -mkdir contracts -``` - -All contract projects will reside within this folder. Note that contracts don't actually have to live here and this is just a style choice. - -2. Next, create a noir project using nargo by running the following in the terminal from the `contracts` folder - -```bash -cd contracts -nargo new example_contract -``` - -This creates a noir project with a Nargo.toml (which is the manifest file of the project). This file is found at `example_contract/src/main.nr`, where we will write our contract. - -Your folder should look like: - -``` -. -|-contracts -| |--example_contract -| | |--src -| | | |--main.nr -|-src -| |--index.ts -``` - -Before writing the contracts, we must add the aztec.nr library. This adds smart contract utility functions for interacting with the Aztec network. - -3. Add aztec.nr library as a dependency to your noir project. Open Nargo.toml that is in the `contracts/example_contract` folder, and add the dependency section as follows: - -import { AztecPackagesVersion } from "@site/src/components/Version"; - -{`[package] -name = "example_contract" -authors = [""] -compiler_version = "0.1" -type = "contract" - -[dependencies] -aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="master", directory="yarn-project/aztec-nr/aztec" } -`} - -:::note -You may need to update your dependencies depending on the contract that you are writing. For example, the token contract [imports more](../getting_started/token_contract_tutorial#project-setup). -::: - -You are now ready to write your own contracts! - -You can replace the content of the generated file `example_contract/src/main.nr` with your contract code. - -## Next Steps - -- You can learn more about writing contracts from the [Contracts section](../contracts/main.md). -- You can find more example Aztec contracts [here](https://github.com/AztecProtocol/aztec-packages/tree/master/yarn-project/noir-contracts/src/contracts). -- Consider going through the [token contract tutorial](./token_contract_tutorial.md) for a deep dive on writing more advanced Aztec contracts and an introduction to some of the concepts that underpin the Aztec network architecture. -- After writing the contract, you have to compile it. Details can be found [here](../contracts/compiling.md). -- After compiling, you can deploy your contract to the Aztec network. Relevant instructions and explanations can be found [here](../contracts/deploying.md). -- Thereafter, you can interact with the contracts similar to how it was shown in the the [Creating and submitting transactions section on the Sandbox page](./sandbox.md#creating-and-submitting-transactions). diff --git a/docs/docs/dev_docs/getting_started/quickstart.md b/docs/docs/dev_docs/getting_started/quickstart.md index f75879a0a74e..51e0233b0d5f 100644 --- a/docs/docs/dev_docs/getting_started/quickstart.md +++ b/docs/docs/dev_docs/getting_started/quickstart.md @@ -87,7 +87,7 @@ 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](./token_contract_tutorial). +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). #include_code deploy yarn-project/end-to-end/src/guides/up_quick_start.sh bash @@ -97,7 +97,7 @@ Note that the deployed contract address is exported, so we can use it as `$CONTR 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](./token_contract_tutorial.md). Once the tokens have been minted, 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). Once the tokens have been minted, 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 @@ -116,4 +116,5 @@ Aztec's Layer 2 network is a fully programmable combined private/public ZK rollu - Aztec Node - Aggregates all of the 'backend' services necessary for the building and publishing of rollups. - Aztec RPC Server - 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 Aztec RPC Server (think Ethers.js). -- [Write your own contracts](./noir_contracts.md) +- [Aztec.nr](../contracts/main.md) - Aztec's smart contract framework + diff --git a/docs/docs/dev_docs/getting_started/sandbox.md b/docs/docs/dev_docs/getting_started/sandbox.md index 32a663537474..b61591004006 100644 --- a/docs/docs/dev_docs/getting_started/sandbox.md +++ b/docs/docs/dev_docs/getting_started/sandbox.md @@ -8,18 +8,24 @@ import Image from "@theme/IdealImage"; 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 private token contract on the Aztec network using Aztec.js. -## What do you need? +You can find the [complete tutorial code here](https://github.com/AztecProtocol/dev-rel/tree/main/tutorials/sandbox-tutorial/token). + +## Prerequisites - Node.js >= v18 - Docker and Docker Compose (Docker Desktop under WSL2 on windows) That's it... -## Ok, so how do I try it out? +## Install the Sandbox -You can just curl the site like this: +In your terminal: ```sh /bin/bash -c "$(curl -fsSL 'https://sandbox.aztec.network')" @@ -36,17 +42,15 @@ Within a few seconds the Sandbox should be up and running! -## I have the Sandbox running, show me how to use it - -We will deploy a token contract, and send tokens privately, using the Sandbox. You can see the final result of the [tutorial code here](https://github.com/AztecProtocol/dev-rel/tree/main/tutorials/sandbox-tutorial/token), if you don't want to follow along, copy and pasting the example code. +## Project setup -Writing the contract itself is out of scope for this tutorial, so we will use a Token Contract which has been pre-supplied as an example. See [here](../contracts/main.md) for more information on how to write contracts for Aztec. +We will deploy a pre-compiled token contract, and send tokens privately, using the Sandbox. -The following should work for MacOS, Linux or even WSL2 Ubuntu under Windows. +:::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) +::: -Let's create an empty project called `token`. If you are familiar with setting up Typescript projects then you can skip to step 6. - -Although both `yarn` and `npm` would work, this example uses `yarn`. Open the terminal and do the following +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 @@ -59,22 +63,22 @@ node -v ```sh mkdir token cd token -yarn init +yarn init -yp ``` -1. Create a `src` folder inside your new `token` directory: +3. Create a `src` folder inside your new `token` directory: ```sh mkdir src ``` -4. Add typescript to the yarn project +4. Add necessary yarn packages (and optionally add typescript too) ```sh -yarn add typescript @types/node --dev +yarn add @aztec/aztec.js @aztec/noir-contracts typescript @types/node ``` -Add a `tsconfig.json` file into the project root, here is an example: +5. [Optional] If creating a typescript file, add a `tsconfig.json` file into the project root, here is an example: ```json { @@ -102,7 +106,7 @@ Add a `tsconfig.json` file into the project root, here is an example: } ``` -5. Add a `scripts` section to `package.json` and set `"type": "module"`: +6. Update `package.json` - Add a `scripts` section to `package.json` and set `"type": "module"`: ```json { @@ -119,20 +123,22 @@ Add a `tsconfig.json` file into the project root, here is an example: "clean": "rm -rf ./dest tsconfig.tsbuildinfo", "start": "yarn build && DEBUG='token' node ./dest/index.js" }, - "devDependencies": { - "@types/node": "^20.4.9", - "typescript": "^5.1.6" + "dependencies": { + "@aztec/aztec.js": "^0.7.10", + "@aztec/noir-contracts": "^0.7.10", + "@types/node": "^20.6.3", + "typescript": "^5.2.2" } } ``` -6. Next, install Aztec related dependencies +7. Next, install Aztec related dependencies ```sh yarn add @aztec/aztec.js @aztec/noir-contracts ``` -7. Create an `index.ts` file in the `src` directory with the following sandbox connection setup: +8. 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 @@ -144,7 +150,9 @@ async function main() { main(); ``` -8. Finally, run the package: +9. Finally, run the package: + +In the project root, run ```sh yarn start @@ -166,48 +174,21 @@ A successful run should show: Great! The Sandbox is running and we are able to interact with it. -## Account Creation/Deployment - -The next step is to create some accounts. An in-depth explaining about accounts on aztec can be found [here](../../concepts/foundation/accounts/main.md). But creating an account on the Sandbox does 2 things: +## Accounts -1. Deploys an account contract -- representing you -- allowing you to perform actions on the network (deploy contracts, call functions etc). -2. Adds your encryption keys to the RPC Server allowing it to decrypt and manage your private state. +The sandbox is preloaded with multiple accounts so you don't have to sit and create them. Let's load these accounts -Continue with adding the following to the `index.ts` file in our example: +#include_code load_accounts /yarn-project/end-to-end/src/e2e_sandbox_example.test.ts typescript -#include_code Accounts /yarn-project/end-to-end/src/e2e_sandbox_example.test.ts typescript +An explanation on accounts on Aztec can be found [here](../../concepts/foundation/accounts/main.md). -Running `yarn start` should now output: - -``` - token Aztec Sandbox Info { - version: 1, - chainId: 31337, - rollupAddress: EthAddress { - buffer: - }, - client: 'aztec-rpc@0.1.0', - compatibleNargoVersion: '0.11.1-aztec.0' - } - token Creating accounts using schnorr signers... +3ms - token Created Alice's account at 0x1509b252...0027 +10s - token Created Bob's account at 0x031862e8...e7a3 +0ms -``` - -That might seem like a lot to digest but it can be broken down into the following steps: - -1. We create 2 `Account` objects in Typescript. This object heavily abstracts away the mechanics of configuring and deploying an account contract and setting up a 'wallet' for signing transactions. If you aren't interested in building new types of account contracts or wallets then you don't need to be too concerned with it. In this example we have constructed account contracts and corresponding wallets that sign/verify transactions using schnorr signatures. -2. We wait for the deployment of the 2 account contracts to complete. -3. We retrieve the expected account addresses from the `Account` objects and ensure that they are present in the set of account addresses registered on the Sandbox. - -Note, we use the `getRegisteredAccounts` API to verify that the addresses computed as part of the -account contract deployment have been successfully added to the Sandbox. - -If you were looking at your terminal that is running the Sandbox you should have seen a lot of activity. This is because the Sandbox will have simulated the deployment of both contracts, executed the private kernel circuit for each before submitted 2 transactions to the pool. The sequencer will have picked them up and inserted them into a rollup and executed the recursive rollup circuits before publishing the rollup to Anvil. Once this has completed, the rollup is retrieved and pulled down to the internal RPC Server so that any new account state can be decrypted. +If you want more accounts, you can find instructions in the [Account creation section](../wallets/creating_schnorr_accounts.md). ## Token Contract Deployment -Now that we have our accounts setup, let's move on to deploy our private token contract. Add this to `index.ts` below the code you added earlier: +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) + +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: #include_code Deployment /yarn-project/end-to-end/src/e2e_sandbox_example.test.ts typescript @@ -369,4 +350,4 @@ You can find the [complete tutorial code here](https://github.com/AztecProtocol/ 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](./noir_contracts.md) and refer to the [Contracts section](../contracts/main.md) on syntax, compiling, deploying and interacting with how to start writing contracts. +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. diff --git a/docs/docs/dev_docs/getting_started/updating.md b/docs/docs/dev_docs/getting_started/updating.md new file mode 100644 index 000000000000..cb0662ca63ca --- /dev/null +++ b/docs/docs/dev_docs/getting_started/updating.md @@ -0,0 +1,91 @@ +--- +title: Updating +--- + +There are 4 components whose versions need to be kept compatible: +1. Aztec Sandbox, +2. Aztec CLI, +3. Noir compiler `nargo`, +4. Noir framework for Aztec contracts `aztec.nr`. + +Aztec Sandbox, Aztec CLI and `aztec.nr` are using the same versioning scheme and their versions must match. +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')" +``` + +It will download and start the latest version of sandbox. + +If you would like to use a fixed version of the sandbox, you can export the `SANDBOX_VERSION` environmental variable. +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 +``` + +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... +``` + +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 + +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 +Finally we need to update the Noir framework for Aztec contracts. +We need to install a version compatible with our `nargo` and Sandbox. + +To update the framework we will update a tag of the `aztec.nr` dependency in the `Nargo.toml` file to the `SANDBOX_VERSION` from above. +Find all the dependencies pointing to the directory within `aztec.nr` framework and update the corresponding tag. +E.g.: + +```diff +[dependencies] +-aztec = { git="https://github.com/AztecProtocol/aztec-packages", tag="aztec-packages-v0.7.5", directory="yarn-project/aztec-nr/aztec" } ++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="aztec-packages-v0.7.5", directory="yarn-project/aztec-nr/value-note" } ++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: +```shell +cd /your/project/root +aztec-cli compile ./ +``` + +If the dependencies fail to resolve ensure that the tag matches a tag in the [aztec-packages repository](https://github.com/AztecProtocol/aztec-packages/tags). diff --git a/docs/docs/dev_docs/sandbox/main.md b/docs/docs/dev_docs/sandbox/main.md deleted file mode 100644 index 66d4e60c755e..000000000000 --- a/docs/docs/dev_docs/sandbox/main.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: Aztec Sandbox ---- - -## What is the Aztec Sandbox? - -The Aztec Sandbox is local development system against which you can build and test Aztec.nr contracts in a fast, safe, and free environment. - -For a complete walk-through deploying and using a private contract with the Sandbox and CLI, see our [quickstart](../getting_started/quickstart). diff --git a/docs/docs/dev_docs/sandbox/common_errors.md b/docs/docs/dev_docs/sandbox_errors/main.md similarity index 99% rename from docs/docs/dev_docs/sandbox/common_errors.md rename to docs/docs/dev_docs/sandbox_errors/main.md index c13345e00ddc..1c6561d02ca7 100644 --- a/docs/docs/dev_docs/sandbox/common_errors.md +++ b/docs/docs/dev_docs/sandbox_errors/main.md @@ -31,7 +31,7 @@ You cannot execute a public Aztec.nr function in the private kernel #### 2011 - PRIVATE_KERNEL__UNSUPPORTED_OP You are trying to do something that is currently unsupported in the private kernel. If this is a blocker feel free to open up an issue on our monorepo [aztec3-packages](https://github.com/AztecProtocol/aztec3-packages/tree/master) or reach out to us on discord -Note that certain operations are unsupported on certain versions of the private kernel. Eg static calls are allowed for all but the initial iteration of the private kernel (which initialises the kernel for subsequent function calls). +Note that certain operations are unsupported on certain versions of the private kernel. Eg static calls are allowed for all but the initial iteration of the private kernel (which initializes the kernel for subsequent function calls). #### 2012 - PRIVATE_KERNEL__CONTRACT_ADDRESS_MISMATCH For the initial iteration of the private kernel, only the expected Aztec.nr contract should be the entrypoint. Static and delegate calls are not allowed in the initial iteration. diff --git a/docs/docs/dev_docs/testing/cheat_codes.md b/docs/docs/dev_docs/testing/cheat_codes.md index 4e2ca1ac0997..3fd12b183256 100644 --- a/docs/docs/dev_docs/testing/cheat_codes.md +++ b/docs/docs/dev_docs/testing/cheat_codes.md @@ -458,13 +458,13 @@ The baseSlot is specified in the Aztec.nr contract. ```rust struct Storage { - balances: Map>, + balances: Map>, } impl Storage { fn init() -> Self { Storage { - balances: Map::new(1, |slot| PublicState::new(slot, FieldSerialisationMethods)), + balances: Map::new(1, |slot| PublicState::new(slot, FieldSerializationMethods)), } } } @@ -496,13 +496,13 @@ Note: One Field element occupies a storage slot. Hence, structs with multiple fi ```rust struct Storage { - balances: Map>, + balances: Map>, } impl Storage { fn init() -> Self { Storage { - balances: Map::new(1, |slot| PublicState::new(slot, FieldSerialisationMethods)), + balances: Map::new(1, |slot| PublicState::new(slot, FieldSerializationMethods)), } } } diff --git a/docs/docs/dev_docs/tutorials/main.md b/docs/docs/dev_docs/tutorials/main.md new file mode 100644 index 000000000000..da6889b6fc80 --- /dev/null +++ b/docs/docs/dev_docs/tutorials/main.md @@ -0,0 +1,3 @@ +import DocCardList from '@theme/DocCardList'; + + diff --git a/docs/docs/dev_docs/testing/testing.md b/docs/docs/dev_docs/tutorials/testing.md similarity index 96% rename from docs/docs/dev_docs/testing/testing.md rename to docs/docs/dev_docs/tutorials/testing.md index d8bdf31adbe7..e00bccd1a81f 100644 --- a/docs/docs/dev_docs/testing/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](../sandbox/main.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. +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. #include_code sandbox-example /yarn-project/end-to-end/src/guides/dapp_testing.test.ts typescript @@ -127,7 +127,7 @@ In the near future, transactions where a public function call fails will get min We can check private or public state directly rather than going through view-only methods, as we did in the initial example by calling `token.methods.balance().view()`. Bear in mind that directly accessing contract storage will break any kind of encapsulation. -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](../contracts/syntax/storage.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` utility class: +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](../contracts/syntax/storage.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`](./../testing/cheat_codes.md) utility class: #include_code calc-slot /yarn-project/end-to-end/src/guides/dapp_testing.test.ts typescript @@ -163,7 +163,7 @@ We can query the RPC server for the unencrypted logs emitted in the block where ## Cheats -The `CheatCodes` class, which we used for [calculating the storage slot above](#state), also includes a set of cheat methods for modifying the chain state that can be handy for testing. +The [`CheatCodes`](./../testing/cheat_codes.md) class, which we used for [calculating the storage slot above](#state), also includes a set of cheat methods for modifying the chain state that can be handy for testing. ### Set next block timestamp diff --git a/docs/docs/dev_docs/dapps/tutorials/contract_deployment.md b/docs/docs/dev_docs/tutorials/writing_dapp/contract_deployment.md similarity index 87% rename from docs/docs/dev_docs/dapps/tutorials/contract_deployment.md rename to docs/docs/dev_docs/tutorials/writing_dapp/contract_deployment.md index d677b403f771..34ce039738de 100644 --- a/docs/docs/dev_docs/dapps/tutorials/contract_deployment.md +++ b/docs/docs/dev_docs/tutorials/writing_dapp/contract_deployment.md @@ -3,12 +3,12 @@ To add contracts to your application, we'll start by creating a new `nargo` project. We'll then compile the contracts, and write a simple script to deploy them to our Sandbox. :::info -Follow the instructions [here](../../getting_started/noir_contracts.md) to install `nargo` if you haven't done so already. +Follow the instructions [here](../../contracts/setup.md) to install `nargo` if you haven't done so already. ::: -## Initialise nargo project +## initialize nargo project -Create a new `contracts` folder, and from there, initialise a new project called `token`: +Create a new `contracts` folder, and from there, initialize a new project called `token`: ```sh mkdir contracts && cd contracts @@ -17,13 +17,12 @@ nargo new --contract token Then, open the `contracts/token/Nargo.toml` configuration file, and add the `aztec.nr` and `value_note` libraries as dependencies: -import { AztecPackagesVersion } from "@site/src/components/Version"; - -{`[dependencies] -aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="${AztecPackagesVersion()}", directory="yarn-project/aztec-nr/aztec" } -value_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="${AztecPackagesVersion()}", directory="yarn-project/aztec-nr/value-note"} -safe_math = { git="https://github.com/AztecProtocol/aztec-packages/", tag="${AztecPackagesVersion()}", directory="yarn-project/aztec-nr/safe-math"} -`} +```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"} +safe_math = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="yarn-project/aztec-nr/safe-math"} +``` Last, copy-paste the code from the `Token` contract into `contracts/token/main.nr`: diff --git a/docs/docs/dev_docs/dapps/tutorials/contract_interaction.md b/docs/docs/dev_docs/tutorials/writing_dapp/contract_interaction.md similarity index 95% rename from docs/docs/dev_docs/dapps/tutorials/contract_interaction.md rename to docs/docs/dev_docs/tutorials/writing_dapp/contract_interaction.md index 545cc8271003..c33fc40d16c3 100644 --- a/docs/docs/dev_docs/dapps/tutorials/contract_interaction.md +++ b/docs/docs/dev_docs/tutorials/writing_dapp/contract_interaction.md @@ -12,7 +12,7 @@ Let's start by showing our user's private balance for the token across their acc Note that this function will only return a valid response for accounts registered in the RPC Server, since it requires access to the [user's private state](../../wallets/main.md#private-state). In other words, you cannot query the private balance of another user for the token contract. ::: -To do this, let's first initialise a new `Contract` instance using `aztec.js` that represents our deployed token contracts. Create a new `src/contracts.mjs` file with the imports for our artifacts and other dependencies: +To do this, let's first initialize a new `Contract` instance using `aztec.js` that represents our deployed token contracts. Create a new `src/contracts.mjs` file with the imports for our artifacts and other dependencies: ```js // src/contracts.mjs @@ -45,7 +45,7 @@ Balance of 0x0e1f60e8566e2c6d32378bdcadb7c63696e853281be798c107266b8c3a88ea9b: 0 Now that we can see the balance for each user, let's transfer tokens from one account to another. To do this, we will first need access to a `Wallet` object. This wraps access to an RPC Server and also provides an interface to craft and sign transactions on behalf of one of the user accounts. -We can initialise a wallet using one of the `getAccount` methods from `aztec.js`, along with the corresponding signing and encryption keys: +We can initialize a wallet using one of the `getAccount` methods from `aztec.js`, along with the corresponding signing and encryption keys: ```js import { getSchnorrAccount } from "@aztec/aztec.js"; @@ -56,17 +56,17 @@ const wallet = await getSchnorrAccount( ).getWallet(); ``` -For ease of use, `aztec.js` also ships with a helper `getSandboxAccountsWallets` method that returns a wallet for each of the pre-initialised accounts in the Sandbox, so you can send transactions as any of them. +For ease of use, `aztec.js` also ships with a helper `getSandboxAccountsWallets` method that returns a wallet for each of the pre-initialized accounts in the Sandbox, so you can send transactions as any of them. ```js import { getSandboxAccountsWallets } from '@aztec/aztec.js'; ``` -We'll use one of these wallets to initialise the `Contract` instance that represents our private token contract, so every transaction sent through it will be sent through that wallet. +We'll use one of these wallets to initialize the `Contract` instance that represents our private token contract, so every transaction sent through it will be sent through that wallet. #include_code transferPrivateFunds yarn-project/end-to-end/src/sample-dapp/index.mjs javascript -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 initialise the private token `Contract` instance using the `owner` wallet, meaning that any transactions sent through it will have the `owner` as sender. +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. Next, we send a transfer transaction, moving 1 unit of balance to the `recipient` account address. This has no immediate effect, since the transaction first needs to be simulated locally and then submitted and mined. Only once this has finished we can query the balances again and see the effect of our transaction. We are using a `showPrivateBalances` helper function here which has the code we wrote in the section above. diff --git a/docs/docs/dev_docs/dapps/tutorials/main.md b/docs/docs/dev_docs/tutorials/writing_dapp/main.md similarity index 92% rename from docs/docs/dev_docs/dapps/tutorials/main.md rename to docs/docs/dev_docs/tutorials/writing_dapp/main.md index 0685ab032a30..e62d47301272 100644 --- a/docs/docs/dev_docs/dapps/tutorials/main.md +++ b/docs/docs/dev_docs/tutorials/writing_dapp/main.md @@ -13,8 +13,8 @@ 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 CLI](../../cli/cli.md) -- [Nargo](../../getting_started/noir_contracts.md) for building contracts +- [Aztec CLI](../../cli/main.md) +- [Nargo](../../contracts/setup.md) for building contracts ## Prerequisites diff --git a/docs/docs/dev_docs/dapps/tutorials/project_setup.md b/docs/docs/dev_docs/tutorials/writing_dapp/project_setup.md similarity index 100% rename from docs/docs/dev_docs/dapps/tutorials/project_setup.md rename to docs/docs/dev_docs/tutorials/writing_dapp/project_setup.md diff --git a/docs/docs/dev_docs/dapps/tutorials/rpc_server.md b/docs/docs/dev_docs/tutorials/writing_dapp/rpc_server.md similarity index 85% rename from docs/docs/dev_docs/dapps/tutorials/rpc_server.md rename to docs/docs/dev_docs/tutorials/writing_dapp/rpc_server.md index 4df09e27b9e7..407295dca707 100644 --- a/docs/docs/dev_docs/dapps/tutorials/rpc_server.md +++ b/docs/docs/dev_docs/tutorials/writing_dapp/rpc_server.md @@ -2,7 +2,7 @@ As an app developer, the [Aztec RPC Server](https://github.com/AztecProtocol/aztec-packages/tree/master/yarn-project/aztec-rpc) 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](../../sandbox/main.md), which runs a local RPC Server and an Aztec Node, both connected to a local Ethereum development node like Anvil. The Sandbox also includes a set of pre-initialised accounts that you can use from your app. +During the Sandbox phase, this role is fulfilled by the [Aztec Sandbox](../../getting_started/sandbox.md), which runs a local RPC Server 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. @@ -26,7 +26,7 @@ Should the above fail due to a connection error, make sure the Sandbox is runnin ## Load user accounts -With our connection to the RPC server, let's try loading the accounts that are pre-initialised in the Sandbox: +With our connection to the RPC server, let's try loading the accounts that are pre-initialized in the Sandbox: #include_code showAccounts yarn-project/end-to-end/src/sample-dapp/index.mjs javascript diff --git a/docs/docs/dev_docs/dapps/tutorials/testing.md b/docs/docs/dev_docs/tutorials/writing_dapp/testing.md similarity index 82% rename from docs/docs/dev_docs/dapps/tutorials/testing.md rename to docs/docs/dev_docs/tutorials/writing_dapp/testing.md index 24da56dbf84d..ff9732be801f 100644 --- a/docs/docs/dev_docs/dapps/tutorials/testing.md +++ b/docs/docs/dev_docs/tutorials/writing_dapp/testing.md @@ -4,7 +4,7 @@ title: Testing To wrap up this tutorial, we'll set up a simple automated test for our dapp contracts. We will be using [jest](https://jestjs.io/), but any nodejs test runner works fine. -Here we'll only test the happy path for a `transfer` on our private token contract, but in a real application you should be testing both happy and unhappy paths, as well as both your contracts and application logic. Refer to the full [testing guide](../../testing/testing.md) for more info on testing and assertions. +Here we'll only test the happy path for a `transfer` on our private token contract, but in a real application you should be testing both happy and unhappy paths, as well as both your contracts and application logic. Refer to the full [testing guide](../testing.md) for more info on testing and assertions. ## Dependencies @@ -32,7 +32,7 @@ import TokenContractAbi from "../contracts/token/target/Token.json" assert { typ describe("token", () => {}); ``` -Let's set up our test suite. We'll start [a new Sandbox instance within the test](../../testing/testing.md#running-sandbox-in-the-nodejs-process), create two fresh accounts to test with, and deploy an instance of our contract. The `aztec-sandbox` and `aztec.js` provide the helper functions we need to do this: +Let's set up our test suite. We'll start [a new Sandbox instance within the test](../testing.md#running-sandbox-in-the-nodejs-process), create two fresh accounts to test with, and deploy an instance of our contract. The `aztec-sandbox` and `aztec.js` provide the helper functions we need to do this: #include_code setup yarn-project/end-to-end/src/sample-dapp/index.test.mjs javascript @@ -44,7 +44,7 @@ Now that we have a working test environment, we can write our first test for exe #include_code test yarn-project/end-to-end/src/sample-dapp/index.test.mjs javascript -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. Check out the [testing guide](../../testing/testing.md) for more ideas. +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. Check out the [testing guide](../testing.md) for more ideas. ## Running our tests @@ -56,4 +56,4 @@ yarn node --experimental-vm-modules $(yarn bin jest) --testRegex '.*\.test\.mjs$ ## Next steps -Now that you have finished the tutorial, you can learn more about [writing contracts with Noir](../../contracts/main.md), check out the [Sandbox's architecture](../../sandbox/main.md), or read about the [fundamental concepts behind Aztec Network](../../../concepts/foundation/main.md). +Now that you have finished the tutorial, you can learn more about [writing contracts with Noir](../../contracts/main.md) or read about the [fundamental concepts behind Aztec Network](../../../concepts/foundation/main.md). diff --git a/docs/docs/dev_docs/getting_started/token_contract_tutorial.md b/docs/docs/dev_docs/tutorials/writing_token_contract.md similarity index 96% rename from docs/docs/dev_docs/getting_started/token_contract_tutorial.md rename to docs/docs/dev_docs/tutorials/writing_token_contract.md index d53e63c161db..44acee30adbb 100644 --- a/docs/docs/dev_docs/getting_started/token_contract_tutorial.md +++ b/docs/docs/dev_docs/tutorials/writing_token_contract.md @@ -1,7 +1,7 @@ -# Token Contract Tutorial +# Writing a Standard token contract in Aztec.nr In this tutorial we will go through writing a standard L2 native token contract -for the Aztec Network, using the Aztec.nr contract libraries. It is recommended that you go through the [the introduction to contracts](./noir_contracts) section before this tutorial to gain some familiarity with writing Aztec smart contracts. +for the Aztec Network, using the Aztec.nr contract libraries. It is recommended that you go through the [the introduction to contracts](../contracts/main.md) and [setup instructions](../contracts/setup.md) section before this tutorial to gain some familiarity with writing Aztec smart contracts. This tutorial is intended to help you get familiar with the Aztec.nr library, Aztec contract syntax and some of the underlying structure of the Aztec network. @@ -14,7 +14,7 @@ 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 code defined [here](https://github.com/AztecProtocol/aztec-packages/blob/master/yarn-project/noir-contracts/src/contracts/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](https://github.com/AztecProtocol/aztec-packages/blob/master/yarn-project/noir-contracts/src/contracts/token_contract/src/main.nr), and explain what is being added as we go. ## Requirements @@ -22,7 +22,7 @@ You will need to install nargo, the Noir build too. if you are familiar with Rus -If you've already installed the `aztec-cli`, as described in the quickstart [here](./quickstart#cli), you can check which version of Noir is compatible with your version of the CLI and sandbox by running: +If you've already installed the `aztec-cli`, as described in the quickstart [here](../getting_started/quickstart.md#cli), you can check which version of Noir is compatible with your version of the CLI and sandbox by running: ```bash aztec-cli get-node-info @@ -65,7 +65,7 @@ cd token_contract_tutorial && mkdir contracts && cd contracts Create a new Noir project using nargo. ```bash -nargo init --name token_contract +nargo new --contract token_contract ``` Your project should look like this: @@ -80,19 +80,18 @@ Your project should look like this: Add the following dependencies to your Nargo.toml file, below the package information: -import { AztecPackagesVersion } from "@site/src/components/Version"; - -{`[package] +```toml +[package] name = "token_contract" authors = [""] compiler_version = "0.1" type = "contract" - + [dependencies] -aztec = { git="https://github.com/AztecProtocol/aztec-packages/", tag="${AztecPackagesVersion()}", directory="yarn-project/aztec-nr/aztec" } -value_note = { git="https://github.com/AztecProtocol/aztec-packages/", tag="${AztecPackagesVersion()}", directory="yarn-project/aztec-nr/value-note"} -safe_math = { git="https://github.com/AztecProtocol/aztec-packages/", tag="${AztecPackagesVersion()}", directory="yarn-project/aztec-nr/safe-math"} -`} +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"} +safe_math = { git="https://github.com/AztecProtocol/aztec-packages/", tag="#include_aztec_version", directory="yarn-project/aztec-nr/safe-math"} +``` ## Contract Interface @@ -257,7 +256,7 @@ Below the dependencies, paste the following Storage struct: Reading through the storage variables: -- `admin` a single Field value stored in public state. `FIELD_SERIALISED_LEN` indicates the length of the variable, which is 1 in this case because it's a single Field element. A `Field` is basically an unsigned integer with a maximum value determined by the underlying cryptographic curve. +- `admin` a single Field value stored in public state. `FIELD_SERIALIZED_LEN` indicates the length of the variable, which is 1 in this case because it's a single Field element. A `Field` is basically an unsigned integer with a maximum value determined by the underlying cryptographic curve. - `minters` is a mapping of Fields in public state. This will store whether an account is an approved minter on the contract. - `balances` is a mapping of private balances. Private balances are stored in a `Set` of `ValueNote`s. The balance is the sum of all of an account's `ValueNote`s. - `total_supply` is a Field value stored in public state and represents the total number of tokens minted. @@ -270,7 +269,7 @@ You can read more about it [here](../contracts/syntax/storage.md). Once we have Storage defined, we need to specify how to initialize it. The `init` method creates and initializes an instance of `Storage`. We define an initialization method for each of the storage variables defined above. Storage initialization is generic and can largely be reused for similar types, across different contracts, but it is important to note that each storage variable specifies it's storage slot, starting at 1. -Also, the public storage variables define the type that they store by passing the methods by which they are serialized. Because all `PublicState` in this contract is storing Field elements, each storage variable takes `FieldSerialisationMethods`. +Also, the public storage variables define the type that they store by passing the methods by which they are serialized. Because all `PublicState` in this contract is storing Field elements, each storage variable takes `FieldSerializationMethods`. #include_code storage_init /yarn-project/noir-contracts/src/contracts/token_contract/src/main.nr rust @@ -487,7 +486,7 @@ This must be included in every contract because it depends on the storage slots, ## Compiling -Now that the contract is complete, you should be able to compile it with the `aztec-cli`. See the [CLI page](../cli/cli.md) for instructions on setting it up. +Now that the contract is complete, you should be able to compile it with the `aztec-cli`. See the [CLI page](../cli/main.md) for instructions on setting it up. ```bash aztec-cli compile /path/to/token_contracts_folder diff --git a/docs/docs/dev_docs/wallets/creating_schnorr_accounts.md b/docs/docs/dev_docs/wallets/creating_schnorr_accounts.md new file mode 100644 index 000000000000..ea9e1cda5f5a --- /dev/null +++ b/docs/docs/dev_docs/wallets/creating_schnorr_accounts.md @@ -0,0 +1,60 @@ +--- +title: Creating Schnorr Accounts +--- + +## Introduction + +This section shows how to create schnorr account wallets on the Aztec Sandbox. + +An in-depth explaining about accounts on aztec can be found [here](../../concepts/foundation/accounts/main.md). But creating an account on the Sandbox does 2 things: + +1. Deploys an account contract -- representing you -- allowing you to perform actions on the network (deploy contracts, call functions etc). +2. Adds your encryption keys to the RPC Server allowing it to decrypt and manage your private state. + +## Pre-requisites + +Have a running Sandbox and a repository that interacts with it as explained [here](../getting_started/sandbox.md). + +Let's assume you have a file `src/index.ts` from the example used in the Sandbox page. + +## Create accounts on the sandbox + +1. Import relevant modules: + +#include_code imports /yarn-project/end-to-end/src/e2e_sandbox_example.test.ts typescript + +2. Code to create an account. You must run this inside of a function: + +#include_code create_accounts /yarn-project/end-to-end/src/e2e_sandbox_example.test.ts typescript + +3. Running `yarn start` should now output: + +``` + token Aztec Sandbox Info { + version: 1, + chainId: 31337, + rollupAddress: EthAddress { + buffer: + }, + client: 'aztec-rpc@0.1.0', + compatibleNargoVersion: '0.11.1-aztec.0' + } + token Creating accounts using schnorr signers... +3ms + token Created Alice's account at 0x1509b252...0027 +10s + token Created Bob's account at 0x031862e8...e7a3 +0ms +``` + +That might seem like a lot to digest but it can be broken down into the following steps: + +1. We create 2 `Account` objects in Typescript. This object heavily abstracts away the mechanics of configuring and deploying an account contract and setting up a 'wallet' for signing transactions. If you aren't interested in building new types of account contracts or wallets then you don't need to be too concerned with it. In this example we have constructed account contracts and corresponding wallets that sign/verify transactions using schnorr signatures. +2. We wait for the deployment of the 2 account contracts to complete. +3. We retrieve the expected account addresses from the `Account` objects and ensure that they are present in the set of account addresses registered on the Sandbox. + +Note, we use the `getRegisteredAccounts` API to verify that the addresses computed as part of the +account contract deployment have been successfully added to the Sandbox. + +If you were looking at your terminal that is running the Sandbox you should have seen a lot of activity. This is because the Sandbox will have simulated the deployment of both contracts, executed the private kernel circuit for each before submitted 2 transactions to the pool. The sequencer will have picked them up and inserted them into a rollup and executed the recursive rollup circuits before publishing the rollup to Anvil. Once this has completed, the rollup is retrieved and pulled down to the internal RPC Server so that any new account state can be decrypted. + +## Next Steps + +Check out our section on [Writing your own Account Contract](./writing_an_account_contract.md) leveraging our account abstraction diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index 7354306c98f9..54f750d2e396 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -122,6 +122,32 @@ const config = { disableInDev: false, }, ], + [ + "@spalladino/docusaurus-plugin-typedoc", + { + id: "apis/aztec-rpc", + entryPoints: ["../yarn-project/types/src/interfaces/aztec_rpc.ts"], + tsconfig: "../yarn-project/types/tsconfig.json", + entryPointStrategy: "expand", + out: "apis/aztec-rpc", + disableSources: true, + frontmatter: { sidebar_label: "Aztec RPC Server" }, + }, + ], + [ + "@spalladino/docusaurus-plugin-typedoc", + { + id: "apis/aztec-js", + entryPoints: [ + "../yarn-project/aztec.js/src/contract/index.ts", + "../yarn-project/aztec.js/src/account/index.ts", + ], + tsconfig: "../yarn-project/aztec.js/tsconfig.json", + entryPointStrategy: "resolve", + out: "apis/aztec-js", + disableSources: true, + }, + ], // ["./src/plugins/plugin-embed-code", {}], ], themeConfig: diff --git a/docs/internal_notes/dev_docs/sandbox/components.md b/docs/internal_notes/dev_docs/sandbox/components.md index cb07a4b6139b..0db084b65082 100644 --- a/docs/internal_notes/dev_docs/sandbox/components.md +++ b/docs/internal_notes/dev_docs/sandbox/components.md @@ -223,7 +223,7 @@ Implementation notes for this milestone: Responsibilities: -- Wins a period of time to become the sequencer (depending on finalised protocol). +- Wins a period of time to become the sequencer (depending on finalized protocol). - Chooses a set of txs from the tx pool to be in the rollup. - Simulate the rollup of txs. - Adds proof requests to the request pool (not for this milestone). diff --git a/docs/netlify.toml b/docs/netlify.toml index 478b38843c9e..96e8a4fbc882 100644 --- a/docs/netlify.toml +++ b/docs/netlify.toml @@ -56,7 +56,43 @@ [[redirects]] from = "/dev_docs/getting_started/cli" - to = "/dev_docs/cli" + to = "/dev_docs/cli/main" + +[[redirects]] + from = "/dev_docs/getting_started/noir_contracts" + to = "/dev_docs/contracts/main" + +[[redirects]] + from = "/dev_docs/getting_started/token_contract_tutorial" + to = "/dev_docs/tutorials/writing_token_contract" + +[[redirects]] + from = "/dev_docs/sandbox/main" + to = "/dev_docs/getting_started/sandbox" + +[[redirects]] + from = "/dev_docs/dapps/tutorials/main" + to = "/dev_docs/tutorials/writing_dapp/main" + +[[redirects]] + from = "/dev_docs/dapps/tutorials/project_setup" + to = "/dev_docs/tutorials/writing_dapp/project_setup" + +[[redirects]] + from = "/dev_docs/dapps/tutorials/contract_deployment" + to = "/dev_docs/tutorials/writing_dapp/contract_deployment" + +[[redirects]] + from = "/dev_docs/dapps/tutorials/contract_interaction" + to = "/dev_docs/tutorials/writing_dapp/contract_interaction" + +[[redirects]] + from = "/dev_docs/dapps/tutorials/rpc_server" + to = "/dev_docs/tutorials/writing_dapp/rpc_server" + +[[redirects]] + from = "/dev_docs/dapps/tutorials/testing" + to = "/dev_docs/tutorials/writing_dapp/testing" [[redirects]] from = "/aztec/cryptography/cryptography-roadmap" diff --git a/docs/package.json b/docs/package.json index b3017e9b2b22..594416233534 100644 --- a/docs/package.json +++ b/docs/package.json @@ -4,19 +4,20 @@ "private": true, "scripts": { "docusaurus": "docusaurus", - "start": "docusaurus start", - "start:dev": "concurrently \"yarn preprocess:dev\" \"docusaurus start --host 0.0.0.0\"", - "start:dev:local": "concurrently \"yarn preprocess:dev\" \"docusaurus start\"", - "build": "yarn preprocess && docusaurus build", + "start": "yarn preprocess && yarn typedoc && docusaurus start", + "start:dev": "concurrently \"yarn preprocess:dev\" \"yarn typedoc:dev\" \"sleep 2 && docusaurus start --host 0.0.0.0\"", + "start:dev:local": "concurrently \"yarn preprocess:dev\" \"yarn typedoc:dev\" \"sleep 2 && docusaurus start\"", + "build": "./scripts/build.sh", "swizzle": "docusaurus swizzle", "deploy": "docusaurus deploy", - "clear": "rm -rf 'processed-docs' 'processed-docs-cache' && docusaurus clear", + "clear": "rm -rf 'processed-docs' 'processed-docs-cache' docs/apis && docusaurus clear", "serve": "docusaurus serve", "preprocess": "yarn node ./src/preprocess/index.js", "preprocess:dev": "nodemon --config nodemon.json ./src/preprocess/index.js", + "typedoc": "rm -rf docs/apis && docusaurus generate-typedoc && cp -a docs/apis processed-docs/", + "typedoc:dev": "nodemon -w ../yarn-project -e '*.js,*.ts,*.nr,*.md' --exec \"rm -rf docs/apis && yarn docusaurus generate-typedoc && cp -a docs/apis processed-docs/\"", "write-translations": "docusaurus write-translations", - "write-heading-ids": "docusaurus write-heading-ids", - "update-specs": "./scripts/update_specs.sh" + "write-heading-ids": "docusaurus write-heading-ids" }, "dependencies": { "@docusaurus/core": "^2.4.1", @@ -36,9 +37,12 @@ }, "devDependencies": { "@docusaurus/module-type-aliases": "^2.4.1", + "@spalladino/docusaurus-plugin-typedoc": "^0.20.3", "@tsconfig/docusaurus": "^1.0.5", "concurrently": "^8.0.1", "nodemon": "^3.0.1", + "typedoc": "^0.25.1", + "typedoc-plugin-markdown": "^3.16.0", "typescript": "^4.7.2" }, "browserslist": { diff --git a/docs/scripts/build.sh b/docs/scripts/build.sh new file mode 100755 index 000000000000..d1c4aaab1d4d --- /dev/null +++ b/docs/scripts/build.sh @@ -0,0 +1,48 @@ +#!/bin/bash +set -eo pipefail + +# Helper function for building packages in yarn project +build_package() { + local package_name="$1" + local build_command="${2:-yarn build}" + + echo "Building $package_name..." + (cd "yarn-project/$package_name" && $build_command) +} + +# Build script. If run on Netlify, first it needs to compile all yarn-projects +# that are involved in typedoc in order to generate their type information. +if [ -n "$NETLIFY" ]; then + # Move to project root + cd .. + echo Working dir $(pwd) + + # Make sure the latest tag is available for loading code snippets from it + LAST_TAG="aztec-packages-v$(jq -r '.["."]' .release-please-manifest.json)" + echo Fetching latest released tag $LAST_TAG... + git fetch origin refs/tags/$LAST_TAG:refs/tags/$LAST_TAG + + # Tweak global tsconfig so we skip tests in all projects + echo Removing test files from tsconfig... + jq '. + { "exclude": ["**/*test.ts"] }' yarn-project/tsconfig.json > yarn-project/tsconfig.tmp.json + mv yarn-project/tsconfig.tmp.json yarn-project/tsconfig.json + + # Install deps (maybe we can have netlify download these automatically so they get cached..?) + echo Installing yarn-project dependencies... + (cd yarn-project && yarn) + + # Build the required projects for typedoc + build_package "aztec-rpc" + build_package "aztec.js" "yarn build:ts" + + # Back to docs site + cd docs + + # Install deps + echo Install docs deps... + yarn +fi + +# Now build the docsite +echo Building docsite... +yarn preprocess && yarn typedoc && yarn docusaurus build diff --git a/docs/sidebars.js b/docs/sidebars.js index 9b4ac8d3111b..1ec97eda8ea5 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -196,8 +196,35 @@ const sidebars = { items: [ "dev_docs/getting_started/quickstart", "dev_docs/getting_started/sandbox", - "dev_docs/getting_started/noir_contracts", - "dev_docs/getting_started/token_contract_tutorial", + "dev_docs/getting_started/updating", + ], + }, + + { + label: "Tutorials", + type: "category", + link: { + type: "doc", + id: "dev_docs/tutorials/main", + }, + items: [ + "dev_docs/tutorials/writing_token_contract", + { + label: "Writing a DApp", + type: "category", + link: { + type: "doc", + id: "dev_docs/tutorials/writing_dapp/main", + }, + items: [ + "dev_docs/tutorials/writing_dapp/project_setup", + "dev_docs/tutorials/writing_dapp/rpc_server", + "dev_docs/tutorials/writing_dapp/contract_deployment", + "dev_docs/tutorials/writing_dapp/contract_interaction", + "dev_docs/tutorials/writing_dapp/testing", + ], + }, + "dev_docs/tutorials/testing", ], }, @@ -210,6 +237,7 @@ const sidebars = { }, items: [ "dev_docs/contracts/workflow", + "dev_docs/contracts/setup", "dev_docs/contracts/layout", { label: "Syntax", @@ -227,6 +255,9 @@ const sidebars = { "dev_docs/contracts/syntax/globals", ], }, + "dev_docs/contracts/compiling", + "dev_docs/contracts/deploying", + "dev_docs/contracts/artifacts", { label: "Portals", type: "category", @@ -241,9 +272,7 @@ const sidebars = { "dev_docs/contracts/portals/outbox", ], }, - "dev_docs/contracts/compiling", - "dev_docs/contracts/deploying", - "dev_docs/contracts/artifacts", + "dev_docs/contracts/common_errors", // { // label: "Resources", // type: "category", @@ -283,58 +312,7 @@ const sidebars = { ], }, - { - label: "Sandbox", - type: "category", - link: { - type: "doc", - id: "dev_docs/sandbox/main", - }, - items: ["dev_docs/sandbox/common_errors"], - }, - - { - label: "CLI", - type: "category", - link: { - type: "doc", - id: "dev_docs/cli/main", - }, - items: ["dev_docs/cli/cli"], - }, - { - label: "DApp Development", - type: "category", - items: [ - // { - // label: "API", - // type: "category", - // link: { - // type: "doc", - // id: "dev_docs/dapps/api/main", - // }, - // items: [ - // "dev_docs/dapps/api/aztec_rpc", - // "dev_docs/dapps/api/contract_interaction", - // ], - // }, - { - label: "Tutorials", - type: "category", - link: { - type: "doc", - id: "dev_docs/dapps/tutorials/main", - }, - items: [ - "dev_docs/dapps/tutorials/project_setup", - "dev_docs/dapps/tutorials/rpc_server", - "dev_docs/dapps/tutorials/contract_deployment", - "dev_docs/dapps/tutorials/contract_interaction", - "dev_docs/dapps/tutorials/testing", - ], - }, - ], - }, + "dev_docs/cli/main", { label: "Testing", @@ -343,7 +321,7 @@ const sidebars = { type: "doc", id: "dev_docs/testing/main", }, - items: ["dev_docs/testing/testing", "dev_docs/testing/cheat_codes"], + items: ["dev_docs/testing/cheat_codes"], }, { @@ -356,6 +334,7 @@ const sidebars = { items: [ "dev_docs/wallets/architecture", "dev_docs/wallets/writing_an_account_contract", + "dev_docs/wallets/creating_schnorr_accounts", ], }, @@ -364,9 +343,27 @@ const sidebars = { type: "category", items: [], },*/ + "dev_docs/sandbox_errors/main", "dev_docs/privacy/main", "dev_docs/limitations/main", + { + label: "API Reference", + type: "category", + items: [ + { + label: "Aztec RPC Server", + type: "doc", + id: "apis/aztec-rpc/interfaces/AztecRPC", + }, + { + label: "Aztec.js", + type: "category", + items: [{ dirName: "apis/aztec-js", type: "autogenerated" }], + }, + ], + }, + { type: "html", value: '', diff --git a/docs/src/preprocess/include_code.js b/docs/src/preprocess/include_code.js new file mode 100644 index 000000000000..9991780e2cc0 --- /dev/null +++ b/docs/src/preprocess/include_code.js @@ -0,0 +1,324 @@ +const fs = require("fs"); +const path = require("path"); +const childProcess = require("child_process"); + +const getLineNumberFromIndex = (fileContent, index) => { + return fileContent.substring(0, index).split("\n").length; +}; + +/** + * Search for lines of the form + */ +function processHighlighting(codeSnippet, identifier) { + const lines = codeSnippet.split("\n"); + /** + * For an identifier = bar: + * + * Matches of the form: `highlight-next-line:foo:bar:baz` will be replaced with "highlight-next-line". + * Matches of the form: `highlight-next-line:foo:baz` will be replaced with "". + */ + const regex1 = /highlight-next-line:([a-zA-Z0-9-._:]+)/; + const replacement1 = "highlight-next-line"; + const regex2 = /highlight-start:([a-zA-Z0-9-._:]+)/; + const replacement2 = "highlight-start"; + const regex3 = /highlight-end:([a-zA-Z0-9-._:]+)/; + const replacement3 = "highlight-end"; + const regex4 = /this-will-error:([a-zA-Z0-9-._:]+)/; + const replacement4 = "this-will-error"; + + let result = ""; + let mutated = false; + + const processLine = (line, regex, replacement) => { + const match = line.match(regex); + if (match) { + mutated = true; + + const identifiers = match[1].split(":"); + if (identifiers.includes(identifier)) { + line = line.replace(match[0], replacement); + } else { + // Remove matched text completely + line = line.replace(match[0], ""); + } + } else { + // No match: it's an ordinary line of code. + } + return line.trim() == "//" || line.trim() == "#" ? "" : line; + }; + + for (let line of lines) { + mutated = false; + line = processLine(line, regex1, replacement1); + line = processLine(line, regex2, replacement2); + line = processLine(line, regex3, replacement3); + line = processLine(line, regex4, replacement4); + result += line === "" && mutated ? "" : line + "\n"; + } + + return result.trim(); +} + +let lastReleasedVersion; + +/** Returns the last released tag */ +function getLatestTag() { + if (!lastReleasedVersion) { + const manifest = path.resolve( + __dirname, + "../../../.release-please-manifest.json" + ); + lastReleasedVersion = JSON.parse(fs.readFileSync(manifest).toString())["."]; + } + return lastReleasedVersion + ? `aztec-packages-v${lastReleasedVersion}` + : undefined; +} + +/** Returns whether to use the latest release or the current version of stuff. */ +function useLastRelease() { + return process.env.NETLIFY || process.env.INCLUDE_RELEASED_CODE; +} + +/** + * Returns the contents of a file. If the build is running for publishing, it will load the contents + * of the file in the last released version. + */ +function readFile(filePath, tag) { + if (tag && tag !== "master") { + try { + const tag = getLatestTag(); + const root = path.resolve(__dirname, "../../../"); + const relPath = path.relative(root, filePath); + return childProcess.execSync(`git show ${tag}:${relPath}`).toString(); + } catch (err) { + console.error( + `Error reading file ${filePath} from latest version. Falling back to current content.` + ); + } + } + return fs.readFileSync(filePath, "utf-8"); +} + +/** Extracts a code snippet, trying with the last release if applicable, and falling back to current content. */ +function extractCodeSnippet(filePath, identifier) { + if (useLastRelease()) { + try { + return doExtractCodeSnippet(filePath, identifier, false); + } catch (err) { + console.error( + `Error extracting code snippet ${identifier} for ${filePath}: ${err}. Falling back to current content.` + ); + } + } + + return doExtractCodeSnippet(filePath, identifier, true); +} + +/** + * Parse a code file, looking for identifiers of the form: + * `docs:start:${identifier}` and `docs:end:{identifier}`. + * Extract that section of code. + * + * It's complicated if code snippet identifiers overlap (i.e. the 'start' of one code snippet is in the + * middle of another code snippet). The extra logic in this function searches for all identifiers, and + * removes any which fall within the bounds of the code snippet for this particular `identifier` param. + * @returns the code snippet, and start and end line numbers which can later be used for creating a link to github source code. + */ +function doExtractCodeSnippet(filePath, identifier, useCurrent) { + const tag = useCurrent ? "master" : getLatestTag(); + let fileContent = readFile(filePath, tag); + let lineRemovalCount = 0; + let linesToRemove = []; + + const startRegex = /(?:\/\/|#)\s+docs:start:([a-zA-Z0-9-._:]+)/g; // `g` will iterate through the regex.exec loop + const endRegex = /(?:\/\/|#)\s+docs:end:([a-zA-Z0-9-._:]+)/g; + + /** + * Search for one of the regex statements in the code file. If it's found, return the line as a string and the line number. + */ + const lookForMatch = (regex) => { + let match; + let matchFound = false; + let matchedLineNum = null; + let actualMatch = null; + let lines = fileContent.split("\n"); + while ((match = regex.exec(fileContent))) { + if (match !== null) { + const identifiers = match[1].split(":"); + let tempMatch = identifiers.includes(identifier) ? match : null; + + if (tempMatch === null) { + // If it's not a match, we'll make a note that we should remove the matched text, because it's from some other identifier and should not appear in the snippet for this identifier. + for (let i = 0; i < lines.length; i++) { + let line = lines[i]; + if (line.trim() == match[0].trim()) { + linesToRemove.push(i + 1); // lines are indexed from 1 + ++lineRemovalCount; + } + } + } else { + if (matchFound === true) { + throw new Error( + `Duplicate for regex ${regex} and identifier ${identifier}` + ); + } + matchFound = true; + matchedLineNum = getLineNumberFromIndex(fileContent, tempMatch.index); + actualMatch = tempMatch; + } + } + } + + return [actualMatch, matchedLineNum]; + }; + + let [startMatch, startLineNum] = lookForMatch(startRegex); + let [endMatch, endLineNum] = lookForMatch(endRegex); + + // Double-check that the extracted line actually contains the required start and end identifier. + if (startMatch !== null) { + const startIdentifiers = startMatch[1].split(":"); + startMatch = startIdentifiers.includes(identifier) ? startMatch : null; + } + if (endMatch !== null) { + const endIdentifiers = endMatch[1].split(":"); + endMatch = endIdentifiers.includes(identifier) ? endMatch : null; + } + + if (startMatch === null || endMatch === null) { + if (startMatch === null && endMatch === null) { + throw new Error( + `Identifier "${identifier}" not found in file "${filePath}"` + ); + } else if (startMatch === null) { + throw new Error( + `Start line "docs:start:${identifier}" not found in file "${filePath}"` + ); + } else { + throw new Error( + `End line "docs:end:${identifier}" not found in file "${filePath}"` + ); + } + } + + let lines = fileContent.split("\n"); + + // We only want to remove lines which actually fall within the bounds of our code snippet, so narrow down the list of lines that we actually want to remove. + linesToRemove = linesToRemove.filter((lineNum) => { + const removal_in_bounds = lineNum >= startLineNum && lineNum <= endLineNum; + return removal_in_bounds; + }); + + // Remove lines which contain `docs:` comments for unrelated identifiers: + lines = lines.filter((l, i) => { + return !linesToRemove.includes(i + 1); // lines are indexed from 1 + }); + + // Remove lines from the snippet which fall outside the `docs:start` and `docs:end` values. + lines = lines.filter((l, i) => { + return i + 1 > startLineNum && i + 1 < endLineNum - linesToRemove.length; // lines are indexed from 1 + }); + + // We have our code snippet! + let codeSnippet = lines.join("\n"); + + // The code snippet might contain some docusaurus highlighting comments for other identifiers. We should remove those. + codeSnippet = processHighlighting(codeSnippet, identifier); + + return [codeSnippet, startLineNum, endLineNum, tag]; +} + +/** + * Explaining this regex: + * + * E.g. `#include_code snippet_identifier /circuits/my_code.cpp cpp` + * + * #include_code\s+(\S+)\s+(\S+)\s+(\S+) + * - This is the main regex to match the above format. + * - \s+: one or more whitespace characters (space or tab) after `include_code` command. + * - (\S+): one or more non-whitespaced characters. Captures this as the first argument, which is a human-readable identifier for the code block. + * - etc. + * + * Lookaheads are needed to allow us to ignore commented-out lines: + * + * ^(?!