diff --git a/documentation updates aleo ambassadors/book.toml b/documentation updates aleo ambassadors/book.toml deleted file mode 100644 index 2b70c5d76..000000000 --- a/documentation updates aleo ambassadors/book.toml +++ /dev/null @@ -1,6 +0,0 @@ -[book] -title = "zero-to-zk" -authors = ["Zk"] -language = "en" -multilingual = false -src = "src" diff --git a/documentation updates aleo ambassadors/src/SUMMARY.md b/documentation updates aleo ambassadors/src/SUMMARY.md deleted file mode 100644 index 1b99c09c9..000000000 --- a/documentation updates aleo ambassadors/src/SUMMARY.md +++ /dev/null @@ -1,77 +0,0 @@ -# Summary - -- [Overview](./overview.md) -- [LEARN](./learn/README.md) - - - [Core Architecture](./learn/core-architecture.md) - - [Concepts](./learn/concepts/README.md) - - [Accounts](./learn/concepts/accounts.md) - - [Programs](./learn/concepts/programs/README.md) - - [Execution](./learn/concepts/programs/execution.md) - - [Deployment](./learn/concepts/programs/deployment.md) - - [Blocks](./learn/concepts/blocks.md) - - [Transactions](./learn/concepts/transactions.md) - - [Transitions](./learn/concepts/transitions.md) - - [Storage](./learn/concepts/storage.md) - - [Fee](./learn/concepts/fee.md) - - [zkCloud](./learn/zkcloud/README.md) - - [snarkOS](./learn/zkcloud/snarkos.md) - - [snarkVM](./learn/zkcloud/snarkvm.md) - - [Network](./learn/network/README.md) - - [Validators](./learn/network/validators.md) - - [Clients](./learn/network/clients.md) - - [Provers](./learn/network/provers.md) - - [Consensus](./learn/network/concensus.md) - -- [BUILD](./build/README.md) - - - [Leo](./build/leo/README.md) - - - [Overview](./build/leo/overview.md) - - [Installation](./build/installation/installation.md) - - [HelloLeo](./build/leo/helloleo.md) - - [Core Components](./build/leo/README.md) - - [Language](./build/leo/language.md) - - [Operators](./build/leo/operators.md) - - [Commands](./build/leo/commands.md) - - [Manage your Program](./build/leo/manage-your-program/README.md) - - [Compiling Programs](./build/leo/compiling-programs.md) - - [Deploying Programs](./build/leo/deploying-programs.md) - - [Executing Programs](./build/leo/executing-programs.md) - - [Resources](./build/leo/resources/README.md) - - [Tooling](./build/leo/resources/tooling.md) - - [Leo Playground](./build/leo/resources/leo-playground.md) - - [Leo Syntax Cheatsheet](./build/leo/resources/leo-syntax-cheatsheet.md) - - [Developer Resources](./build/leo/resources/developer-resources.md) - - [Aleo SDK](./build/leo/aleo-sdk/README.md) - - - [Overview](./build/leo/aleo-sdk/overview.md) - - [Javascript/TypeScript](./build/leo/aleo-sdk/js-ts/README.md) - - - [Guide](./build/leo/aleo-sdk/js-ts/guide.md) - - [Account](./build/leo/aleo-sdk/js-ts/account.md) - - [Aleo Network Client](./build/leo/aleo-sdk/js-ts/aleo-network-client.md) - - [Development Client](./build/leo/aleo-sdk/js-ts/development-client.md) - - - [Create Aleo App](./build/leo/aleo-sdk/create-aleo-app/README.md) - - [Installation](./build/leo/aleo-sdk/create-aleo-app/installation.md) - - [React + JS + Leo Tutorial](./build/leo/aleo-sdk/create-aleo-app/react-js-leo-tutorial.md) - - [Wasm](./build/leo/aleo-sdk/wasm/README.md) - - - [Installation](./build/leo/aleo-sdk/wasm/installation.md) - - [NodeJS + Browser](./build/leo/aleo-sdk/wasm/nodejs-browser.md) - - [Browser(Multi-Threaded)](./build/leo/aleo-sdk/wasm/browser-multi-threaded.md) - - - [Python](./build/leo/aleo-sdk/python/README.md) - - [Aleo SDK](./build/leo/aleo-sdk/python/aleo-sdk.md) - - [zkML Transpiler](./build/leo/ale-sdk/python/zkml-transpiler.md) - - - [Development Netowrk](./build/development-network/README.md) - - [snarkOS Node RPC](./build/snarkos-node-rpc/README.md) - - [Data and analytics](./build/data-and-analytics/README.md) - - - [Advanced](./advanced/README.md) - - [InclusionProof](./advanced/inclusion-proof..md) - - [Dive into AVM](./advanced/dive-into-avm/README.md) - - [Circuit](./advanced/dive-into-avm/circuits-r1cs.md) - - [Aleo Account](./advanced/dive-into-avm/aleo-account-keys.md) diff --git a/documentation updates aleo ambassadors/src/advanced/README.md b/documentation updates aleo ambassadors/src/advanced/README.md deleted file mode 100644 index 931fae06c..000000000 --- a/documentation updates aleo ambassadors/src/advanced/README.md +++ /dev/null @@ -1 +0,0 @@ -# Advanced diff --git a/documentation updates aleo ambassadors/src/blog/exploring_aleo_record_model.md b/documentation updates aleo ambassadors/src/blog/exploring_aleo_record_model.md deleted file mode 100644 index ec49ab5e7..000000000 --- a/documentation updates aleo ambassadors/src/blog/exploring_aleo_record_model.md +++ /dev/null @@ -1,178 +0,0 @@ -# Exploring Aleo's Record Model - -![alt text](./images/aleo.jpeg) - -## Introduction -Before we can dive into the explanation of a record, we first have to make sure that you understand what Aleo is, and why it chose a record model as its core data structure. - -Autonomous Ledger Execution Offchain (Aleo) is a layer-1 blockchain that combines general-purpose programmability with privacy by default. - -The core idea behind Aleo is ZEXE or zero-knowledge execution initially written in this [research paper](https://eprint.iacr.org/2018/962.pdf) in 2018. It first introduced the record model which extends the UTXO model from Zcash and enables storing and encrypting arbitrary data (user assets and application states), rather than just values of specific assets or tokens. - - -## Privacy -There are generally four different types of privacy that relate to blockchains. - -Aleo fulfils the 3 of them: -- [x] Private inputs (messages) -- [x] Private outputs (state changes) -- [x] Private user -- [ ] Private function - -Initially, Aleo was aiming for function privacy as well (as detailed in the original ZEXE paper) but decided against it as it would have led to worse performance and longer proving times. - - - -## Comparing state storage in blockchains -There are two main state models used in blockchains - UTXO (unspent transaction output) and the account model (introduced by Ethereum). - -Aleo uses a variation of the UTXO model - the record model. - - -

-Account vs UTXO -

- -

-Source: galaxy.com -

-
- -### Account Model -In the account model as used in Ethereum, the application state can be found by referencing to a particular address. - -As such, anyone would be able to view the activities of any account, simply with the knowledge of the address. - -

-Ethereum Storage Diagram -

- -

-Source: ethereum.org -

-
- - -

-Ethereum World State Diagram -

- -

-Source: Article by Lucas Saldanha -

- -
- - -### Record Model -In the record model, the application state, along with its owner are encrypted and stored on the blockchain. - - -

-Aleo Records Diagram -

- -

-Source: Zexe: Enabling Decentralized Private Computation -

- -
- - -

-Aleo World State Diagram -

- - -

-Source: Zexe: Enabling Decentralized Private Computation -

-
- - -## Record Model Explained -Records are a fundamental data structure that can contain any arbitrary payload and are used for encoding user assets or application states. Records represent a fragment of the global state kept on-chain. For example, the balance of your credits in a given account is composed by the multiple credit records that have your address as the owner. - - -An Aleo record is serialized in the following format: - -| Parameter | Type | Description | -|------------|:----------------------------:|-----------------------------------------------------------------------------------------------------| -| owner | address | The address public key of the owner of the program record | -| data | Map | A data payload containing arbitrary application-dependent information | -| nonce | group | The serial number nonce of the program record | - - -An example record: -```bash -{ - owner: aleo13ssze66adjjkt795z9u5wpq8h6kn0y2657726h4h3e3wfnez4vqsm3008q.private, - amount: 100u64.private, - _nonce: 5861592911433819692697358191094794940442348980903696700646555355124091569429group.public -} -``` - -Owner -
-`aleo13ssze66adjjkt795z9u5wpq8h6kn0y2657726h4h3e3wfnez4vqsm3008q` - -The record owner is an account address, and specifies the party who is authorized to spend the record. - - -Data -
-`100u64` - -The record can encode arbitrary application information. The "amount" key is the data payload that the record carries. - - -Nonce -
-`5861592911433819692697358191094794940442348980903696700646555355124091569429group` - -The serial number nonce is used to create a unique identifier for each record, and is computed via a PRF evaluation of the address secret key ask of the owner and the record's serial number. - - - - -For a practical demonstration of a record in Aleo, see [here](https://youtu.be/JIgrKv_Q6Jo?feature=shared). - - -### Updating State -In the record model, applications update their state by consuming records containing the old state, and producing new records that contain the updated state. Records that have been used will be marked as spent and cannot be used again. - - -

-UTXO diagram -

- -

-Source: adapulse.io -

-
- -The consumption and production of records is typically done in a transition function. A transaction in Aleo can contain up to 32 transitions, one of which is reserved for the transaction fee. - - - -

-Transaction in Aleo -

- -## Why Record Model? - -In the account-based model, an application's data is stored in a persistent location tied to the application's account, and updates are made directly to this stored data. For a typical token transfer transaction using this model, user balances would be stored in a table mapping user account addresses to their respective balances. When User A transfers money to User B, A's balance in the table is reduced, and B's balance is increased by the same amount. - -If we were to try making the transactions private (hiding the amount transferred and the identities of A and B), instead of storing actual balances, the application can store commitments to these balances. Transactions would then update these commitments rather than the actual balances. However, while this approach hides transaction values, it does not hide user identities. To also hide user identities, every transaction would need to update all commitments in the table, which becomes increasingly inefficient as the number of users grows. - -Although the account model is more intuitive for developers, it uses account addresses to index global state. This means that while a private account model can achieve privacy for inputs and outputs, it still compromises user privacy since account addresses cannot be encrypted. Another issue with the private account model is the lack of concurrency, as only one user can access and update the entire program state at a time. - -Aleo's record model uses program IDs to uniquely identify programs instead of account addresses. This improves privacy and enables programs to have internal states. This approach is more efficient and solves the concurrency issue. - -## Conclusion -Aleo is new a layer-1 blockchain that emphasizes on programmable privacy and scalability. It has chosen the record model as it's fundamental data structure because the account-based model cannot provide privacy with scalability. The record model also provides an enhancement over the UTXO model used in bitcoin, by it's ability to encode any arbitrary data, thus providing programmable privacy. - - - diff --git a/documentation updates aleo ambassadors/src/build/README.md b/documentation updates aleo ambassadors/src/build/README.md deleted file mode 100644 index 405d1ab08..000000000 --- a/documentation updates aleo ambassadors/src/build/README.md +++ /dev/null @@ -1 +0,0 @@ -# BUILD diff --git a/documentation updates aleo ambassadors/src/build/data-and-analytics/README.md b/documentation updates aleo ambassadors/src/build/data-and-analytics/README.md deleted file mode 100644 index d742cf0f8..000000000 --- a/documentation updates aleo ambassadors/src/build/data-and-analytics/README.md +++ /dev/null @@ -1 +0,0 @@ -# Data and analytics diff --git a/documentation updates aleo ambassadors/src/build/development-network/README.md b/documentation updates aleo ambassadors/src/build/development-network/README.md deleted file mode 100644 index 7d75dc849..000000000 --- a/documentation updates aleo ambassadors/src/build/development-network/README.md +++ /dev/null @@ -1 +0,0 @@ -# Development Netowrk diff --git a/documentation updates aleo ambassadors/src/build/leo/README.md b/documentation updates aleo ambassadors/src/build/leo/README.md deleted file mode 100644 index 28e40cf76..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/README.md +++ /dev/null @@ -1 +0,0 @@ -# Leo diff --git a/documentation updates aleo ambassadors/src/build/leo/ale-sdk/python/zkml-transpiler.md b/documentation updates aleo ambassadors/src/build/leo/ale-sdk/python/zkml-transpiler.md deleted file mode 100644 index 63b8048bb..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/ale-sdk/python/zkml-transpiler.md +++ /dev/null @@ -1 +0,0 @@ -# zkML Transpiler diff --git a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/README.md b/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/README.md deleted file mode 100644 index 7567930ba..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/README.md +++ /dev/null @@ -1 +0,0 @@ -# Aleo SDK diff --git a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/create-aleo-app/README.md b/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/create-aleo-app/README.md deleted file mode 100644 index abe525963..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/create-aleo-app/README.md +++ /dev/null @@ -1 +0,0 @@ -# Create Aleo App diff --git a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/create-aleo-app/installation.md b/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/create-aleo-app/installation.md deleted file mode 100644 index b0d432174..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/create-aleo-app/installation.md +++ /dev/null @@ -1,32 +0,0 @@ -# Create Aleo App -# Installation - - Create Aleo App - -## Scaffolding Your First Aleo Project - -:::note -**Compatibility:** -[Node.js](https://nodejs.org/en/) version 18+ -::: - -With NPM: - -```bash -npm create aleo-app@latest -``` - -1. Enter the project name. -2. This will prompt you to choose a preferred framework from the following options: - - `React` - - `Node.js` - - `Vanilla (JavaScript)` - -3. If you choose `React` as your framework, the supported templates are: - - `JavaScript` + `Leo` - - `TypeScript` + `Leo` - - `TypeScript` + `Next.js` - -## More Information - -Based on create-vite: https://github.com/vitejs/vite/tree/main/packages/create-vite diff --git a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/create-aleo-app/react-js-leo-tutorial.md b/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/create-aleo-app/react-js-leo-tutorial.md deleted file mode 100644 index c5b42317d..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/create-aleo-app/react-js-leo-tutorial.md +++ /dev/null @@ -1 +0,0 @@ -# React + JS + Leo Tutorial diff --git a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/js-ts.md b/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/js-ts.md deleted file mode 100644 index d081981f1..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/js-ts.md +++ /dev/null @@ -1 +0,0 @@ -# Javascript/TypeScript diff --git a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/js-ts/README.md b/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/js-ts/README.md deleted file mode 100644 index d081981f1..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/js-ts/README.md +++ /dev/null @@ -1 +0,0 @@ -# Javascript/TypeScript diff --git a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/js-ts/account.md b/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/js-ts/account.md deleted file mode 100644 index 50b219504..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/js-ts/account.md +++ /dev/null @@ -1 +0,0 @@ -# Account diff --git a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/js-ts/aleo-network-client.md b/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/js-ts/aleo-network-client.md deleted file mode 100644 index 7c0b23633..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/js-ts/aleo-network-client.md +++ /dev/null @@ -1,364 +0,0 @@ -# Aleo Network Client - - - -## Overview -

Connection management class that encapsulates REST calls to publicly exposed endpoints of Aleo nodes. -The methods provided in this class provide information on the Aleo Blockchain

- -**Kind**: global class - -* [AleoNetworkClient](#AleoNetworkClient) - * [new AleoNetworkClient(host)](#new_AleoNetworkClient_new) - * [.setAccount(host)](#AleoNetworkClient+setHost) - * [.setAccount(account)](#AleoNetworkClient+setAccount) - * [.getAccount()](#AleoNetworkClient+getAccount) - * [.getBlock(height)](#AleoNetworkClient+getBlock) - * [.getBlockRange(start, end)](#AleoNetworkClient+getBlockRange) - * [.getProgram(programId)](#AleoNetworkClient+getProgram) - * [.getProgramObject(programId)](#AleoNetworkClient+getProgramObject) - * [.getProgramImports(programId)](#AleoNetworkClient+getProgramImports) - * [.getDeploymentTransactionIDForProgram(programId)](#AleoNetworkClient+getDeploymentTransactionIDForProgram) - * [.getDeploymentTransactionForProgram(programId)](#AleoNetworkClient+getDeploymentTransactionForProgram) - * [.getProgramMappingNames(programId)](#AleoNetworkClient+getProgramMappingNames) - * [.getMappingValue(programId, mappingName, key)](#AleoNetworkClient+getMappingValue) - * [.getLatestBlock()](#AleoNetworkClient+getLatestBlock) - * [.getLatestHeight()](#AleoNetworkClient+getLatestHeight) - * [.getStateRoot()](#AleoNetworkClient+getStateRoot) - * [.getTransaction(id)](#AleoNetworkClient+getTransaction) - * [.getTransactions(height)](#AleoNetworkClient+getTransactions) - * [.getTransactionsInMempool()](#AleoNetworkClient+getTransactionsInMempool) - * [.getTransitionId()](#AleoNetworkClient+getTransitionId) - * [.findUnspentRecords()](#AleoNetworkClient+findUnspentRecords) - - - -### new AleoNetworkClient(host) - -| Param | Type | -| --- | --- | -| host | string | - -**Example** -```js -// Connection to a local node -let local_connection = new AleoNetworkClient("http://localhost:3030"); - -// Connection to a public beacon node -let public_connection = new AleoNetworkClient("https://api.explorer.aleo.org/v1"); -``` - - -### aleoNetworkClient.setHost(host) -

Set a new host for the networkClient

- -| Param | Type | -| --- | --- | -| host | string | - -**Example** -```js -// New connection to a public beacon node -let public_connection = AleoNetworkClient.setHost("https://api.explorer.aleo.org/v1"); -``` - - -### aleoNetworkClient.setAccount(account) -

Set an account

- -**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) - -| Param | Type | -| --- | --- | -| account | Account | - -**Example** -```js -let account = new Account(); -connection.setAccount(account); -``` - - -### aleoNetworkClient.getAccount() -

Return the Aleo account used in the node connection

- -**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) -**Example** -```js -let account = connection.getAccount(); -``` - - -### aleoNetworkClient.getBlock(height) -

Returns the block contents of the block at the specified block height

- -**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) - -| Param | Type | -| --- | --- | -| height | number | - -**Example** -```js -let block = connection.getBlock(1234); -``` - - -### aleoNetworkClient.getBlockRange(start, end) -

Returns a range of blocks between the specified block heights

- -**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) - -| Param | Type | -| --- | --- | -| start | number | -| end | number | - -**Example** -```js -let blockRange = connection.getBlockRange(2050, 2100); -``` - - -### aleoNetworkClient.getProgram(programId) -

Returns the source code of a program

- -**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) - -| Param | Type | -| --- | --- | -| programId | string | - -**Example** -```js -let program = connection.getProgram("foo.aleo"); -``` - - - -### aleoNetworkClient.getProgramObject(programId) -

Returns a program object from a program ID or program source code

- -**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) - -| Param | Type | -| --- | --- | -| programId | string | - -**Example** -```js -let program = connection.getProgramObject("foo.aleo"); -``` - - - -### aleoNetworkClient.getProgramImports(programId) -

Returns an object containing the source code of a program and the source code of all programs it imports

- -**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) - -| Param | Type | -| --- | --- | -| programId | string | - -**Example** -```js -let program = connection.getProgramImports("foo.aleo"); -``` - - - -### aleoNetworkClient.getDeploymentTransactionIDForProgram(programId) -

Returns the deployment transaction id associated with the specified program

- -**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) - -| Param | Type | -| --- | --- | -| programId | string | - -**Example** -```js -let program = connection.getDeploymentTransactionIDForProgram("foo.aleo"); -``` - - - -### aleoNetworkClient.getDeploymentTransactionForProgram(programId) -

Returns the deployment transaction associated with a specified program

- -**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) - -| Param | Type | -| --- | --- | -| programId | string | - -**Example** -```js -let program = connection.getDeploymentTransactionForProgram("foo.aleo"); -``` - - - -### aleoNetworkClient.getProgramMappingNames(programId) -

Returns the names of the mappings of a program

- -**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) - -| Param | Type | -| --- | --- | -| programId | string | - -**Example** -```js -let mappings = connection.getProgramMappingNames("credits.aleo"); -``` - - - -### aleoNetworkClient.getProgramImportNames(programId) -

Get a list of the program names that a program imports

- -**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) - -| Param | Type | -| --- | --- | -| programId | string | - -**Example** -```js -let mappings = connection.getProgramImportNames("foo.aleo"); -``` - - - -### aleoNetworkClient.getMappingValue(programId, mappingName, key) -

Returns the value of a program's mapping for a specific key

- -**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) - -| Param | Type | -| --- | --- | -| programId | string | -| mappingName | string | -| key | string | - -**Example** -```js -## Get public balance of an account -let mappingValue = connection.getMappingValue("credits.aleo", "account", "aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px"); -``` - - -### aleoNetworkClient.getLatestBlock() -

Returns the block contents of the latest block

- -**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) -**Example** -```js -let latestHeight = connection.getLatestBlock(); -``` - - - -### aleoNetworkClient.getLatestHeight() -

Returns the latest block height

- -**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) -**Example** -```js -let latestHeight = connection.getLatestHeight(); -``` - - - -### aleoNetworkClient.getLatestCommittee() -

Returns the latest committee

- -**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) -**Example** -```js -let latestCommittee = connection.getLatestCommittee(); -``` - - -### aleoNetworkClient.getStateRoot() -

Returns the latest state/merkle root of the Aleo blockchain

- -**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) -**Example** -```js -let stateRoot = connection.getStateRoot(); -``` - - -### aleoNetworkClient.getTransaction(id) -

Returns a transaction by its unique identifier

- -**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) - -| Param | Type | -| --- | --- | -| id | string | - -**Example** -```js -let transaction = connection.getTransaction("at1handz9xjrqeynjrr0xay4pcsgtnczdksz3e584vfsgaz0dh0lyxq43a4wj"); -``` - - - -### aleoNetworkClient.getTransactions(height) -

Returns the transactions present at the specified block height

- -**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) - -| Param | Type | -| --- | --- | -| height | number | - -**Example** -```js -let transactions = connection.getTransactions(654); -``` - - -### aleoNetworkClient.getTransactionsInMempool() -

Returns the transactions in the memory pool.

- -**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) -**Example** -```js -let transactions = connection.getTransactionsInMempool(); -``` - - -### aleoNetworkClient.getTransitionId() -

Returns the transition id by its unique identifier

- -**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) -**Example** -```js -let transition = connection.getTransitionId("2429232855236830926144356377868449890830704336664550203176918782554219952323field"); -``` - - -### aleoNetworkClient.findUnspentRecords() -

Attempts to find unspent records in the Aleo blockchain for a specified private key

- -**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) -**Example** -```js -// Find all unspent records -const privateKey = "[PRIVATE_KEY]"; -let records = connection.findUnspentRecords(0, undefined, privateKey); - -// Find specific amounts -const startHeight = 500000; -const amounts = [600000, 1000000]; -let records = connection.findUnspentRecords(startHeight, undefined, privateKey, amounts); - -// Find specific amounts with a maximum number of cumulative microcredits -const maxMicrocredits = 100000; -let records = connection.findUnspentRecords(startHeight, undefined, privateKey, undefined, maxMicrocredits); -``` diff --git a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/js-ts/development-client.md b/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/js-ts/development-client.md deleted file mode 100644 index 3faf21754..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/js-ts/development-client.md +++ /dev/null @@ -1 +0,0 @@ -# Development Client diff --git a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/js-ts/guide.md b/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/js-ts/guide.md deleted file mode 100644 index f65662a5f..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/js-ts/guide.md +++ /dev/null @@ -1,1187 +0,0 @@ -# Javascript/Typescript - - - - Aleo SDK - - - - -## Tools for Building Zero Knowledge Web Apps - -The Aleo SDK is a collection of JavaScript libraries for building zero knowledge web applications in both the browser -and node.js. - -## Overview - -Aleo provides the ability to run programs in zero knowledge. The Aleo SDK provides the tools to use these programs -within the browser and all other levels of the web stack to build privacy preserving applications. - -The Aleo SDK provides the following functionality (Click to see examples): -1. [Aleo account management](https://provable.tools/account) -2. [Web-based program execution and deployment](https://provable.tools/develop) -3. [Aleo credit transfers](https://provable.tools/transfer) -4. [Management of program state and data](https://provable.tools/record) -5. [Communication with the Aleo network](https://provable.tools/rest) - -## Table of Contents - -* [Installation](#Installation) -* [Usage](#Usage) - * [Zero Knowledge Web App Examples](#Zero-Knowledge-Web-App-Examples) - * [Create Aleo App](#create-aleo-app) - * [Provable.tools](#provabletools) - * [Create An Aleo Account](#1-create-an-aleo-account) - * [Execute Aleo Programs](#2-execute-aleo-programs) - * [Aleo Programs](#21-aleo-programs) - * [Program Execution Model](#22-program-execution-model) - * [WebAssembly Initialization](#23-webassembly-initialization) - * [Local Program Execution](#24-local-program-execution) - * [Online Program Execution](#25-program-execution-on-the-aleo-network) - * [Program Proving Keys and Records](#26-program-proving-keys--program-records) - * [Deploy Programs](#27-deploy-a-new-program-to-the-aleo-network) - * [React Example](#28-react-example) - * [Aleo Credit Transfers](#3-aleo-credit-transfers) - * [Aleo Credits](#31-aleo-credits) - * [Transfer Aleo Credits](#32-transfer-aleo-credits) - * [Check Public Balances](#32-checking-public-balances) - * [Program Data and Private State](#4-managing-program-data-and-private-state) - * [Private State Data: Records](#41-private-state-data-records) - * [Record Usage Example](#42-record-usage-example-private-value-transfers) - * [Public State Data: Mappings](#43-public-state-data-mappings) - * [Reading Mappings](#44-reading-mappings) - * [Initializing and Updating Mappings](#45-initializing--updating-mappings) - * [Communicating with the Aleo Network](#5-communicating-with-the-aleo-network) -* [Further Documentation](#further-documentation) - -## Installation - -### NPM - -To install the Aleo SDK from NPM run: - -`npm install @aleohq/sdk` or `yarn add @aleohq/sdk`. - -### Build from source - -To build the project from source, go to this project's root and execute: - -`npm install && npm run build` - -## Usage - -## Zero Knowledge Web App Examples - -### Create Aleo App -A set of fully functional examples of zero knowledge web apps can be found in -[create-aleo-app](https://github.com/AleoHQ/sdk/tree/testnet3/create-aleo-app). Create-aleo-app provides several web-app -templates in common web frameworks such as React that can be used as a starting point for building zero knowledge web apps. - -Developers can get started immediately with create-react-app by running: -`npm create aleo-app@latest` - -### Provable.tools - -Additionally, the SDK powers [Provable.tools](https://provable.tools) - a React app that provides a graphical interface for most -of the functionality provided by the SDK and can be used as a reference for usage of the SDK. Source code for provable.tools -can be found [in the SDK repo here](https://github.com/AleoHQ/sdk/tree/testnet3/website) - -## 1. Create an Aleo Account - -The first step in operating a zero knowledge web application is creating a cryptographic identity for a user. In the -context of Aleo, this process starts by generating a private key. From this private key, several keys that enable a user -to interact with Aleo programs can be derived. - -These keys include: -#### Private Key -The key used to represent an identity of an individual user. This key is used to authorize zero -knowledge program execution. -#### View Key -This key is derived from the private key and can be used to identify all records and transaction data that -belongs to an individual user. -#### Compute Key -A key that can be used to trustlessly run applications and generate transactions on a user's behalf. -#### Address -A public address that can be used to trustlessly identify a user in order for that user to receive official -Aleo credits or unique data defined by other zero-knowledge Aleo programs. - -All of these keys can be created using the account object: -```typescript -import { Account } from '@aleohq/sdk'; - -const account = new Account(); - -// Individual keys can then be accessed through the following methods -const privateKey = account.privateKey(); -const viewKey = account.viewKey(); -const address = account.address(); -``` - -Please note that all keys are considered sensitive information and should be stored securely. - -## 2. Execute Aleo Programs - -### 2.1 Aleo Programs - -Aleo programs provide the ability for users to make any input or output of a program private and prove that the program -was run correctly. Keeping program inputs and outputs private allows developers to build privacy into their applications. - -Zero-Knowledge programs are written in one of two languages: -1. [Leo](https://developer.aleo.org/leo/language): A high level, developer friendly language for developing - zero knowledge programs. -2. [Aleo Instructions](https://developer.aleo.org/aleo/): A low level language that provides developers fine - grained control over the execution flow of zero knowledge programs. Leo programs are compiled into Aleo Instructions - under the hood. - -Documentation for both languages can be found at [developer.aleo.org](https://developer.aleo.org). - -#### Hello world in the Leo Language -``` -// A simple program adding two numbers together -program helloworld.aleo { - transition hello(public a: u32, b: u32) -> u32 { - let c: u32 = a + b; - return c; - } -} -``` - -#### Hello world in Aleo instructions -``` -program helloworld.aleo; - -// The leo code above compiles to the following Aleo instructions -function hello: - input r0 as u32.public; - input r1 as u32.private; - add r0 r1 into r2; - output r2 as u32.private; -``` - -### 2.2 Program Execution Model - -The SDK provides the ability to execute Aleo Instructions programs %100 client-side within the browser. - -The `ProgramManager` object encapsulates the functionality for executing programs and making zero knowledge proofs about -them. Under the hood it uses cryptographic code compiled from [snarkVM](https://developer.aleo.org/aleo) into WebAssembly. -JavaScript bindings to this WebAssembly code allows execution of programs in zero knowledge fully within the browser -without requiring any external communication with the internet. Users interested in lower level details on how this is -achieved can visit the [aleo-wasm](https://github.com/AleoHQ/sdk/tree/testnet3/wasm) crate. - -The basic execution flow of a program is as follows: -1. A web app is loaded with an instance of the `ProgramManager` object -2. An Aleo program in `Aleo Instructions` format is loaded into the `ProgramManager` as a wasm object -3. The web app provides a user input form for the program -4. The user submits the inputs and the zero knowledge execution is performed client-side within WebAssembly -5. The result is returned to the user -6. (Optional) A fully encrypted zero knowledge transcript of the execution is optionally sent to the Aleo network - -A diagrammatic representation of the program execution flow is shown below. -```mermaid -graph LR - p1[Leo Program] - p2[Aleo Instructions] - - subgraph Browser Web-App - subgraph ProgramManager - subgraph Aleo-Wasm-Module - in-memory-program - end - end - end - - p1-->p2--load program--oin-memory-program-.ZK result.->user - user-.user input.->in-memory-program - in-memory-program-."ZK result (Optional)".->Aleo-Network -``` - -### 2.3 WebAssembly Initialization - -❗WebAssembly must be initialized before calling any SDK functions. The current Aleo SDK manages the wasm initialization. Therefore, the workers must be defined properly. - -Aleo programs are made zero knowledge through the usage of `ZkSnarks`. The Rust code behind Aleo programs and the ZkSnarks -that make them zero knowledge are hosted in the [snarkVM Repository](https://github.com/AleoHQ/SnarkVM). The Aleo SDK -compiles this code to WebAssembly and creates JavaScript bindings, enabling Aleo programs to run directly in the browser. - -Before any logic within the SDK is run within the browser however, the WebAssembly module the SDK contains must be -initialized before any SDK functions can be executed. This is done simply by calling the `initializeWasm` function at a -point in your code before any other SDK functions are called: -```typescript -import { Account, initializeWasm } from '@aleohq/sdk'; - -// Assuming top-level await is enabled. This can also be initialized within a promise. -await initializeWasm(); - -/// Create a new Aleo account -const account = new Account(); -```` - -An example of how to initialize WebAssembly in a React app is shown in [Section 2.8](#28-React-Example) - -### 2.4 Local Program Execution -A simple example of running the hello world program within the web browser is shown below: -```typescript -import { Account, Program } from '@aleohq/sdk'; - -/// Create the source for the "hello world" program -const program = "program helloworld.aleo;\n\nfunction hello:\n input r0 as u32.public;\n input r1 as u32.private;\n add r0 r1 into r2;\n output r2 as u32.private;\n"; -const programManager = new ProgramManager(); - -/// Create a temporary account for the execution of the program -const account = new Account(); -programManager.setAccount(account); - -/// Get the response and ensure that the program executed correctly -const executionResponse = await programManager.executeOffline(program, "hello", ["5u32", "5u32"]); -const result = executionResponse.getOutputs(); -assert(result === ["10u32"]); -``` - -### 2.5 Program execution on the Aleo Network -The SDK also provides the ability to execute programs and record an encrypted transcript of the execution on the Aleo -network that anyone can trustlessly verify. - -This process can be thought of being executed in three steps: -1. A program is run locally -2. A proof that the program was executed correctly and that the outputs follow from the inputs is generated -3. A transcript of the proof is generated client-side containing encrypted proof data (see [Section 4](#4-managing-program-data-and-private-state)) - and any public outputs or state the user of the program wishes to reveal -4. The proof transcript is posted to the Aleo network and verified by the Aleo validator nodes in a trustless manner -5. If the proof is valid, it is stored and anyone can later verify the proof and read the outputs the author of the - program has chosen to make public. Private inputs will remain encrypted, but the author of the proof can also choose to - retrieve this encrypted state at any point and decrypt it locally for their own use. - -This process of posting the execution to the Aleo Network serves as a globally trustless and verifiable record of -program execution. It also provides a global record of any state changes made to either records or data stored on the Aleo network. - -A simple example of running the hello world program on the Aleo network is shown below: -```typescript - import { Account, AleoNetworkClient, NetworkRecordProvider, ProgramManager, KeySearchParams} from '@aleohq/sdk'; - -// Create a key provider that will be used to find public proving & verifying keys for Aleo programs -const keyProvider = new AleoKeyProvider(); -keyProvider.useCache = true; - -// Define an account which will execute the transaction on-chain -const account = new Account({ privateKey: private_key }); -const privateKeyObject = PrivateKey.from_string(private_key); - -// Create a record provider that will be used to find records and transaction data for Aleo programs -const networkClient = new AleoNetworkClient("https://api.explorer.aleo.org/v1"); -const recordProvider = new NetworkRecordProvider(account, networkClient); - -// Initialize a program manager to talk to the Aleo network with the configured key and record providers -const programName = "hello_hello.aleo"; -const programManager = new ProgramManager("https://api.explorer.aleo.org/v1", keyProvider, recordProvider); -programManager.setHost("https://api.explorer.aleo.org/v1") -programManager.setAccount(account); - -// For example: "cacheKey": "hello_hello:hello" -const cacheKey = `${programId}:${aleoFunction}`; -const keySearchParams = new AleoKeyProviderParams({ "cacheKey": cacheKey }); - -// Execute the program function -const executionResponse = await programManager.execute( - programId, - aleoFunction, - fee, - false, - inputs, - undefined, - keyParams, - undefined, - undefined, - undefined, - privateKeyObject - ); - -const transaction = await programManager.networkClient.getTransaction(executionResponse); - -``` - -A reader of the above example may notice the `RecordProvider` and `KeyProvider` classes that were not present in the local -execution example. The `KeyProvider` class helps users of the SDK find `Proving Keys` for programs. `Proving Keys` -allow zero knowledge proofs that the programs were executed correctly to be created. The `RecordProvider` class helps -find `Records` which are private data associated with programs that can be changed and updated throughout time. -These two concepts are explained in more detail below. - -### 2.6 Program Proving Keys & Program Records - -Executing Aleo programs in zero knowledge requires two additional pieces of information. - -1. **Function Proving & Verifying Keys:** Proving and Verifying keys are cryptographic keys that are generated when a - program function is executed. These keys are public and unique for each function in a program. The proving key allows any party to - execute the program and generate a proof that the program was executed correctly. The verifying keys allow any party - to verify that the proof was generated correctly and the execution is correct. These keys are required to create the - zero knowledge property of program execution. -2. **Program Records:** Records are private state generated by a program belonging to a unique private keyholder. Records - are generated by a program's functions and can be changed and updated by when a user runs various functions of the - program. These records are private by default and are used to manage updatable private state. One of the most clear - usages of records is to the `credits` record in the `credits.aleo`. Credits records are one of two official ways of - representing Aleo credits on the Aleo Network and are used to pay all transaction fees on the network. More information - on Records can be found in the [Records](#41-private-state-data--records) section below. - -For this reason, all programs will need proving and verifying keys to operate and many functions in Aleo programs will -require records as inputs. To simplify the process of managing keys and records, the Aleo SDK provides two abstractions -for managing these concepts: - -1. **KeyProvider:** When programs execute, by default, they will synthesize the proving and verifying keys needed to - make a zero knowledge proof. However, these keys are large and expensive to generate. For this reason, applications may - want to store these keys and re-use them for future execution. The `KeyProvider` interface provides the ability for - users of the SDK to provide their own key storage and retrieval mechanism. The SDK provides a default implementation - of the `KeyProvider` interface via the `AleoKeyProvider` class. -2. **RecordProvider:** When programs execute, they will often need to find records that belong to a user. The - `RecordProvider` interface allows users of the SDK to implement their own record storage and retrieval mechanism. The - SDK provides a default implementation of the `RecordProvider` interface via the `NetworkRecordProvider` class which - searches the Aleo network for records uniquely belonging to a user. - -The `ProgramManager` class is capable of taking a `KeyProvider` and `RecordProvider` as arguments and will use them to -find the correct keys and records for a program execution. - -### 2.7 Deploy a new Program to the Aleo Network - -The Aleo Network contains a public registry of programs that can be executed by anyone. Any user can add an Aleo program -to the network (as long as it doesn't already currently exist) by paying a deployment fee in Aleo credits. The SDK -provides a simple interface for deploying programs to the Aleo network using the program manager. - -```typescript -import { Account, AleoNetworkClient, NetworkRecordProvider, ProgramManager, KeySearchParams} from '@aleohq/sdk'; - -// Create a key provider that will be used to find public proving & verifying keys for Aleo programs -const keyProvider = new AleoKeyProvider(); -keyProvider.useCache = true; - -// Create a record provider that will be used to find records and transaction data for Aleo programs -const networkClient = new AleoNetworkClient("https://api.explorer.aleo.org/v1"); -const recordProvider = new NetworkRecordProvider(account, networkClient); - -// Initialize a program manager to talk to the Aleo network with the configured key and record providers -const programManager = new ProgramManager("https://api.explorer.aleo.org/v1", keyProvider, recordProvider); - -// Define an Aleo program to deploy -const program = "program hello_hello.aleo;\n\nfunction hello:\n input r0 as u32.public;\n input r1 as u32.private;\n add r0 r1 into r2;\n output r2 as u32.private;\n"; - -// Define a fee to pay to deploy the program -const fee = 1.8; // 1.8 Aleo credits - -// Deploy the program to the Aleo network -const tx_id = await programManager.deploy(program, fee); - -// Verify the transaction was successful -const transaction = await programManager.networkClient.getTransaction(tx_id); -``` - -### 2.8 React Example - -The above concepts can be tied together in a concrete example of a React web app. This example can be installed in one -step by running: - -`npm create aleo-app@latest` - -#### Wasm Initialization - -The WASM module can be initialized within the browser. A common way of achieving this within a React App is using a React UseEffect hook. - -`aleo-wasm-hook.js` -```jsx -import { useEffect, useState } from "react"; -import * as sdk from "@aleohq/sdk"; - -await sdk.initializeWasm(); -export const useAleoWASM = () => { - const [aleoInstance, setAleoInstance] = useState(null); - - useEffect(() => { - if (aleoInstance === null) { - setAleoInstance(sdk); - } - }, []); // eslint-disable-line react-hooks/exhaustive-deps - return aleoInstance; -}; -```` -Once a hook for the WASM initialization is created, it can be used anywhere within the app. - -#### Program Execution - -Program execution is a computationally expensive process. For this reason, it is recommended to execute programs in -webworkers. - -We will have 2 main components for workers: -- worker.js -- AleoWorker.js (Manager for worker file) - -
-Example Web Worker Usage - -A worker file that performs the execution can be created as follows: -`worker.js` -```jsx -import { - Account, - ProgramManager, - PrivateKey, - initThreadPool, - AleoKeyProvider, - AleoNetworkClient, - NetworkRecordProvider, -} from "@aleohq/sdk"; -import { expose, proxy } from "comlink"; - -await initThreadPool(); - -async function localProgramExecution(program, aleoFunction, inputs) { - const programManager = new ProgramManager(); - - // Create a temporary account for the execution of the program - const account = new Account(); - programManager.setAccount(account); - - const executionResponse = await programManager.run( - program, - aleoFunction, - inputs, - false, - ); - return executionResponse.getOutputs(); -} - -async function getPrivateKey() { - const key = new PrivateKey(); - return proxy(key); -} - -async function deployProgram(program) { - const keyProvider = new AleoKeyProvider(); - keyProvider.useCache(true); - - // Create a record provider that will be used to find records and transaction data for Aleo programs - const networkClient = new AleoNetworkClient("https://api.explorer.aleo.org/v1"); - - // Use existing account with funds - const account = new Account({ - privateKey: "user1PrivateKey", - }); - - const recordProvider = new NetworkRecordProvider(account, networkClient); - - // Initialize a program manager to talk to the Aleo network with the configured key and record providers - const programManager = new ProgramManager( - "https://api.explorer.aleo.org/v1", - keyProvider, - recordProvider, - ); - - programManager.setAccount(account); - - // Define a fee to pay to deploy the program - const fee = 1.9; // 1.9 Aleo credits - - // Deploy the program to the Aleo network - const tx_id = await programManager.deploy(program, fee); - - return tx_id; -} - -const workerMethods = { localProgramExecution, getPrivateKey, deployProgram }; -expose(workerMethods); -``` - -`AleoWorker.js` -```jsx -import { wrap } from "comlink"; - -let singletonWorker = null; - -const AleoWorker = () => { - if (!singletonWorker) { - const worker = new Worker(new URL("worker", import.meta.url), { - type: "module", - }); - - worker.onerror = function(event) { - console.error("Error in worker: " + event?.message); - }; - - singletonWorker = wrap(worker); - } - return singletonWorker; -}; - -export { AleoWorker }; -``` -
- -Using both WebWorkers and SDK initialization in React, a single-page app can be created by importing `AleoWorker.js`, which executes Aleo zero-knowledge programs. - -
-Example App.jsx Implementing Zero Knowledge Program Execution - -```jsx -import { useState } from "react"; -import reactLogo from "./assets/react.svg"; -import aleoLogo from "./assets/aleo.svg"; -import "./App.css"; -import helloworld_program from "../helloworld/build/main.aleo?raw"; -import { AleoWorker } from "./workers/AleoWorker"; - -const aleoWorker = AleoWorker(); -function App() { - const [count, setCount] = useState(0); - const [account, setAccount] = useState(null); - const [executing, setExecuting] = useState(false); - const [deploying, setDeploying] = useState(false); - - const generateAccount = async () => { - const key = await aleoWorker.getPrivateKey(); - setAccount(await key.to_string()); - }; - - async function execute() { - setExecuting(true); - const result = await aleoWorker.localProgramExecution( - helloworld_program, - "main", - ["5u32", "5u32"], - ); - setExecuting(false); - - alert(JSON.stringify(result)); - } - - async function deploy() { - setDeploying(true); - try { - const result = await aleoWorker.deployProgram(helloworld_program); - console.log("Transaction:") - console.log("https://api.explorer.aleo.org/v1/transaction?id=" + result) - alert("Transaction ID: " + result); - } catch (e) { - console.log(e) - alert("Error with deployment, please check console for details"); - } - setDeploying(false); - } - - return ( - <> -
- - Aleo logo - - - React logo - -
-

Aleo + React

-
- -

- -

-

- -

-

- Edit src/App.jsx and save to test HMR -

-
- - {/* Advanced Section */} -
-

Advanced Actions

-

- Deployment on Aleo requires certain prerequisites like seeding your - wallet with credits and retrieving a fee record. Check README for more - details. -

-

- -

-
-

- Click on the Aleo and React logos to learn more -

- - ); -} - -export default App; -``` - -
- -#### Integrating Aleo Programs Into Your App - -If you are starting with a simple framework template rather than with Aleo templates, handling files with a .aleo extension in a web application requires specific configurations because these files are not natively recognized by most web development environments. The .aleo extension typically belongs to Aleo zero-knowledge programs, which are special scripts or codes used within the Aleo platform to ensure privacy and security through cryptographic proofs. - -To integrate these files into a web application, such as a React app, you need to define how they should be treated during the build process. - -**Configuration File** - -Adding configuration rules in your build system (like Vite, Webpack, or Next.js) is necessary to tell the build tool how to process these files. Using something like raw-loader in this configuration ensures that .aleo files are loaded as plain text. This step is essential because it converts the content of .aleo files into a usable format that your web application can execute or display. - -``` -module:{ - rules:[ - { - test: /\.aleo$/i, - use: 'raw-loader', - }, - ] -} -``` - -
-Handling .aleo Types in TypeScript -`config.d.ts` -If you are using TypeScript, you need to inform the TypeScript compiler about the type of content these files contain by declaring a module for *.aleo files: -``` -declare module '*.aleo' { - const content: string; - export default content; - } -``` -Make sure that you included custom types in your `tsconfig` file. - -
- - -A full example of this implementation can be found [here](https://github.com/AleoHQ/sdk/blob/testnet3/create-aleo-app/template-react-leo/src/App.jsx) - -## 3. Aleo Credit Transfers - -### 3.1 Aleo Credits - -The official token of operation of the Aleo Network are Aleo credits. Aleo credits are used to pay all fees for program -execution on the Aleo network. - - - -Aleo credits are defined in the [credits.aleo](https://explorer.aleo.org/program/credits.aleo) program. This program is -deployed to the Aleo Network and defines data structures representing Aleo credits and the functions used to manage them. - - - -There are two ways to hold Aleo credits. - -#### 1 - Private balances via credits.aleo records -The first method is owning a `credits` record which enables a participant in the Aleo -network to hold a private balance of Aleo credits. -``` -record credits: - owner as address.private; - microcredits as u64.private; -``` - -A user's total private credits balance will consist of all unspent `credits` records owned by the user with a nonzero -`microcredits` value. - -#### 2 - Public balances via credits.aleo account mapping -The second is by holding a `balance` in the `account` mapping in the `credits.aleo` program on the Aleo Network. - -``` -mapping account: - key owner as address.public; - value microcredits as u64.public; -``` - -The total public credits balance of a user is the value of account mapping at the user's address. Users can hold both private and public balances simultaneously. - -More information about `records` and `mappings` and how they related to private and public balances are explained in the -[Managing Program Data and Private State](#4-managing-program-data-and-private-state) section. - -### 3.2 Transfer Aleo Credits -The `ProgramManager` allows transfers of aleo credits via the `transfer` method. This function executes the credits.aleo -program under the hood. - -There are four transfer functions available. - -#### 1. transfer_private - -Takes a `credits` record of owned by the sender, subtracts an amount from it, and adds that amount -to a new record owned by the receiver. This function is %100 private and does not affect the `account` mapping. - -```mermaid -graph LR - user1--record1 \n owner: user1address \n balance: 10000u64-->t1[transfer_private] - user1--amount: 4000u64-->t1 - t1-.record2 \n owner: user1address \n amount: 6000u64.->user1 - t1--record3 \n owner: user2address \n balance: 4000u64-->user2 - -``` - -#### 2. transfer_private_to_public -Takes a `credits` record of owned by the sender, subtracts an amount from it, and adds -that amount to the `account` mapping of the receiver. This function is %50 private and %50 public. It consumes a record -as a private input and generates a public balance in the `account` mapping entry belonging to the receiver. - -```mermaid -graph LR - subgraph credits.aleo - m1[account mapping \n key: user3address \n value: 3000u64] - end - user1--record3 \n owner: user2address \n balance: 4000u64-->t1[transfer_private_to_public] - t1-.record4 \n owner: user2address \n amount: 1000u64.->user1 - t1--amount 3000u64-->m1 -``` - -#### 3. transfer_public - -Subtracts an amount of `credits` stored in the `account` mapping of the `credits.aleo program`, and -adds that amount to the `account` mapping of the receiver. This function is 100% public and does not consume or generate -any records. - -```mermaid -graph LR - subgraph credits.aleo account mappings - state 2 - m3[account mapping \n key: user4address \n value: 3000u64] - m4[account mapping \n key: user3address \n value: 0u64] - end - - subgraph credits.aleo account mappings - state 1 - m2[account mapping \n key: user3address \n value: 3000u64]--transfer_public \n recipient: user4address \n amount: 3000u64-->m3 - m1[account mapping \n key: user4address \n value: N/A] - end -``` - -#### 4. transfer_public_to_private -Subtracts an amount `credits` stored in the `account` mapping of the `credits.aleo program` -and adds that amount to a new private record owned by the receiver. This function is %50 private and %50 public. -It publicly consumes a balance in the `account` mapping entry belonging to the sender and generates a private record -as a private output. - -```mermaid -graph LR - subgraph credits.aleo account mappings - state 2 - m2[account mapping \n key: user5address \n value: 0u64] - end - - subgraph credits.aleo account mappings - state 1 - m1[account mapping \n key: user5address \n value: 3000u64] - end - - m1--recipient: user6address \n amount: 3000u64-->transfer_public_to_private - transfer_public_to_private--record5 \n owner: user6address \n amount: 3000u64-->user6 -``` - -All four of these functions can be used to transfer credits between users via the `transfer` function in the -`ProgramManager` by specifying the transfer type as the third argument. - -```typescript -import { Account, ProgramManager, AleoKeyProvider, NetworkRecordProvider, AleoNetworkClient } from '@aleo/sdk'; - -// Create a new NetworkClient, KeyProvider, and RecordProvider -const account = Account.from_string({privateKey: "user1PrivateKey"}); -const networkClient = new AleoNetworkClient("https://api.explorer.aleo.org/v1"); -const keyProvider = new AleoKeyProvider(); -const recordProvider = new NetworkRecordProvider(account, networkClient); - -// Initialize a program manager with the key provider to automatically fetch keys for executions -const USER_1_ADDRESS = "user1Address"; -const programManager = new ProgramManager("https://api.explorer.aleo.org/v1", keyProvider, recordProvider); -programManager.setAccount(account); - -// Send a private transfer to yourself -const tx_id = await programManager.transfer(1, USER_1_ADDRESS, "transfer_private", 0.2); - -// Update or initialize a public balance in your own account mapping -const tx_id_2 = await programManager.transfer(1, USER_1_ADDRESS, "transfer_private_to_public", 0.2); - -// Check the value of your public balance -let public_balance = programManager.networkClient.getMappingValue("credits.aleo", USER_1_ADDRESS); -assert(public_balance === 0.2*1_000_000); - -/// Send public transfer to another user -const USER_2_ADDRESS = "user2Address"; -const tx_id_3 = await programManager.transfer(1, USER_2_ADDRESS, "transfer_public", 0.1); - -// Check the value of the public balance and assert that it has been updated -public_balance = programManager.networkClient.getMappingValue("credits.aleo", USER_1_ADDRESS); -const user2_public_balance = programManager.networkClient.getMappingValue("credits.aleo", USER_1_ADDRESS); -assert(public_balance === 0.1*1_000_000); -assert(user2_public_balance === 0.1*1_000_000); - -/// Create a private record from a public balance -const tx_id_4 = await programManager.transfer(1, USER_1_ADDRESS, "transfer_public_to_private", 0.1); - -// Check the value of the public balance and assert that it has been updated -public_balance = programManager.networkClient.getMappingValue("credits.aleo", USER_1_ADDRESS); -assert(public_balance === 0); -``` - -### 3.2 Checking Public Balances -As shown above, a public balance of any address can be checked with `getMappingValue` function of the `NetworkClient`. - -```typescript -const networkClient = new AleoNetworkClient("https://api.explorer.aleo.org/v1"); -const USER_1_ADDRESS = "user1Address"; -const public_balance = networkClient.getMappingValue("credits.aleo", USER_1_ADDRESS); -``` - -## 4. Managing Program Data and Private State - -### 4.1 Private State Data: Records -Records in are analogous to concept of [UTXOs](https://en.wikipedia.org/wiki/Unspent_transaction_output). When a record is -created by a program, it can then be consumed later by the same program as an input to a function. Once a record is used -as input, it is considered consumed and cannot be used again. In many cases a new record will be created from the output -of the function. Records are private by default and are associated with a single Aleo program and a single private key -representing a user. - -### 4.2 Record Usage Example: Private Value Transfers - -A straightforward example of a usage of records in a program can be demonstrated by explaining the process of private -value transfers of official Aleo credits on the Aleo network. - - - -Aleo credits are the official token in which all on-chain execution and deployment fees are paid. Credits can be public -or private. Private credits are represented by the `credits` record in the [credits.aleo](https://explorer.aleo.org/programs/credits.aleo) -program. - - - -``` -record credits: - owner as address.private; - microcredits as u64.private; -``` - -Credits records contain an `owner` field representing the address which owns the record and a `microcredits` field -representing the amount of microcredits in the record. 1 credit is equal to 1,000,000 microcredits. - -An example of an Aleo function that both takes a record as input and outputs a record is the `transfer_private` function -of the `credits.aleo` program. This function takes a private `credits` record as input and outputs two new private `credits` -records as output (one that sends the credits to the recipient and one that sends the remaining credits to the sender). - -The source code for the `transfer_private` is: -``` -function transfer_private: - input r0 as credits.record; - input r1 as address.private; - input r2 as u64.private; - sub r0.microcredits r2 into r3; - cast r1 r2 into r4 as credits.record; - cast r0.owner r3 into r5 as credits.record; - output r4 as credits.record; - output r5 as credits.record; -``` - -The `transfer_private` function can be graphically represented by the graph below. In the graph the first record "Record 1" -is consumed and can never be used again. From the data in Record 1, two more records are created. One containing -the intended amount for the recipient which is now owned by the recipient and another containing the remaining credits -which is sent back to the sender. - -```mermaid -graph LR - User1[Sender Address] - i1[Input 1: Credits Record 1]-->p1 - i2[Input 2: Recipient Address]-->p1 - p1[Credits.aleo:transfer_private] - p1--Credits Record 2-->User1 - p1--Credits Record 3-->R1[Recipient Address] -``` - -This chain of ownership is tracked by the Aleo Blockchain when users choose to submit their transactions to the Aleo -Network. This allows other users who receive records to receive the updated data and verify that this data was -provably generated by the intended program. - -What this process allows is a private chain of state to be created between multiple users. In the context of value -transfers, a chain of state might look like the following: - -```mermaid -graph LR - user1--record1-->t1[transfer_private] - t1-.record2.->user1 - t1--record3-->user2 - user2--record3-->t2[transfer_private] - t2--record5-->user3 - t2-.record4.->user2 -``` - -The above state chain would be executed in the following way using the SDK: -#### Step 1 - User 1 sends a private value transfer to User 2 -```typescript -// USER 1 -import { Account, ProgramManager, AleoKeyProvider, NetworkRecordProvider, AleoNetworkClient } from '@aleo/sdk'; - -// Create a new NetworkClient, KeyProvider, and RecordProvider -const account = Account.from_string({privateKey: "user1PrivateKey"}); -const networkClient = new AleoNetworkClient("https://api.explorer.aleo.org/v1"); -const keyProvider = new AleoKeyProvider(); -const recordProvider = new NetworkRecordProvider(account, networkClient); - -// Initialize a program manager with the key provider to automatically fetch keys for executions -const USER_2_ADDRESS = "user2Address"; -const programManager = new ProgramManager("https://api.explorer.aleo.org/v1", keyProvider, recordProvider); -programManager.setAccount(account); - -/// Send private transfer to user 2 -const tx_id = await programManager.transfer(1, USER_2_ADDRESS, "transfer_private", 0.2); -``` - -#### Step 2 - User 2 receives the transaction ID and fetches the credits record they received from user 1 from the network. They then send it to user 3 - -```typescript -// USER 2 -import { Account, ProgramManager, AleoKeyProvider, NetworkRecordProvider, AleoNetworkClient } from '@aleo/sdk'; - -// Create a new NetworkClient, KeyProvider, and RecordProvider -const account = Account.from_string({privateKey: "user2PrivateKey"}); -const networkClient = new AleoNetworkClient("https://api.explorer.aleo.org/v1"); -const keyProvider = new AleoKeyProvider(); -const recordProvider_User2 = new NetworkRecordProvider(account, networkClient); - -// Initialize a program manager with the key provider to automatically fetch keys for executions -const programManager = new ProgramManager("https://api.explorer.aleo.org/v1", keyProvider, recordProvider); -programManager.setAccount(account); - -// Fetch the transaction from the network that user 1 sent -const transaction = await programManager.networkClient.getTransaction(tx_id); -const record = transaction.execution.transitions[0].outputs[0].value; - -// Decrypt the record with the user's view key -const recordCiphertext = RecordCiphertext.fromString(record); -const recordPlaintext = recordCiphertext.decrypt(account.viewKey()); - -// Send a transfer to user 3 using the record found above -const USER_3_ADDRESS = "user3Address"; -const tx_id = await programManager.transfer(1, USER_3_ADDRESS, "transfer_private", 0.2, undefined, recordPlaintext); -``` - -When an execution such as `transfer_private` consumes or generates a record is posted on the network and encrypted transcript -of the execution is posted, containing an encrypted version of the record output and a transaction ID. - -Because the records are encrypted when they're posted on the network, they do not reveal any information about the party -who executed the program, nor the contents of the record. The only information that is revealed is the program ID, -function name, encrypted function inputs, and the transaction ID of the program execution. No user except for the recipient -of the record can see the contents of the record. - -Below you can see what the exact data which is posted to the Aleo Network when `transfer_private` is run. Note that the -record, the amount transferred, and both the sender & recipient addresses are all encrypted. - -
-transfer_private Execution Transcript - -```json - "transactions": [ - { - "status": "accepted", - "type": "execute", - "index": 0, - "transaction": { - "type": "execute", - "id": "at1s7dxunms8xhdzgaxrwf0yvq2dqgxtf4a3j8g878rhfr0zwhap5gqywsw8y", - "execution": { - "transitions": [ - { - "id": "as1thy8fvkz0rkls5wnmfq5udrcvvzurq7mqk8pkhjf63htqjf9mugqp0mfhd", - "program": "credits.aleo", - "function": "transfer_private", - "inputs": [ - { - "type": "record", - "id": "1406044754369042876058586523429806531093330762697573675195902502647806778955field", - "tag": "242626059121157295593694555515381893342956813170338731374395259242800138642field" - }, - { - "type": "private", - "id": "1533599744296862879610225011439684001995294756698105572984689232395187168232field", - "value": "ciphertext1qgqgpu7m8p0rwjahwffyvm4g4n6903d6ufqty74z4504w4rn356hgp9jvpuvx8suu0pukr3sl7n8x65dz35nu4jdy4lgcguxldygufrfpyqd6xr5" - }, - { - "type": "private", - "id": "4081557229261486898857101724786348855190759711760925564309233047223407640812field", - "value": "ciphertext1qyqxd9wue0qh8hs6dgevn7zleedfkzf7pft8ecked2xq3pw54pgqzyqr69sgx" - } - ], - "outputs": [ - { - "type": "record", - "id": "1388064668770056715587596299070268626507043043686185311840561493640415146425field", - "checksum": "5376939704883651492329501631722578074516322228314928758786996843926470523116field", - "value": "record1qyqsq4r7mcd3ystjvjqda0v2a6dxnyzg9mk2daqjh0wwh359h396k7c9qyxx66trwfhkxun9v35hguerqqpqzqzshsw8dphxlzn5frh8pknsm5zlvhhee79xnhfesu68nkw75dt2qgrye03xqm4zf5xg5n6nscmmzh7ztgptlrzxq95syrzeaqaqu3vpzqf03s6" - }, - { - "type": "record", - "id": "4635504195534945632234501197115926012056789160185660629718795843347495373207field", - "checksum": "3428805926164481449334365355155755448945974546383155334133384781819684465685field", - "value": "record1qyqsp2vsvvfulmk0q0tmxq7p9pffhfhha9h9pxsftujh57kkjuahx9s0qyxx66trwfhkxun9v35hguerqqpqzq8etfmzt2elj37hkf9fen2m2qes8564sr8k970zyud5eqmq7ztzq5r3095mkfdzqzz7yp6qfavqsl3t22t6dvgauqqt2xqk98zwmtusq5ck7fm" - } - ], - "tpk": "5283803395323806407328334221689294196419052177553228331323093330938016699852group", - "tcm": "4398026033398688325681745841147300822741685834906186660771751747897598751646field" - } - ], -``` -
- - -#### Record Decryption - -If a user receives a private record from a program execution, they can use the SDK to decrypt encrypted records with -their view keys and view their contents. Only records that are owned by the user can be decrypted. Decryption of records -that are not owned by the user will fail. - -Record decryption and ownership verification can be done in the SDK using the following code: - -```typescript -import { Account, RecordCiphertext, RecordPlaintext } from '@aleo/sdk'; - -// Create an account from an existing private key -const account = Account.from_string({privateKey: "existingPrivateKey"}); - -// Record value received as a string from program output or found on the Aleo network -const record = "record1qyqsq4r7mcd3ystjvjqda0v2a6dxnyzg9mk2daqjh0wwh359h396k7c9qyxx66trwfhkxun9v35hguerqqpqzqzshsw8dphxlzn5frh8pknsm5zlvhhee79xnhfesu68nkw75dt2qgrye03xqm4zf5xg5n6nscmmzh7ztgptlrzxq95syrzeaqaqu3vpzqf03s6"; - -const recordCiphertext = RecordCiphertext.fromString(record); - -// Check ownership of the record. If the account is the owner, decrypt the record -if (RecordCiphertext.is_owner(account.viewKey())) { - // Decrypt the record with the account's view key - const recordPlaintext = recordCiphertext.decrypt(account.viewKey()); - - // View the record data - console.log(recordPlaintext.toString()); -} -``` - -### 4.3 Public State Data: Mappings -Mappings are simple key value stores defined in a program. They are represented by a key and a value each of a specified -type. They are stored directly within the Aleo blockchain and can be publicly read by any participant in the Aleo network. - -An example of a mapping usage is `account` mapping in the `credits.aleo` program. -``` -mapping account: - key owner as address.public; - value microcredits as u64.public; -``` - -The `account` mapping is used to store public credits balances on the Aleo network. It takes a public address as a key -and a public u64 value representing the number of microcredits owned by the address. - -Mappings within programs are identified by the `mapping` identifier. Any program where this keyword appears contains an -on-chain mapping. An example of a program that uses a mapping is shown below: -``` -program player_mapping_example.aleo - -// The mapping identifier representing a score -mapping score: - key player as address.public; - value score as u64.public; - -// The update score function -function update_score: - input r0 as address.public; - input r1 as u64.public; - -// The finalize code block will be executed by Aleo network nodes. -// When it runs it will update the value of the mapping. -finalize update_score: - input r0 as address.public; - input r1 as u64.public; - get.or_use score[r0] 0u64 into r2; - add r1 r2 into r3; - set r3 into account[r0]; -``` - -Note that the above function has a `finalize` identifier. This identifier is used to identify a portion of a function's -code that should be executed by nodes on the Aleo network. Program mappings are updated exclusively by code run by nodes -on the Aleo Network written in `finalize` blocks. - -### 4.4 Reading Mappings -Any state within a program mapping is public and can be read by any participant in the Aleo network. The `NetworkClient` -class provides the `getMapping` method to read the public mappings within a program and the `getMappingValue` method to -read the value of a specific key within a mapping. - -```typescript -import { AleoNetworkClient } from '@aleo/sdk'; - -const networkClient = new AleoNetworkClient("https://api.explorer.aleo.org/v1"); -const creditsMappings = networkClient.getMappings("credits.aleo"); -assert(creditsMappings === ["account"]); - -const publicCredits = networkClient.getMapping("credits.aleo", "[a valid aleo account with zero balance]"); -assert(publicCredits === "0u64"); -``` - -### 4.5 Initializing & Updating Mappings -Updating mappings is done by executing a program function on the Aleo network which has a finalize block that updates the -program's mapping. For instance the `transfer_public` function in the `credits.aleo` program updates the `account` -mapping (and thus a user's balance) when called. - -``` -// The public interface called by users -function transfer_public: - input r0 as address.public; - input r1 as u64.public; - finalize self.signer r0 r1; - -// The finalize block run by nodes on the Aleo network which update a user's public balance -finalize transfer_public: - input r0 as address.public; - input r1 as address.public; - input r2 as u64.public; - get.or_use account[r0] 0u64 into r3; - sub r3 r2 into r4; - set r4 into account[r0]; - get.or_use account[r1] 0u64 into r5; - add r5 r2 into r6; - set r6 into account[r1]; -``` - -From the perspective of the caller of the API, this is as simple as executing a normal Aleo function. Given the inputs -to a function with a finalize scope that updates a mapping are valid, the mapping will either be intialized or updated -by the Aleo network. All the user of the SDK must do is ensure that the inputs to the function are valid. - -If function inputs are Invalid, the Network will return an error, but the fee paid for the transaction will still be -consumed. So it is important to ensure that the inputs to a function are valid before executing it. - -A simple example of a mapping update can be shown by simply executing the 'transfer_public` as shown below. - -```typescript -import { Account, ProgramManager, AleoKeyProvider, NetworkRecordProvider, AleoNetworkClient } from '@aleo/sdk'; - -// Create a new NetworkClient, KeyProvider, and RecordProvider -const account = Account.from_string({privateKey: "user1PrivateKey"}); -const networkClient = new AleoNetworkClient("https://api.explorer.aleo.org/v1"); -const keyProvider = new AleoKeyProvider(); -const recordProvider = new NetworkRecordProvider(account, networkClient); - -// Initialize a program manager with the key provider to automatically fetch keys for executions -const RECIPIENT_ADDRESS = "user1Address"; -const programManager = new ProgramManager("https://api.explorer.aleo.org/v1", keyProvider, recordProvider); -programManager.setAccount(account); - -// Update or initialize a public balance -const tx_id = await programManager.transfer(1, RECIPIENT_ADDRESS, "transfer_private_to_public", 0.2); -``` - - -## 5. Communicating with the Aleo Network - -Communication with the Aleo network is done through the `AleoNetworkClient` class. This class provides methods to query -data from Aleo network nodes and submit transactions to the Aleo network. - -A full list of methods provided by the `AleoNetworkClient` class and usage examples can be found in the -[Network Client API documentation](https://developer.aleo.org/sdk/typescript/aleo_network_client). - -## Further Documentation - -API documentation for this package, the Leo Language, and Aleo instructions can be found on the [Aleo Developer Hub](https://developer.aleo.org/sdk/typescript/overview). - -To view the API documentation for this package locally, open `docs/index.html`. -To regenerate the documentation, run `npx jsdoc --configure jsdoc.json --verbose` diff --git a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/overview.md b/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/overview.md deleted file mode 100644 index 07dd0c5c7..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/overview.md +++ /dev/null @@ -1 +0,0 @@ -# Overview diff --git a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/python/README.md b/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/python/README.md deleted file mode 100644 index 4193ef4be..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/python/README.md +++ /dev/null @@ -1 +0,0 @@ -# Python diff --git a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/python/aleo-sdk.md b/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/python/aleo-sdk.md deleted file mode 100644 index 7567930ba..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/python/aleo-sdk.md +++ /dev/null @@ -1 +0,0 @@ -# Aleo SDK diff --git a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/wasm/README.md b/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/wasm/README.md deleted file mode 100644 index d4fdb1ba1..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/wasm/README.md +++ /dev/null @@ -1 +0,0 @@ -# Wasm diff --git a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/wasm/browser-multi-threaded.md b/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/wasm/browser-multi-threaded.md deleted file mode 100644 index 8b9cd6e9d..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/wasm/browser-multi-threaded.md +++ /dev/null @@ -1 +0,0 @@ -# Browser(Multi-Threaded) diff --git a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/wasm/installation.md b/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/wasm/installation.md deleted file mode 100644 index 25267fe2b..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/wasm/installation.md +++ /dev/null @@ -1 +0,0 @@ -# Installation diff --git a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/wasm/nodejs-browser.md b/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/wasm/nodejs-browser.md deleted file mode 100644 index d4e4f16ad..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/aleo-sdk/wasm/nodejs-browser.md +++ /dev/null @@ -1 +0,0 @@ -# NodeJS + Browser diff --git a/documentation updates aleo ambassadors/src/build/leo/commands.md b/documentation updates aleo ambassadors/src/build/leo/commands.md deleted file mode 100644 index c3cdfc4f0..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/commands.md +++ /dev/null @@ -1,91 +0,0 @@ -# Commands - -In this section we explore the Leo CLI and explain what each command does. - -Let's get started with creating a new basic project. - - -## leo new -``` -leo new hello -cd hello -``` -This creates a new folder with the following directory structure. -``` -package/ -├── .env # Your program environment -├── program.json # Your program manifest -├── README.md # Your program description -├── build/ # Your built program will be placed here -├── inputs/ # Will be deprecated in the future -└── src/ - └── main.leo # Your program file -``` - -## leo example -Creates a sample program in a new directory -Example: -``` -leo example token -``` -This creates the token example program in a new directory. - -## leo run - -``` -leo run {$TRANSITION} {$INPUTS} -``` -To run a Leo transition function with inputs from the command line. {$INPUTS} should be a list of inputs to the program separated by spaces. This command does not synthesize the program circuit or generate proving and verifying keys. Running this command also builds the program under the build directory. - -Example: - -``` -leo run main 1u32 2u32 -``` -![run output example](./images/run-output.png) - - - -## leo execute - -``` -leo execute {$TRANSITION} {$INPUTS} -``` -To execute a Leo transition function with inputs from the command line. {$INPUTS} should be a list of inputs to the program separated by spaces. This command synthesizes the program circuit and generates proving and verifying keys. - -Example: - -``` -leo execute main 1u32 2u32 -``` - -![run output example](./images/execute-output.png) - - -## leo clean -``` -leo clean -``` -This command cleans the build directory - -## leo account -To create a new Aleo account, run: -``` -leo account new - -# Output: - Private Key APrivateKey1zkp... - View Key AViewKey1... - Address aleo1... -``` - -To import an existing Aleo account, run: -``` -leo account import {$PRIVATE_KEY} -``` - -## leo update -To download and install the latest Leo version, run: -``` -leo update -``` diff --git a/documentation updates aleo ambassadors/src/build/leo/compiling-programs.md b/documentation updates aleo ambassadors/src/build/leo/compiling-programs.md deleted file mode 100644 index 676ddafef..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/compiling-programs.md +++ /dev/null @@ -1 +0,0 @@ -# Compiling Programs diff --git a/documentation updates aleo ambassadors/src/build/leo/deploying-programs.md b/documentation updates aleo ambassadors/src/build/leo/deploying-programs.md deleted file mode 100644 index ef3aa7070..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/deploying-programs.md +++ /dev/null @@ -1 +0,0 @@ -# Deploying Programs diff --git a/documentation updates aleo ambassadors/src/build/leo/executing-programs.md b/documentation updates aleo ambassadors/src/build/leo/executing-programs.md deleted file mode 100644 index 1adb0d45b..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/executing-programs.md +++ /dev/null @@ -1 +0,0 @@ -# Executing Programs diff --git a/documentation updates aleo ambassadors/src/build/leo/helloleo.md b/documentation updates aleo ambassadors/src/build/leo/helloleo.md deleted file mode 100644 index f39483a26..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/helloleo.md +++ /dev/null @@ -1 +0,0 @@ -# HelloLeo diff --git a/documentation updates aleo ambassadors/src/build/leo/images/execute-output.png b/documentation updates aleo ambassadors/src/build/leo/images/execute-output.png deleted file mode 100644 index bc31e6d27..000000000 Binary files a/documentation updates aleo ambassadors/src/build/leo/images/execute-output.png and /dev/null differ diff --git a/documentation updates aleo ambassadors/src/build/leo/images/run-output.png b/documentation updates aleo ambassadors/src/build/leo/images/run-output.png deleted file mode 100644 index 742663edf..000000000 Binary files a/documentation updates aleo ambassadors/src/build/leo/images/run-output.png and /dev/null differ diff --git a/documentation updates aleo ambassadors/src/build/leo/installation.md b/documentation updates aleo ambassadors/src/build/leo/installation.md deleted file mode 100644 index 25267fe2b..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/installation.md +++ /dev/null @@ -1 +0,0 @@ -# Installation diff --git a/documentation updates aleo ambassadors/src/build/leo/language.md b/documentation updates aleo ambassadors/src/build/leo/language.md deleted file mode 100644 index 403a5489d..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/language.md +++ /dev/null @@ -1 +0,0 @@ -# Language diff --git a/documentation updates aleo ambassadors/src/build/leo/manage-your-program/README.md b/documentation updates aleo ambassadors/src/build/leo/manage-your-program/README.md deleted file mode 100644 index ed1516c01..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/manage-your-program/README.md +++ /dev/null @@ -1 +0,0 @@ -# Manage your Program diff --git a/documentation updates aleo ambassadors/src/build/leo/operators.md b/documentation updates aleo ambassadors/src/build/leo/operators.md deleted file mode 100644 index 0d12c6d61..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/operators.md +++ /dev/null @@ -1 +0,0 @@ -# Operators diff --git a/documentation updates aleo ambassadors/src/build/leo/overview.md b/documentation updates aleo ambassadors/src/build/leo/overview.md deleted file mode 100644 index 07dd0c5c7..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/overview.md +++ /dev/null @@ -1 +0,0 @@ -# Overview diff --git a/documentation updates aleo ambassadors/src/build/leo/resources/README.md b/documentation updates aleo ambassadors/src/build/leo/resources/README.md deleted file mode 100644 index 3c1229ee1..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/resources/README.md +++ /dev/null @@ -1 +0,0 @@ -# Resources diff --git a/documentation updates aleo ambassadors/src/build/leo/resources/developer-resources.md b/documentation updates aleo ambassadors/src/build/leo/resources/developer-resources.md deleted file mode 100644 index a67a44392..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/resources/developer-resources.md +++ /dev/null @@ -1 +0,0 @@ -# Developer Resources diff --git a/documentation updates aleo ambassadors/src/build/leo/resources/leo-playground.md b/documentation updates aleo ambassadors/src/build/leo/resources/leo-playground.md deleted file mode 100644 index 83325e6d4..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/resources/leo-playground.md +++ /dev/null @@ -1 +0,0 @@ -# Leo Playground diff --git a/documentation updates aleo ambassadors/src/build/leo/resources/leo-syntax-cheatsheet.md b/documentation updates aleo ambassadors/src/build/leo/resources/leo-syntax-cheatsheet.md deleted file mode 100644 index db21440dd..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/resources/leo-syntax-cheatsheet.md +++ /dev/null @@ -1 +0,0 @@ -# Leo Syntax Cheatsheet diff --git a/documentation updates aleo ambassadors/src/build/leo/resources/tooling.md b/documentation updates aleo ambassadors/src/build/leo/resources/tooling.md deleted file mode 100644 index a07e7c8bb..000000000 --- a/documentation updates aleo ambassadors/src/build/leo/resources/tooling.md +++ /dev/null @@ -1 +0,0 @@ -# Tooling diff --git a/documentation updates aleo ambassadors/src/build/overview.md b/documentation updates aleo ambassadors/src/build/overview.md deleted file mode 100644 index 07dd0c5c7..000000000 --- a/documentation updates aleo ambassadors/src/build/overview.md +++ /dev/null @@ -1 +0,0 @@ -# Overview diff --git a/documentation updates aleo ambassadors/src/build/snarkos-node-rpc/README.md b/documentation updates aleo ambassadors/src/build/snarkos-node-rpc/README.md deleted file mode 100644 index 3553f74fc..000000000 --- a/documentation updates aleo ambassadors/src/build/snarkos-node-rpc/README.md +++ /dev/null @@ -1 +0,0 @@ -# snarkOS Node RPC diff --git a/documentation updates aleo ambassadors/src/learn/README.md b/documentation updates aleo ambassadors/src/learn/README.md deleted file mode 100644 index 58e167b7b..000000000 --- a/documentation updates aleo ambassadors/src/learn/README.md +++ /dev/null @@ -1 +0,0 @@ -# LEARN diff --git a/documentation updates aleo ambassadors/src/learn/concepts/README.md b/documentation updates aleo ambassadors/src/learn/concepts/README.md deleted file mode 100644 index 74d42e13c..000000000 --- a/documentation updates aleo ambassadors/src/learn/concepts/README.md +++ /dev/null @@ -1 +0,0 @@ -# Concepts diff --git a/documentation updates aleo ambassadors/src/learn/concepts/accounts.md b/documentation updates aleo ambassadors/src/learn/concepts/accounts.md index 82ba51090..cbd2c7d2a 100644 --- a/documentation updates aleo ambassadors/src/learn/concepts/accounts.md +++ b/documentation updates aleo ambassadors/src/learn/concepts/accounts.md @@ -1,6 +1,4 @@ --- -Author: [Cedric](syyanyuhui@gmail.com) -LastUpdate: 2024-05-06 --- ## Address Types in Aleo diff --git a/documentation updates aleo ambassadors/src/learn/concepts/accounts_zh.md b/documentation updates aleo ambassadors/src/learn/concepts/accounts_zh.md deleted file mode 100644 index 9e6cd1c5f..000000000 --- a/documentation updates aleo ambassadors/src/learn/concepts/accounts_zh.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -Author: [Cedric](syyanyuhui@gmail.com) -LastUpdate: 2024-05-06 ---- - -## Aleo的地址类型 - -在Aleo中存在两种地址类型,分别是用户地址和程序地址。 - -用户地址有唯一对应的ViewKey和PrivateKey。在Aleo网络中,我们可以创建具有隐私保护的程序,用户与程序的交互对于其他所有人都是不可见的。这里的**用户地址隐私性**是由ViewKey提供的,也就是说,谁拥有用户地址对应的ViewKey谁就拥有该地址的所有的可见性。PrivateKey是**用户地址所有权**的证明,谁拥有用户地址对应的PrivateKey谁就拥有该地址下的所有资产。Address、ViewKey、PrivateKey是根据密码学设计出来的紧密相关的一组数学对象。PrivateKey可以推导出ViewKey,ViewKey则可以推导出Address,这个过程是单向的,我们没有办法从Address反向推出ViewKey,或者根据ViewKey反向推出PrivateKey。 - - - -程序的地址由ProgramID通过安全的哈希算法而来,与用户地址不同,程序地址没有对应的ViewKey或者PrivateKey。更准确的来说,实际上存在与程序地址唯一确定的ViewKey和PrivateKey,但任何人都没有办法从程序地址推导出对应的ViewKey和PrivateKey。因为程序地址不存在PrivateKey和ViewKey,程序地址的资产完全由程序中所定义的逻辑进行控制,这对于在Aleo网络中构建去中心的Dapp,保护用户存放在Dapp中的资产非常重要。 - - - -## 如何在Aleo上存储资产? - -以Aleo Credits为例,用户地址可以同时拥有Private Balance和Public Balance,这两者之间可以随意进行转换,并且都可以用来支付Aleo网络的Fee。 - -Private Balance是基于Record Model实现的(类似于比特币的UTXO模型),我们可以将它类比为纸币。 - -Public Balance类似于以太坊的Account模型,我们可以将其类比于银行卡余额。 - -Record Model是类似于比特币UTXO的模型,但功能更加强大,我们可以在Program中定义Record并存储在定义的数据,并且在链上以加密的形式存在,只有Record的所有者地址对应的ViewKey才查看Record的具体信息以及是否被消耗。 - -Record的产生完全取决于Program是如何定义的。 - -Record的消耗则需要满足三个条件: - -- Record确实存在并且尚未被消耗 -- Record消耗需要满足程序的定义规则(如Aleo Credits转账,需要消耗一个Record同时产生两个Record,两个新产生的Record的金额之和等于消耗的Record的金额) -- 需要Record的Owner进行签名授权,只有Record的Owner可以消耗Record。 - -[Learn more about Record Model](TODO: Add link to record model) - - - -Public Balance以Mapping的形式存储,是公开可见的,每个地址对应一个条目。 - - - -## 支付Aleo网络费用 - -在Aleo网络中,用户需要使用Aleo Credits为他们的交易支付Fee。当用户发送交易时,交易由两部分组成,一部分是交易真正的负载信息,只能是Execution(调用一个Program)或者 是Deployment(部署一个Program),另一部分是Fee Transaction。Fee Transaction是特定的一个Transaction类型,不会单独存在,其中有一个参数是ExecutionID或者是DeploymentID,这个参数保证了Fee Transaction是为特定的Execution或者Deployment承担费用的,由此将Execution 和 Fee绑定起来。 - -``` -Transaction -- Execution || Deployment -- Fee(execution_id, fee_amount) -``` - diff --git a/documentation updates aleo ambassadors/src/learn/concepts/blocks.md b/documentation updates aleo ambassadors/src/learn/concepts/blocks.md deleted file mode 100644 index 54e0a5ff9..000000000 --- a/documentation updates aleo ambassadors/src/learn/concepts/blocks.md +++ /dev/null @@ -1 +0,0 @@ -# Blocks diff --git a/documentation updates aleo ambassadors/src/learn/concepts/fee.md b/documentation updates aleo ambassadors/src/learn/concepts/fee.md deleted file mode 100644 index af609bd26..000000000 --- a/documentation updates aleo ambassadors/src/learn/concepts/fee.md +++ /dev/null @@ -1 +0,0 @@ -# Fee diff --git a/documentation updates aleo ambassadors/src/learn/concepts/programs/README.md b/documentation updates aleo ambassadors/src/learn/concepts/programs/README.md deleted file mode 100644 index 19a7859d9..000000000 --- a/documentation updates aleo ambassadors/src/learn/concepts/programs/README.md +++ /dev/null @@ -1 +0,0 @@ -# Programs diff --git a/documentation updates aleo ambassadors/src/learn/concepts/programs/deployment.md b/documentation updates aleo ambassadors/src/learn/concepts/programs/deployment.md deleted file mode 100644 index d36c65e59..000000000 --- a/documentation updates aleo ambassadors/src/learn/concepts/programs/deployment.md +++ /dev/null @@ -1 +0,0 @@ -# Deployment diff --git a/documentation updates aleo ambassadors/src/learn/concepts/programs/execution.md b/documentation updates aleo ambassadors/src/learn/concepts/programs/execution.md deleted file mode 100644 index a2e753b62..000000000 --- a/documentation updates aleo ambassadors/src/learn/concepts/programs/execution.md +++ /dev/null @@ -1 +0,0 @@ -# Execution diff --git a/documentation updates aleo ambassadors/src/learn/concepts/transactions.md b/documentation updates aleo ambassadors/src/learn/concepts/transactions.md deleted file mode 100644 index a5fd09c18..000000000 --- a/documentation updates aleo ambassadors/src/learn/concepts/transactions.md +++ /dev/null @@ -1 +0,0 @@ -# Transactions diff --git a/documentation updates aleo ambassadors/src/learn/concepts/transitions.md b/documentation updates aleo ambassadors/src/learn/concepts/transitions.md deleted file mode 100644 index bbe279abd..000000000 --- a/documentation updates aleo ambassadors/src/learn/concepts/transitions.md +++ /dev/null @@ -1 +0,0 @@ -# Transitions diff --git a/documentation updates aleo ambassadors/src/learn/network/README_zh.md b/documentation updates aleo ambassadors/src/learn/network/README_zh.md deleted file mode 100644 index 97fa4ba40..000000000 --- a/documentation updates aleo ambassadors/src/learn/network/README_zh.md +++ /dev/null @@ -1,20 +0,0 @@ -![aleo_network](images/aleo_network.jpg) - -在Aleo中存在着两个网络:一个是共识网络、一个是P2P网络。有三种节点类型:Validator、Prover、Client。 - -### Validator - -Validator会加入到两个网络中,一个是共识网络,通常监听5000端口,另一个是P2P网络,通常监听4130端口。Validator之间会通过5000端口互相连接,形成一个共识网络,Client和Prover不被允许连接共识网络。 - -Validator节点的主要职责,是按照AleoBFT的规则产生新的块。 - -在Aleo P2P Network中,除了Client 和 Prover之间会通过P2P互相连接之外,Client和Prover也会连接一定数量的Validator节点,以获取共识网络中最新块以及状态信息。 - -### Client - -Client节点的主要职责,是同步来自共识网络产生的块并更新账本信息。用户可以通过Client的RPC来访问当前Aleo网络的最新状态信息,也可以通过RPC来将Transaction广播到网络中。当共识网络产生的新的块包含Transaction,则意味着Transaction被成功的执行了。 - -### Prover - -Prover节点的主要职责,是同步来自共识网络产生的CoinbasePuzzle,并运行CoinbasePuzzle的算法得到满足要求的Solution,然后通过P2P网络广播给共识网络,当共识网络产生的新的块中包含这个Solution,Solution对应的Prover会获得相应的CoinbaseReward奖励。 - diff --git a/documentation updates aleo ambassadors/src/learn/network/provers_zh.md b/documentation updates aleo ambassadors/src/learn/network/provers_zh.md deleted file mode 100644 index 0e8b5565a..000000000 --- a/documentation updates aleo ambassadors/src/learn/network/provers_zh.md +++ /dev/null @@ -1,40 +0,0 @@ -# Provers - - - -### Prover在网络中扮演的角色 - -Prover是Aleo网络中的一个重要组成部分,它不参与到Aleo的网络共识中。Prover运行特定的算法,通过求解*CoinbasePuzzle*得到满足*ProofTarget*的*ProverSolution*,然后广播,当*ProverSolution*被验证者节点确认并被打包到区块中时,Prover可以获得相应的*CoinbaseReward*奖励。 - - - -### Prover的经济激励 - -从长期的角度来看,Prover能够获得的*CoinbaseReward*的奖励与它的算力在整个网络中的占比成正比。Prover的经济激励与Bitcoin中的PoW相类似,不同点在于Aleo网络中并不是赢家通吃的策略,*ProverSolution*只要满足*ProofTarget*就可以被网络接受,这样的方式使得Prover获得的奖励更加公平和稳定。值得注意的是,与Validator的*BlockReward*不同,*CoinbaseReward*会随着时间而递减,每年的产出会缩减10%,直到10年后,将不再有*CoinbaseReward*奖励。 - -用户可以通过[浏览器](https://testnet3.aleoscan.io)来查看CoinbaseReward、BlockReward、以及PuzzleReward。 - -> PuzzleReward = CoinbaseReward * 2 / 3 -> -> BlockReward = 23.8 + CoinbaseReward * 1 / 3 -> -> 其中: -> -> BlockReward的奖励由Validator根据质押占比进行分配 -> -> PuzzleReward的奖励由Prover提交的Solution的ProofTarget的占比进行分配 - - - -### CoinbasePuzzle - -Aleo网络中每360个区块组成一个Epoch,当新的Epoch产生时,CoinbasePuzzle也会发生相应的变化,如果Prover依然在计算旧的CoinbasePuzzle,则其计算出的ProverSolution不会再被网络接收。这意味着Prover需要监听共识网络的区块变化,当新的Epoch产生时,更新当前的CoinbasePuzzle信息。 - -除了要求ProverSolution是合法的之外,网络还要求ProverSolution满足大于等于ProofTarget。ProofTarget是用来衡量Prover的工作量的,类似于PoW,ProofTarget越大,Prover所需要进行的计算的工作就越大。Aleo网络会根据当前参与到网络中Prover的算力来调整ProofTarget,当参与到网络中的算力增加时,网络会增大ProofTarget来保证网络中不会出现过多的ProverSolution,防止网络拥堵和大量的ProverSolution没有办法呗打包的情况。 - - - -### 如何成为Prover节点 - -成为Prover节点不需要质押和授权,任何人都可以启动一个Prover节点。 - diff --git a/documentation updates aleo ambassadors/src/learn/network/validators_zh.md b/documentation updates aleo ambassadors/src/learn/network/validators_zh.md deleted file mode 100644 index 6fdd33dc6..000000000 --- a/documentation updates aleo ambassadors/src/learn/network/validators_zh.md +++ /dev/null @@ -1,45 +0,0 @@ -# Validators - -1.验证者节点在网络中的角色以及作用 - -Aleo Validators之间组成一个共识网络,并通过AleoBFT共识协议来决定区块的生成。Validator通过质押Aleo Credits来获得投票权(节点的投票权与质押的Aleo Credits的数量成正比),AleoBFT保证了:当一个新的区块被生成时,这个区块至少获得了超过2/3的投票,这意味着网络中诚实的Validators已经对这个区块达成一致意见,这有效保证了网络的安全,阻止了恶意节点的攻击。区块一旦形成,便认为是达到了最终确定性,区块以及包含的交易将不会被回滚。 - - - - - -2.验证者节点的经济激励 - -AleoBFT的机制保证了如果一个恶意的节点想要攻击网络,则至少需要获得超过1/3的投票权才能阻止新的区块的产生。这意味着,当网络中中质押的Aleo Credits越多时,共识网络会越安全。为了激励验证者节点质押自己的Aleo Credits,当每个区块被产生时,区块中会包含给验证者节点相应的BlockReward奖励。Validator节点获得BlockReward的奖励占比与它质押的Aleo Credits的占比相等。(TODO: Add Link) - - - -3.如何成为验证者节点? - -在Aleo主网上线时,将会拥有10个初始的Validator节点,随后用户可以通过质押至少10,000,000(一百万)的Aleo Credits。当质押的交易请求被共识网络接受之后,新的验证者节点可以立马参与到共识中,并获得BlockReward奖励,这得益于AleoBFT对Narwhal Bullshark所进行的改进。 - -由于网络中的验证者节点在运行的过程中,会通过相互的通信来获得彼此的状态信息,这意味着网络中的验证者节点越多,需要的网络通信的数量级就越大,通信复杂度为O(n)。通信复杂度的上升会导致区块产生的时间延长,在Aleo网络中限制了验证者节点的最大数量为200,以此来平衡去中心化与网络效率。 - -当我们只有少量的Aleo Credits时,虽然我们不能成为独立的验证者节点,但是我们可以通过委托质押的方式来获得BlockReward奖励。 - - - -4.什么是委托质押? - -委托质押是指用户可以通过Program(Aleo的智能合约)将Aleo Credits质押在某个Validator节点上,质押的AleoCredits所得到的投票权也会委托给相应的Validator节点。用户可以获得线性比例的BlockReward奖励,Validator可以通过Program的设置收取一定比例的Fee。XXX(TODO:ADD Link)钱包、浏览器为用户提供了委托质押的功能,用户可以在他们提供的UI界面上看到各个Validator的Fee比例,方便地完成质押。 - -用户也可以随时取消质押,取消质押后的360个区块之后,用户可以将取消质押返还的Aleo Credits提取到余额中。 - - - -5.Transaction和Solution被验证者节点确认的过程 - -![image-20240422165659999](./images/validator-process-transaction.png) - -- Transaction/Solution通过P2P网络或者RPC进入到验证者节点的的消息池 -- 验证者节点将从消息池中选出一些Transactions/Solutions放入到BatchPropose(除了Transactions和Solutions,BatchPropose需要包含前一个轮次的2f + 1个BatchCertificate),并广播给其他的验证者节点。 -- 其他的验证者节点在收到BatchPropose并确保它的合法性之后,会对该BatchPropose进行签名得到BatchSignature,并将BatchSignature返回给该验证者节点。 -- 当验证者节点收到超过2f + 1的BatchSignature之后,将其聚合成为一个BatchCertificate,并广播给其他的验证者节点。 -- 所有的节点都会执行并重复这个过程,产生的BatchCertificate构成一个DAG。当DAG被Commit后,新的区块产生,Transaction和Solution都会被包含在新的区块中。 - -![Illustration_DAG](./images/Illustration_DAG.png) diff --git a/documentation updates aleo ambassadors/src/overview.md b/documentation updates aleo ambassadors/src/overview.md deleted file mode 100644 index 07dd0c5c7..000000000 --- a/documentation updates aleo ambassadors/src/overview.md +++ /dev/null @@ -1 +0,0 @@ -# Overview diff --git a/documentation/00_overview.md b/documentation/00_overview.md index 54775cb37..fcae9a79d 100644 --- a/documentation/00_overview.md +++ b/documentation/00_overview.md @@ -54,6 +54,7 @@ An index of all pages available in this documentation. - [Transaction Fees](./concepts/03A_transaction_fees.md) - [Transitions](./concepts/04_transitions.md) - [Blocks](./concepts/05_blocks.md) +- [Public vs. Private State](./concepts/06_public_private.md) ## Testnet III @@ -91,7 +92,18 @@ An index of all pages available in this documentation. ## Advanced Topics -### Chapter 7: The Aleo Curves +### Chapter 7: Dive into the AVM + +- [Overview](./advanced/dive-into-avm/00_overview.md) +- [Aleo Account Keys](./advanced/dive-into-avm/01_aleo_account_keys.md) +- [Circuits and R1CS](./advanced/dive-into-avm/02_r1cs.md) +- [Inclusion Proofs](./advanced/dive-into-avm/03_inclusion_proof.md) + +### Chapter 8: Introduction to zk-SNARKs + +- [Overview](./advanced/intro-to-zksnark/00_overview.md) + +### Chapter 9: The Aleo Curves - [Overview](./advanced/the_aleo_curves/00_overview.md) - [Edwards BLS12](./advanced/the_aleo_curves/01_edwards_bls12.md) diff --git a/documentation updates aleo ambassadors/src/advanced/dive-into-avm/README.md b/documentation/advanced/dive-into-avm/00_overview.md similarity index 99% rename from documentation updates aleo ambassadors/src/advanced/dive-into-avm/README.md rename to documentation/advanced/dive-into-avm/00_overview.md index c13073271..db26d96f0 100644 --- a/documentation updates aleo ambassadors/src/advanced/dive-into-avm/README.md +++ b/documentation/advanced/dive-into-avm/00_overview.md @@ -1,4 +1,8 @@ -# Aleo’s Virtual Machine (AVM) +--- +id: overview +title: Overview +sidebar_label: Overview +--- The Aleo Virtual Machine (AVM) is a computational platform integral to the Aleo blockchain, designed to run privacy-focused applications. It operates as a stack machine that executes queued instructions. Its primary function is to construct arithmetic circuits described as Rank-1 Constraint System (R1CS), from each instruction in a function. diff --git a/documentation updates aleo ambassadors/src/advanced/dive-into-avm/aleo-account-keys.md b/documentation/advanced/dive-into-avm/01_aleo_account_keys.md similarity index 96% rename from documentation updates aleo ambassadors/src/advanced/dive-into-avm/aleo-account-keys.md rename to documentation/advanced/dive-into-avm/01_aleo_account_keys.md index f618d90b9..d85041a9a 100644 --- a/documentation updates aleo ambassadors/src/advanced/dive-into-avm/aleo-account-keys.md +++ b/documentation/advanced/dive-into-avm/01_aleo_account_keys.md @@ -1,4 +1,8 @@ -# Aleo Account Key Generation +--- +id: aleo_account_keys +title: Aleo Account Keys +sidebar_label: Aleo Account Keys +--- An Aleo account is similar to accounts on other blockchain platforms but designed with a focus on privacy, leveraging cryptographic techniques unique to the platform. Here's a detailed breakdown of the components of an Aleo account and the processes involved in generating addresses, public keys, and private keys: diff --git a/documentation updates aleo ambassadors/src/advanced/dive-into-avm/circuits-r1cs.md b/documentation/advanced/dive-into-avm/02_r1cs.md similarity index 97% rename from documentation updates aleo ambassadors/src/advanced/dive-into-avm/circuits-r1cs.md rename to documentation/advanced/dive-into-avm/02_r1cs.md index e340930e8..2b28eba8c 100644 --- a/documentation updates aleo ambassadors/src/advanced/dive-into-avm/circuits-r1cs.md +++ b/documentation/advanced/dive-into-avm/02_r1cs.md @@ -1,4 +1,8 @@ -# R1CS Circuits +--- +id: r1cs +title: R1CS +sidebar_label: R1CS +--- Aleo Virtual Machine leverages a type of intermediate representation for their circuits called “Rank-1 Constrained System” (R1CS). This format is used to express computations as a system of equations that can later be formally verified. diff --git a/documentation updates aleo ambassadors/src/advanced/inclusion-proof..md b/documentation/advanced/dive-into-avm/03_inclusion_proof.md similarity index 95% rename from documentation updates aleo ambassadors/src/advanced/inclusion-proof..md rename to documentation/advanced/dive-into-avm/03_inclusion_proof.md index 4aed30d41..6024881ac 100644 --- a/documentation updates aleo ambassadors/src/advanced/inclusion-proof..md +++ b/documentation/advanced/dive-into-avm/03_inclusion_proof.md @@ -1,4 +1,8 @@ -# Inclusion Proofs +--- +id: inclusion_proof +title: Inclusion Proofs +sidebar_label: Inclusion Proofs +--- Inclusion proofs are like a special handshake or password that gets you past verifier without revealing the actual element. In Aleo, inclusion proofs are like digital receipts that verify transactions without compromising users' privacy. @@ -12,4 +16,4 @@ In addition to producing these proofs, a user also produces 𝑛+1 “inclusion An inclusion proof also publicly outputs the serial numbers (also called a nullifier in ZCash-like systems) that uniquely identify the records without leaking any information about them. This way, records cannot be consumed more than once. (In addition, the network enforces that no serial number is seen twice within the same transaction.) -**Note:** All of these different proofs are eventually aggregated together into a single proof using Varuna’s batching capabilities. \ No newline at end of file +**Note:** All of these different proofs are eventually aggregated together into a single proof using Varuna’s batching capabilities. diff --git a/documentation updates aleo ambassadors/src/advanced/dive-into-avm/images/aleo_key_generation.png b/documentation/advanced/dive-into-avm/images/aleo_key_generation.png similarity index 100% rename from documentation updates aleo ambassadors/src/advanced/dive-into-avm/images/aleo_key_generation.png rename to documentation/advanced/dive-into-avm/images/aleo_key_generation.png diff --git a/documentation updates aleo ambassadors/src/advanced/dive-into-avm/images/avm_execution_flow_overview.png b/documentation/advanced/dive-into-avm/images/avm_execution_flow_overview.png similarity index 100% rename from documentation updates aleo ambassadors/src/advanced/dive-into-avm/images/avm_execution_flow_overview.png rename to documentation/advanced/dive-into-avm/images/avm_execution_flow_overview.png diff --git a/documentation updates aleo ambassadors/src/advanced/dive-into-avm/images/avs_global_state.png b/documentation/advanced/dive-into-avm/images/avs_global_state.png similarity index 100% rename from documentation updates aleo ambassadors/src/advanced/dive-into-avm/images/avs_global_state.png rename to documentation/advanced/dive-into-avm/images/avs_global_state.png diff --git a/documentation updates aleo ambassadors/src/advanced/intro-to-zksnark/general-intuition.md b/documentation/advanced/intro-to-zksnark/00_overview.md similarity index 95% rename from documentation updates aleo ambassadors/src/advanced/intro-to-zksnark/general-intuition.md rename to documentation/advanced/intro-to-zksnark/00_overview.md index c95cb0608..4871a3d0a 100644 --- a/documentation updates aleo ambassadors/src/advanced/intro-to-zksnark/general-intuition.md +++ b/documentation/advanced/intro-to-zksnark/00_overview.md @@ -1,14 +1,9 @@ -# Advanced - +--- +id: overview +title: Overview +sidebar_label: Overview +--- + In this section we cover the general intuition of a zk proof, we outline the steps in creating a zksnark, we define the actors in a zk proof mainly the prover and verifier. We also introduce the elements in a zkproof like the witness, intermediate representation, trusted setups, structured reference strings and random oracles. We also give the context of where the zksnark proof is used in Aleo. ## Introduction diff --git a/documentation/concepts/02_records.md b/documentation/concepts/02_records.md index 964968176..b26df8961 100644 --- a/documentation/concepts/02_records.md +++ b/documentation/concepts/02_records.md @@ -4,54 +4,165 @@ title: Records sidebar_label: Records --- + A **record** is a fundamental data structure for encoding user assets and application state. -Each account record contains information that specifies the record owner, its stored value, and its application state. -Records in Aleo are consumed and newly created from a [transition](04_transitions.md) function. A [transaction](03_transactions.md) will store multiple transitions, each of which is responsible for the consumption and creation of its individual records. -Optionally, if the `visibility` of the record is `private`, it can be encrypted using the owner's address secret key. +Each account record contains information that specifies the record owner, its stored value, and its application state. +Records in Aleo are consumed and newly created from a [transition](04_transitions.md) function. A [transaction](03_transactions.md) will store multiple transitions, each of which is responsible for the consumption and creation of its individual records. +Optionally, if the `visibility` of an entry in the record is `private`, it is be encrypted using the owner's address secret key. ## Components of a Record An Aleo record is serialized in the following format: -| Parameter | Type | Description | -|:--------------:|:----------------------:|:---------------------------------------------------------------------:| -| `apk` | address | The address public key of the owner of the program record | -| `data` | Map | A data payload containing arbitrary application-dependent information | -| `nonce` | group | The serial number nonce of the program record | -| `visibility` | enum | The record's visibility, which can either be `public` or `private` | -### Owner - -``` -aleo1r0dry2tlhjt0yplctz85692kjpqsadn7xgxsmrehkasykjxynypqza3fpl +| Parameter | Type | Description | +|:---------:|:----------------------:|:----------------------------------------------------------------------------------------------------------------------:| +| `owner` | address | The address public key of the owner of the program record | +| `data` | Map | A data payload containing arbitrary application-dependent information. Each entry can either be `public` or `private`. | +| `nonce` | group | The serial number nonce of the program record | +An example record: +```bash +{ + owner: aleo13ssze66adjjkt795z9u5wpq8h6kn0y2657726h4h3e3wfnez4vqsm3008q.private, + amount: 100u64.private, + _nonce: 5861592911433819692697358191094794940442348980903696700646555355124091569429group.public +} ``` -The **record owner** is an [account address](00_accounts.md#account-address), -and specifies the party who is authorized to spend the record. -### Gates +### Owner +`aleo13ssze66adjjkt795z9u5wpq8h6kn0y2657726h4h3e3wfnez4vqsm3008q` -``` -4130 -``` +The record owner is an account address, and specifies the party who is authorized to spend the record. -### Data -``` -[ RECORD BYTE MAP ] -``` +### Data +`100u64.private` -The **record data** encodes arbitrary application information. +The record can encode arbitrary application information. The "amount" key is the data payload that the record carries. +An entry which has a `visibility` of `private` is encrypted and stored on the ledger. +This enables users to securely and privately transfer record data and values between one another over the public network. +Only the sender and receiver with their corresponding account view keys are able to decrypt the private entries. ### Nonce +`5861592911433819692697358191094794940442348980903696700646555355124091569429group` + +The serial number nonce is used to create a unique identifier for each record, and is computed via a PRF evaluation of the address secret key ask of the owner and the record's serial number. +For a practical demonstration of a record in Aleo, see [here](https://youtu.be/JIgrKv_Q6Jo?feature=shared). + + +## Diving into the Concepts +To understand how to use records, we must understand the design principles behind Aleo. +Autonomous Ledger Execution Offchain (Aleo) is a layer-1 blockchain that combines general-purpose programmability with privacy by default. +The core idea behind Aleo is ZEXE or zero-knowledge execution initially written in this [research paper](https://eprint.iacr.org/2018/962.pdf) in 2018. It first introduced the record model which extends the UTXO model from Zcash and enables storing and encrypting arbitrary data (user assets and application states), rather than just values of specific assets or tokens. + +### Privacy +There are generally four different types of privacy that relate to blockchains. + +Aleo fulfils the 3 of them: +- [x] Private inputs (messages) +- [x] Private outputs (state changes) +- [x] Private user +- [ ] Private function + +Initially, Aleo was aiming for function privacy as well (as detailed in the original ZEXE paper) but decided against it as it would have led to worse performance and longer proving times. + + +### Comparing state storage in blockchains +There are two main state models used in blockchains - UTXO (unspent transaction output) and the account model (introduced by Ethereum). + +Aleo uses a variation of the UTXO model - the record model. + +

+Account vs UTXO +

+ +

+Source: galaxy.com +

+

+ +### Account Model +In the account model as used in Ethereum, the application state can be found by referencing to a particular address. + +As such, anyone would be able to view the activities of any account, simply with the knowledge of the address. + +

+Ethereum Storage Diagram +

+ +

+Source: ethereum.org +

+

+ + +

+Ethereum World State Diagram +

+ +

+Source: Article by Lucas Saldanha +

+ +

+ + + +### Record Model +In the record model, the application state, along with its owner are encrypted and stored on the blockchain. + +

+Aleo Records Diagram +

+ +

+Source: Zexe: Enabling Decentralized Private Computation +

+ +

+ + +

+Aleo World State Diagram +

+ + +

+Source: Zexe: Enabling Decentralized Private Computation +

+

+ + + +### Updating State +In the record model, applications update their state by consuming records containing the old state, and producing new records that contain the updated state. Records that have been used will be marked as spent and cannot be used again. + +

+UTXO diagram +

+ +

+Source: adapulse.io +

+

+ +The consumption and production of records is typically done in a transition function. A transaction in Aleo can contain up to 32 transitions, one of which is reserved for the transaction fee. + + +

+Transaction in Aleo +

+ +### Why is the Record Model Useful? + +In the account-based model, an application's data is stored in a persistent location tied to the application's account, and updates are made directly to this stored data. For a typical token transfer transaction using this model, user balances would be stored in a table mapping user account addresses to their respective balances. When User A transfers money to User B, A's balance in the table is reduced, and B's balance is increased by the same amount. +If we were to try making the transactions private (hiding the amount transferred and the identities of A and B), instead of storing actual balances, the application can store commitments to these balances. Transactions would then update these commitments rather than the actual balances. However, while this approach hides transaction values, it does not hide user identities. To also hide user identities, every transaction would need to update all commitments in the table, which becomes increasingly inefficient as the number of users grows. +Although the account model is more intuitive for developers, it uses account addresses to index global state. This means that while a private account model can achieve privacy for inputs and outputs, it still compromises user privacy since account addresses cannot be encrypted. Another issue with the private account model is the lack of concurrency, as only one user can access and update the entire program state at a time. +Aleo's record model uses program IDs to uniquely identify programs instead of account addresses. This improves privacy and enables programs to have internal states. This approach is more efficient and solves the concurrency issue. + + + + -``` -3024738992072387217402876176731225730589877991873828351104009809002984426287group -``` -The **serial number nonce** is used to create a unique identifier for each record, -and is computed via a `PRF` evaluation of the address secret key `ask` of the `owner` and the record's serial number. -### (Optional) Record Encryption -A record which has a `visibility` of `private` is verifiably encrypted in the transition and stored on the ledger. -This enables users to securely and privately transfer record data and values between one another over the public network. -Only the sender and receiver with their corresponding account view keys are able to decrypt these records. diff --git a/documentation updates aleo ambassadors/src/blog/public_vs_private_state.md b/documentation/concepts/06_public_private.md similarity index 98% rename from documentation updates aleo ambassadors/src/blog/public_vs_private_state.md rename to documentation/concepts/06_public_private.md index a1752293b..4df930d20 100644 --- a/documentation updates aleo ambassadors/src/blog/public_vs_private_state.md +++ b/documentation/concepts/06_public_private.md @@ -1,6 +1,8 @@ -# Public vs. Private State - -![aleo logo](./images/aleo.jpeg) +--- +id: public_private +title: Public vs. Private State +sidebar_label: Public vs. Private State +--- ## Introduction The concept of Zero Knowledge proofs was first introduced in 1985 in the paper [The Knowledge Complexity of Interactive Proof Systems](https://epubs.siam.org/doi/10.1137/0218012?utm_source=the+new+stack&utm_medium=referral&utm_content=inline-mention&utm_campaign=tns+platform). However, it is only in recent years that the groundbreaking technology has been feasible to be applicable to blockchains. diff --git a/documentation/concepts/06_glossary.md b/documentation/concepts/07_glossary.md similarity index 100% rename from documentation/concepts/06_glossary.md rename to documentation/concepts/07_glossary.md diff --git a/documentation updates aleo ambassadors/src/blog/images/account_vs_utxo.png b/documentation/concepts/images/account_vs_utxo.png similarity index 100% rename from documentation updates aleo ambassadors/src/blog/images/account_vs_utxo.png rename to documentation/concepts/images/account_vs_utxo.png diff --git a/documentation updates aleo ambassadors/src/blog/images/aleo.jpeg b/documentation/concepts/images/aleo.jpeg similarity index 100% rename from documentation updates aleo ambassadors/src/blog/images/aleo.jpeg rename to documentation/concepts/images/aleo.jpeg diff --git a/documentation updates aleo ambassadors/src/blog/images/aleo_ledger.png b/documentation/concepts/images/aleo_ledger.png similarity index 100% rename from documentation updates aleo ambassadors/src/blog/images/aleo_ledger.png rename to documentation/concepts/images/aleo_ledger.png diff --git a/documentation updates aleo ambassadors/src/blog/images/ethereum_storage.png b/documentation/concepts/images/ethereum_storage.png similarity index 100% rename from documentation updates aleo ambassadors/src/blog/images/ethereum_storage.png rename to documentation/concepts/images/ethereum_storage.png diff --git a/documentation updates aleo ambassadors/src/blog/images/ethereum_world_state.png b/documentation/concepts/images/ethereum_world_state.png similarity index 100% rename from documentation updates aleo ambassadors/src/blog/images/ethereum_world_state.png rename to documentation/concepts/images/ethereum_world_state.png diff --git a/documentation updates aleo ambassadors/src/blog/images/record.png b/documentation/concepts/images/record.png similarity index 100% rename from documentation updates aleo ambassadors/src/blog/images/record.png rename to documentation/concepts/images/record.png diff --git a/documentation updates aleo ambassadors/src/blog/images/transaction_in_aleo.png b/documentation/concepts/images/transaction_in_aleo.png similarity index 100% rename from documentation updates aleo ambassadors/src/blog/images/transaction_in_aleo.png rename to documentation/concepts/images/transaction_in_aleo.png diff --git a/documentation updates aleo ambassadors/src/blog/images/utxo.png b/documentation/concepts/images/utxo.png similarity index 100% rename from documentation updates aleo ambassadors/src/blog/images/utxo.png rename to documentation/concepts/images/utxo.png diff --git a/documentation/leo/03_language.md b/documentation/leo/03_language.md index 04c614177..a9458a967 100644 --- a/documentation/leo/03_language.md +++ b/documentation/leo/03_language.md @@ -363,6 +363,7 @@ Transition functions in Leo are declared as `transition {name}() {}`. Transition functions can be called directly when running a Leo program (via `leo run`). Transition functions contain expressions and statements that can compute values. Transition functions must be in a program's current scope to be called. +Transition functions that call [async functions](#async-function) to execute code on-chain must be declared as `async transition`. ```leo showLineNumbers program hello.aleo { @@ -447,6 +448,7 @@ The rules for functions (in the traditional sense) are as follows: ### Async Function An async function is declared as `async function` and is used to define computation run on-chain. +A call to an async function returns a [`Future`](#future) object. It is asynchronous because the code gets executed at a later point in time. One of its primary uses is to initiate or change public on chain state within mappings. An async function can only be called by an async [transition function](#transition-function) and is executed on chain, after the zero-knowledge proof of the execution of the associated transition is verified. diff --git a/documentation/leo/17_testnet_beta.md b/documentation/leo/17_testnet_beta.md index a81eb9679..ee700abd5 100644 --- a/documentation/leo/17_testnet_beta.md +++ b/documentation/leo/17_testnet_beta.md @@ -12,7 +12,7 @@ We are about to reach a huge milestone in Aleo's developement. Testnet Beta is a **IMPORTANT:** - **Leo v1.12.0 will be the last Testnet3 compatible version.** -- **Leo v.2.0.0 (to be released) will be the first Testnet Beta compatible version.** (In the meantime, you can build from source on the `testnet-beta` branch of the Leo repository.) +- **Leo v.2.0.0 is the first Testnet Beta compatible version.** (In the meantime, you can build from source on the `testnet-beta` branch of the Leo repository.) For additional support, please feel free to: - File an issue [here](https://github.com/AleoHQ/leo/issues/new/choose). diff --git a/documentation/sdk/create-aleo-app/00_app_installation.md b/documentation/sdk/create-aleo-app/00_app_installation.md index b72627c6d..c64255c35 100644 --- a/documentation/sdk/create-aleo-app/00_app_installation.md +++ b/documentation/sdk/create-aleo-app/00_app_installation.md @@ -19,14 +19,17 @@ With NPM: npm create aleo-app@latest ``` -Then follow the prompts! +1. Enter the project name. +2. This will prompt you to choose a preferred framework from the following options: + - `React` + - `Node.js` + - `Vanilla (JavaScript)` -Currently supported template presets include: -- `react` + `javascript` -- `react` + `javascript` + `leo` -- `node` + `javascript` -- `vanilla (javascript)` +3. If you choose `React` as your framework, the supported templates are: + - `JavaScript` + `Leo` + - `TypeScript` + `Leo` + - `TypeScript` + `Next.js` ## More Information -Based off of create-vite: https://github.com/vitejs/vite/tree/main/packages/create-vite +Based on create-vite: https://github.com/vitejs/vite/tree/main/packages/create-vite diff --git a/documentation/sdk/typescript/00_sdk_overview.md b/documentation/sdk/typescript/00_sdk_overview.md index 9a2cb296d..7bc008122 100644 --- a/documentation/sdk/typescript/00_sdk_overview.md +++ b/documentation/sdk/typescript/00_sdk_overview.md @@ -33,7 +33,7 @@ The Aleo SDK provides the following functionality (Click to see examples): * [Usage](#Usage) * [Zero Knowledge Web App Examples](#Zero-Knowledge-Web-App-Examples) * [Create Aleo App](#create-aleo-app) - * [Aleo.tools](#aleotools) + * [provable.tools](#provabletools) * [Create An Aleo Account](#1-create-an-aleo-account) * [Execute Aleo Programs](#2-execute-aleo-programs) * [Aleo Programs](#21-aleo-programs) @@ -83,7 +83,7 @@ templates in common web frameworks such as React that can be used as a starting Developers can get started immediately with create-react-app by running: `npm create aleo-app@latest` -### Aleo.tools +### Provable Tools Additionally, the SDK powers [provable.tools](https://provable.tools) - a React app that provides a graphical interface for most of the functionality provided by the SDK and can be used as a reference for usage of the SDK. Source code for provable.tools @@ -200,7 +200,7 @@ graph LR ### 2.3 WebAssembly Initialization -❗WebAssembly must be initialized before any SDK functions can be called. +❗WebAssembly must be initialized before calling any SDK functions. The current Aleo SDK manages the wasm initialization. Therefore, the workers must be defined properly. Aleo programs are made zero knowledge through the usage of `ZkSnarks`. The Rust code behind Aleo programs and the ZkSnarks that make them zero knowledge are hosted in the [snarkVM Repository](https://github.com/AleoHQ/SnarkVM). The Aleo SDK @@ -217,9 +217,9 @@ await initializeWasm(); /// Create a new Aleo account const account = new Account(); -```` +``` -An example of how to initialize WebAssembly in a React app is shown in [Section 2.7](#27-React-Example) +An example of how to initialize WebAssembly in a React app is shown in [Section 2.8](#28-React-Example) ### 2.4 Local Program Execution A simple example of running the hello world program within the web browser is shown below: @@ -247,7 +247,7 @@ network that anyone can trustlessly verify. This process can be thought of being executed in three steps: 1. A program is run locally 2. A proof that the program was executed correctly and that the outputs follow from the inputs is generated -3. A transcript of the proof is generated client-side containing encrypted proof data (see [Section 2.6](#4-managing-records-and-private-state)) +3. A transcript of the proof is generated client-side containing encrypted proof data (see [Section 4](#4-managing-program-data-and-private-state)) and any public outputs or state the user of the program wishes to reveal 4. The proof transcript is posted to the Aleo network and verified by the Aleo validator nodes in a trustless manner 5. If the proof is valid, it is stored and anyone can later verify the proof and read the outputs the author of the @@ -265,6 +265,10 @@ import { Account, AleoNetworkClient, NetworkRecordProvider, ProgramManager, KeyS const keyProvider = new AleoKeyProvider(); keyProvider.useCache = true; +// Define an account which will execute the transaction on-chain +const account = new Account({ privateKey: private_key }); +const privateKeyObject = PrivateKey.from_string(private_key); + // Create a record provider that will be used to find records and transaction data for Aleo programs const networkClient = new AleoNetworkClient("https://api.explorer.aleo.org/v1"); const recordProvider = new NetworkRecordProvider(account, networkClient); @@ -272,11 +276,29 @@ const recordProvider = new NetworkRecordProvider(account, networkClient); // Initialize a program manager to talk to the Aleo network with the configured key and record providers const programName = "hello_hello.aleo"; const programManager = new ProgramManager("https://api.explorer.aleo.org/v1", keyProvider, recordProvider); +programManager.setHost("https://api.explorer.aleo.org/v1") +programManager.setAccount(account); -// Provide a key search parameter to find the correct key for the program if they are stored in a memory cache -const keySearchParams = { "cacheKey": "hello_hello:hello" }; -const tx_id = await programManager.execute(programName, "hello_hello", 0.020, ["5u32", "5u32"], undefined, undefined, undefined, keySearchParams); -const transaction = await programManager.networkClient.getTransaction(tx_id); +// For example: "cacheKey": "hello_hello:hello" +const cacheKey = `${programId}:${aleoFunction}`; +const keySearchParams = new AleoKeyProviderParams({ "cacheKey": cacheKey }); + +// Execute the program function +const executionResponse = await programManager.execute( + programId, + aleoFunction, + fee, + false, + inputs, + undefined, + keyParams, + undefined, + undefined, + undefined, + privateKeyObject + ); + +const transaction = await programManager.networkClient.getTransaction(executionResponse); ``` A reader of the above example may notice the `RecordProvider` and `KeyProvider` classes that were not present in the local @@ -360,8 +382,7 @@ step by running: #### Wasm Initialization -Before functionality from the SDK can be used, the WASM module must be initialized within the browser. A common way of -achieving this within a React App is using a React UseEffect hook. +The WASM module can be initialized within the browser. A common way of achieving this within a React App is using a React UseEffect hook. `aleo-wasm-hook.js` ```jsx @@ -379,7 +400,7 @@ export const useAleoWASM = () => { }, []); // eslint-disable-line react-hooks/exhaustive-deps return aleoInstance; }; -```` +``` Once a hook for the WASM initialization is created, it can be used anywhere within the app. #### Program Execution @@ -387,240 +408,170 @@ Once a hook for the WASM initialization is created, it can be used anywhere with Program execution is a computationally expensive process. For this reason, it is recommended to execute programs in webworkers. +We will have 2 main components for workers: +- worker.js +- AleoWorker.js (Manager for worker file) +
Example Web Worker Usage A worker file that performs the execution can be created as follows: `worker.js` ```jsx -import * as aleo from "@aleohq/sdk"; - -// Web Workers contain their own WASM instance, so we initialize it separately from the main thread -await aleo.initializeWasm(); - -// Eight threads are then initialized to execute the program in parallel using multithreading -await aleo.initThreadPool(8); - -/// The program manager is initialized with a key provider and a record provider -const defaultHost = "https://api.explorer.aleo.org/v1"; -const keyProvider = new aleo.AleoKeyProvider(); -const recordProvider = new aleo.NetworkRecordProvider(new Account(), "https://api.explorer.aleo.org/v1"); -const programManager = new aleo.ProgramManager( - defaultHost, - keyProvider, - recordProvider, -); - -// The key provider is set to use an in-memory cache to store keys -keyProvider.useCache(true); - -self.postMessage({ - type: "ALEO_WORKER_READY", -}); - -// The program is executed when specific events are dispatched and then communicates the result to the main thread -// when execution has finished -let lastLocalProgram = null; -self.addEventListener("message", (ev) => { - if (ev.data.type === "ALEO_EXECUTE_PROGRAM_LOCAL") { - const {localProgram, aleoFunction, inputs, privateKey} = ev.data; - - console.log("Web worker: Executing function locally..."); - let startTime = performance.now(); - - (async function () { - try { - // Ensure the program is valid and that it contains the function specified - const program = programManager.createProgramFromSource(localProgram); - const program_id = program.id(); - if (!program.hasFunction(aleoFunction)) { - throw `Program ${program_id} does not contain function ${aleoFunction}`; - } - const cacheKey = `${program_id}:${aleoFunction}`; - - // Get the program imports - const imports = - programManager.networkClient.getProgramImports(localProgram); - - // Get the proving and verifying keys for the function - if (lastLocalProgram !== localProgram) { - const keys = programManager.executionEngine.synthesizeKeypair( - localProgram, - aleoFunction, - ); - programManager.keyProvider.cacheKeys(cacheKey, [ - keys.provingKey(), - keys.verifyingKey(), - ]); - lastLocalProgram = localProgram; - } - - // Pass the cache key to the execute function - const keyParams = new aleo.AleoKeyProviderParams({ - cacheKey: cacheKey, - }); - - // Execute the function locally - let response = await programManager.executeOffline( - localProgram, - aleoFunction, - inputs, - imports, - keyParams, - undefined, - undefined, - aleo.PrivateKey.from_string(privateKey), - ); - - // Return the outputs to the main thread - self.postMessage({ - type: "OFFLINE_EXECUTION_COMPLETED", - outputs, - }); - } catch (error) { - console.error(error); - self.postMessage({ - type: "ERROR", - errorMessage: error.toString(), - }); - } - })(); - } -}); -``` +import { + Account, + ProgramManager, + PrivateKey, + initThreadPool, + AleoKeyProvider, + AleoNetworkClient, + NetworkRecordProvider, +} from "@aleohq/sdk"; +import { expose, proxy } from "comlink"; + +await initThreadPool(); + +async function localProgramExecution(program, aleoFunction, inputs) { + const programManager = new ProgramManager(); + + // Create a temporary account for the execution of the program + const account = new Account(); + programManager.setAccount(account); + + const executionResponse = await programManager.run( + program, + aleoFunction, + inputs, + false, + ); + return executionResponse.getOutputs(); +} + +async function getPrivateKey() { + const key = new PrivateKey(); + return proxy(key); +} + +async function deployProgram(program) { + const keyProvider = new AleoKeyProvider(); + keyProvider.useCache(true); + + // Create a record provider that will be used to find records and transaction data for Aleo programs + const networkClient = new AleoNetworkClient("https://api.explorer.aleo.org/v1"); + + // Use existing account with funds + const account = new Account({ + privateKey: "user1PrivateKey", + }); -The WebWorker can then be initialized in worker provider component which uses React effects + const recordProvider = new NetworkRecordProvider(account, networkClient); + // Initialize a program manager to talk to the Aleo network with the configured key and record providers + const programManager = new ProgramManager( + "https://api.explorer.aleo.org/v1", + keyProvider, + recordProvider, + ); + + programManager.setAccount(account); + + // Define a fee to pay to deploy the program + const fee = 1.9; // 1.9 Aleo credits + + // Deploy the program to the Aleo network + const tx_id = await programManager.deploy(program, fee); + + return tx_id; +} + +const workerMethods = { localProgramExecution, getPrivateKey, deployProgram }; +expose(workerMethods); +``` + +`AleoWorker.js` ```jsx -import { useEffect, useState } from "react"; -import WorkerContext from "./WorkerContext"; +import { wrap } from "comlink"; -const WorkerProvider = ({ children }) => { - const [worker, setWorker] = useState(null); - const [workerReady, setWorkerReady] = useState(false); +let singletonWorker = null; - useEffect(() => { - let worker = new Worker(new URL("./worker.js", import.meta.url), { +const AleoWorker = () => { + if (!singletonWorker) { + const worker = new Worker(new URL("worker", import.meta.url), { type: "module", }); - setWorker(worker); - worker.onmessage = (event) => { - if (event.data.type === "ALEO_WORKER_READY") { - setWorkerReady(true); - } + worker.onerror = function(event) { + console.error("Error in worker: " + event?.message); }; - return () => { - worker.terminate(); - }; - }, []); - - if (!workerReady) { - return ( - <> -
-
-
- - ); + singletonWorker = wrap(worker); } - - return ( - - {children} - - ); + return singletonWorker; }; -export default WorkerProvider; +export { AleoWorker }; ``` -
-Using both webworkers and a wasm initialization in a React hook, a single page app can be created that executes -Aleo zero knowledge programs. +Using both WebWorkers and SDK initialization in React, a single-page app can be created by importing `AleoWorker.js`, which executes Aleo zero-knowledge programs.
Example App.jsx Implementing Zero Knowledge Program Execution +`App.jsx` ```jsx -import { useEffect, useState } from "react"; +import { useState } from "react"; import reactLogo from "./assets/react.svg"; -import aleoLogo from "./assets/aleo.png"; +import aleoLogo from "./assets/aleo.svg"; import "./App.css"; -import { useAleoWASM } from "./aleo-wasm-hook"; +import helloworld_program from "../helloworld/build/main.aleo?raw"; +import { AleoWorker } from "./workers/AleoWorker"; +const aleoWorker = AleoWorker(); function App() { const [count, setCount] = useState(0); - const aleo = useAleoWASM(); const [account, setAccount] = useState(null); - const [loading, setLoading] = useState(false); + const [executing, setExecuting] = useState(false); + const [deploying, setDeploying] = useState(false); - const generateAccount = () => { - setAccount(new aleo.PrivateKey()); + const generateAccount = async () => { + const key = await aleoWorker.getPrivateKey(); + setAccount(await key.to_string()); }; - const [worker, setWorker] = useState(null); - - useEffect(() => { - if (worker === null) { - const spawnedWorker = spawnWorker(); - setWorker(spawnedWorker); - return () => { - spawnedWorker.terminate(); - }; - } - }, []); - - function spawnWorker() { - return new Worker(new URL("workers/worker.js", import.meta.url), { - type: "module", - }); - } - - function postMessagePromise(worker, message) { - return new Promise((resolve, reject) => { - worker.onmessage = (event) => { - resolve(event.data); - }; - worker.onerror = (error) => { - reject(error); - }; - worker.postMessage(message); - }); - } - async function execute() { - const hello_hello_program = - "program hello_hello.aleo;\n" + - "\n" + - "function hello:\n" + - " input r0 as u32.public;\n" + - " input r1 as u32.private;\n" + - " add r0 r1 into r2;\n" + - " output r2 as u32.private;\n"; - - setLoading(true); - const result = await postMessagePromise(worker, { - type: "ALEO_EXECUTE_PROGRAM_LOCAL", - localProgram: hello_hello_program, - aleoFunction: "hello", - inputs: ["5u32", "5u32"], - privateKey: account.to_string(), - }); - setLoading(false); + setExecuting(true); + const result = await aleoWorker.localProgramExecution( + helloworld_program, + "main", + ["5u32", "5u32"], + ); + setExecuting(false); alert(JSON.stringify(result)); } + async function deploy() { + setDeploying(true); + try { + const result = await aleoWorker.deployProgram(helloworld_program); + console.log("Transaction:") + console.log("https://api.explorer.aleo.org/v1/transaction?id=" + result) + alert("Transaction ID: " + result); + } catch (e) { + console.log(e) + alert("Error with deployment, please check console for details"); + } + setDeploying(false); + } + return ( <> @@ -632,21 +583,38 @@ function App() {

-

Edit src/App.jsx and save to test HMR

+ + {/* Advanced Section */} +
+

Advanced Actions

+

+ Deployment on Aleo requires certain prerequisites like seeding your + wallet with credits and retrieving a fee record. Check README for more + details. +

+

+ +

+

Click on the Aleo and React logos to learn more

@@ -658,6 +626,42 @@ export default App; ```
+#### Integrating Aleo Programs Into Your App + +If you are starting with a simple framework template rather than with Aleo templates, handling files with a .aleo extension in a web application requires specific configurations because these files are not natively recognized by most web development environments. The .aleo extension typically belongs to Aleo zero-knowledge programs, which are special scripts or codes used within the Aleo platform to ensure privacy and security through cryptographic proofs. + +To integrate these files into a web application, such as a React app, you need to define how they should be treated during the build process. + +**Configuration File** + +Adding configuration rules in your build system (like Vite, Webpack, or Next.js) is necessary to tell the build tool how to process these files. Using something like raw-loader in this configuration ensures that .aleo files are loaded as plain text. This step is essential because it converts the content of .aleo files into a usable format that your web application can execute or display. + +``` +module:{ + rules:[ + { + test: /\.aleo$/i, + use: 'raw-loader', + }, + ] +} +``` + +
+Handling .aleo Types in TypeScript +If you are using TypeScript, you need to inform the TypeScript compiler about the type of content these files contain by declaring a module for *.aleo files: + +`config.d.ts` +```typescript +declare module '*.aleo' { + const content: string; + export default content; + } +``` +Make sure that you included custom types in your `tsconfig` file. + +
+ A full example of this implementation can be found [here](https://github.com/AleoHQ/sdk/blob/testnet3/create-aleo-app/template-react-leo/src/App.jsx) diff --git a/documentation/sdk/typescript/02_aleo_network_client.md b/documentation/sdk/typescript/02_aleo_network_client.md index 2e57e9731..1bb813cc3 100644 --- a/documentation/sdk/typescript/02_aleo_network_client.md +++ b/documentation/sdk/typescript/02_aleo_network_client.md @@ -13,15 +13,19 @@ The methods provided in this class provide information on the Aleo Blockchain

+ +### aleoNetworkClient.setHost(host) +

Set a new host for the networkClient

+ +| Param | Type | +| --- | --- | +| host | string | + +**Example** +```js +// New connection to a public beacon node +let public_connection = AleoNetworkClient.setHost("https://api.explorer.aleo.org/v1"); +``` ### aleoNetworkClient.setAccount(account) @@ -118,6 +136,71 @@ let blockRange = connection.getBlockRange(2050, 2100); ```js let program = connection.getProgram("foo.aleo"); ``` + + + +### aleoNetworkClient.getProgramObject(programId) +

Returns a program object from a program ID or program source code

+ +**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) + +| Param | Type | +| --- | --- | +| programId | string | + +**Example** +```js +let program = connection.getProgramObject("foo.aleo"); +``` + + + +### aleoNetworkClient.getProgramImports(programId) +

Returns an object containing the source code of a program and the source code of all programs it imports

+ +**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) + +| Param | Type | +| --- | --- | +| programId | string | + +**Example** +```js +let program = connection.getProgramImports("foo.aleo"); +``` + + + +### aleoNetworkClient.getDeploymentTransactionIDForProgram(programId) +

Returns the deployment transaction id associated with the specified program

+ +**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) + +| Param | Type | +| --- | --- | +| programId | string | + +**Example** +```js +let program = connection.getDeploymentTransactionIDForProgram("foo.aleo"); +``` + + + +### aleoNetworkClient.getDeploymentTransactionForProgram(programId) +

Returns the deployment transaction associated with a specified program

+ +**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) + +| Param | Type | +| --- | --- | +| programId | string | + +**Example** +```js +let program = connection.getDeploymentTransactionForProgram("foo.aleo"); +``` + ### aleoNetworkClient.getProgramMappingNames(programId) @@ -133,6 +216,23 @@ let program = connection.getProgram("foo.aleo"); ```js let mappings = connection.getProgramMappingNames("credits.aleo"); ``` + + + +### aleoNetworkClient.getProgramImportNames(programId) +

Get a list of the program names that a program imports

+ +**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) + +| Param | Type | +| --- | --- | +| programId | string | + +**Example** +```js +let mappings = connection.getProgramImportNames("foo.aleo"); +``` + ### aleoNetworkClient.getMappingValue(programId, mappingName, key) @@ -161,25 +261,27 @@ let mappingValue = connection.getMappingValue("credits.aleo", "account", "aleo1r ```js let latestHeight = connection.getLatestBlock(); ``` - -### aleoNetworkClient.getLatestHash() -

Returns the hash of the last published block

+ + +### aleoNetworkClient.getLatestHeight() +

Returns the latest block height

**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) **Example** ```js -let latestHash = connection.getLatestHash(); +let latestHeight = connection.getLatestHeight(); ``` - -### aleoNetworkClient.getLatestHeight() -

Returns the latest block height

+ + +### aleoNetworkClient.getLatestCommittee() +

Returns the latest committee

**Kind**: instance method of [AleoNetworkClient](#AleoNetworkClient) **Example** ```js -let latestHeight = connection.getLatestHeight(); +let latestCommittee = connection.getLatestCommittee(); ``` @@ -206,6 +308,7 @@ let stateRoot = connection.getStateRoot(); ```js let transaction = connection.getTransaction("at1handz9xjrqeynjrr0xay4pcsgtnczdksz3e584vfsgaz0dh0lyxq43a4wj"); ``` + ### aleoNetworkClient.getTransactions(height) @@ -261,4 +364,4 @@ let records = connection.findUnspentRecords(startHeight, undefined, privateKey, // Find specific amounts with a maximum number of cumulative microcredits const maxMicrocredits = 100000; let records = connection.findUnspentRecords(startHeight, undefined, privateKey, undefined, maxMicrocredits); -``` \ No newline at end of file +```