diff --git a/.vscode/ltex.hiddenFalsePositives.en-US.txt b/.vscode/ltex.hiddenFalsePositives.en-US.txt index 84dc8691..5c4c1e91 100644 --- a/.vscode/ltex.hiddenFalsePositives.en-US.txt +++ b/.vscode/ltex.hiddenFalsePositives.en-US.txt @@ -1,3 +1,4 @@ {"rule":"BASE_BASIS","sentence":"^\\QThis guide covers the Cartesi+Espresso integration and how to upgrade Cartesi application such that inputs can be submitted via Espresso instead of the regular base layer.\\E$"} {"rule":"MORFOLOGIK_RULE_EN_US","sentence":"^\\QIntegrating Cartesi and Chronicle offers Cartesi applications access to onchain and offcahin data like, price feed without developers having to set up additional systems or intermediaries.\\E$"} {"rule":"MORFOLOGIK_RULE_EN_US","sentence":"^\\QPrevado Id:\\E$"} +{"rule":"MORFOLOGIK_RULE_EN_US","sentence":"^\\QThe Devnet environment functions similarly to a mainnet.\\E$"} diff --git a/cartesi-rollups_versioned_docs/version-2.0/api-reference/backend/introduction.md b/cartesi-rollups_versioned_docs/version-2.0/api-reference/backend/introduction.md index ddb215a0..082050c3 100644 --- a/cartesi-rollups_versioned_docs/version-2.0/api-reference/backend/introduction.md +++ b/cartesi-rollups_versioned_docs/version-2.0/api-reference/backend/introduction.md @@ -3,7 +3,7 @@ id: introduction title: Introduction --- -The backend of a Cartesi dApp retrieves a new request as follows: +The backend of a Cartesi application as mentioned in the [overview section](../index.md#backend-apis) contains the applications logic and state, it interacts with the Cartesi rollups framework by retrieving request and submitting structured outputs. The application backend retrieves a new request as follows: - Finish — Communicates that any previous processing has been completed and that the backend is ready to handle the subsequent request. This following request is returned as the call's response and can be of the following types: @@ -120,6 +120,81 @@ while True: + +

+
+```rust
+use json::{object, JsonValue};
+use std::env;
+
+pub async fn handle_advance(
+    _client: &hyper::Client,
+    _server_addr: &str,
+    request: JsonValue,
+) -> Result<&'static str, Box> {
+    println!("Received advance request data {}", &request);
+    let _payload = request["data"]["payload"]
+        .as_str()
+        .ok_or("Missing payload")?;
+    // TODO: add application logic here
+    Ok("accept")
+}
+
+pub async fn handle_inspect(
+    _client: &hyper::Client,
+    _server_addr: &str,
+    request: JsonValue,
+) -> Result<&'static str, Box> {
+    println!("Received inspect request data {}", &request);
+    let _payload = request["data"]["payload"]
+        .as_str()
+        .ok_or("Missing payload")?;
+    // TODO: add application logic here
+    Ok("accept")
+}
+
+#[tokio::main]
+async fn main() -> Result<(), Box> {
+    let client = hyper::Client::new();
+    let server_addr = env::var("ROLLUP_HTTP_SERVER_URL")?;
+
+    let mut status = "accept";
+    loop {
+        println!("Sending finish");
+        let response = object! {"status" => status.clone()};
+        let request = hyper::Request::builder()
+            .method(hyper::Method::POST)
+            .header(hyper::header::CONTENT_TYPE, "application/json")
+            .uri(format!("{}/finish", &server_addr))
+            .body(hyper::Body::from(response.dump()))?;
+        let response = client.request(request).await?;
+        println!("Received finish status {}", response.status());
+
+        if response.status() == hyper::StatusCode::ACCEPTED {
+            println!("No pending rollup request, trying again");
+        } else {
+            let body = hyper::body::to_bytes(response).await?;
+            let utf = std::str::from_utf8(&body)?;
+            let req = json::parse(utf)?;
+
+            let request_type = req["request_type"]
+                .as_str()
+                .ok_or("request_type is not a string")?;
+            status = match request_type {
+                "advance_state" => handle_advance(&client, &server_addr[..], req).await?,
+                "inspect_state" => handle_inspect(&client, &server_addr[..], req).await?,
+                &_ => {
+                    eprintln!("Unknown request type");
+                    "reject"
+                }
+            };
+        }
+    }
+}
+```
+
+
+
An **Advance** request involves sending input data to the base layer via JSON-RPC so they can reach the dApp backend to change the application's state. @@ -140,10 +215,12 @@ An **Inspect** request involves making an external HTTP API call to the rollups You can make a simple inspect call from your frontend client to retrieve reports. -To perform an Inspect call, use an HTTP GET request to `
/inspect/`. For example: +To perform an Inspect call, use an HTTP POST request to `
/inspect/` with a body containing the request payload. For example: ```shell -curl http://localhost:8080/inspect/mypath +curl -X POST http://localhost:8080/inspect/0xb483897a2790a5D1a1C5413690bC5933f269b3A9 \ + -H "Content-Type: application/json" \ + -d '"test"' ``` Once the call's response is received, the payload is extracted from the response data, allowing the backend code to examine it and produce outputs as **reports**. diff --git a/cartesi-rollups_versioned_docs/version-2.0/api-reference/backend/notices.md b/cartesi-rollups_versioned_docs/version-2.0/api-reference/backend/notices.md index 90dffa4b..1730d031 100644 --- a/cartesi-rollups_versioned_docs/version-2.0/api-reference/backend/notices.md +++ b/cartesi-rollups_versioned_docs/version-2.0/api-reference/backend/notices.md @@ -13,7 +13,7 @@ Crucially, the base layer conducts on-chain validation of these notices through This validation process ensures the integrity and authenticity of the submitted notices, enabling the blockchain to verify and authenticate the declared off-chain events or conditions. -Let's see how a Cartesi dApp's **Advance** request sends an output to the rollup server as a notice: +Here are sample functions you can add to your application, then call to send a notice to the rollup server: import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; @@ -23,25 +23,30 @@ import TabItem from '@theme/TabItem';

 
 ```javascript
-async function handle_advance(data) {
-  console.log("Received advance request data " + JSON.stringify(data));
-
-  const inputPayload = data["payload"];
+import { stringToHex, hexToString } from "viem";
 
+const emitNotice = async (inputPayload) => {
+  let hexPayload = stringToHex(inputPayload); // convert payload from string to hex 
   try {
     await fetch(rollup_server + "/notice", {
       method: "POST",
       headers: {
         "Content-Type": "application/json",
       },
-      body: JSON.stringify({ payload: inputPayload }),
+      body: JSON.stringify({ payload: hexPayload }),
     });
   } catch (error) {
     //Do something when there is an error
   }
+}
 
+async function handle_advance(data) {
+  console.log("Received advance request data " + JSON.stringify(data));
+  const payload = hexToString(data.payload); // convert input from hex to string for processing
+  await emitNotice(payload);
   return "accept";
 }
+
 ```
 
 
@@ -51,24 +56,16 @@ async function handle_advance(data) {

 
 ```python
-
-def handle_advance(data):
-   logger.info(f"Received advance request data {data}")
-
-   status = "accept"
-   try:
-       inputPayload = data["payload"]
-       ## Send the input payload as a notice
-       response = requests.post(
-           rollup_server + "/notice", json={"payload": inputPayload}
-       )
-       logger.info(
-           f"Received notice status {response.status_code} body {response.content}"
-       )
-   except Exception as e:
-       #  Emits report with error message here
-   return status
-
+# Notice creation Process from a message string
+def emit_notice(message):
+    notice_payload = {"payload": "0x" + message.encode("utf-8").hex()}
+    response = requests.post(rollup_server + "/notice", json=notice_payload)
+    if response.status_code == 200 or response.status_code == 201:
+        logger.info(f"Notice emitted successfully with data: {notice_payload}")
+    else:
+        logger.error(f"Failed to emit Notice with data: {notice_payload}. Status code: {response.status_code}")
+
+emit_notice("hello world")
 ```
 
 
diff --git a/cartesi-rollups_versioned_docs/version-2.0/api-reference/backend/vouchers.md b/cartesi-rollups_versioned_docs/version-2.0/api-reference/backend/vouchers.md index 43b72538..e011dd24 100644 --- a/cartesi-rollups_versioned_docs/version-2.0/api-reference/backend/vouchers.md +++ b/cartesi-rollups_versioned_docs/version-2.0/api-reference/backend/vouchers.md @@ -16,6 +16,89 @@ The [`CartesiDApp`](../contracts/application.md) contract is crucial in validati The result of the voucher execution is recorded on the base layer. This recording typically involves submitting claims by a consensus contract, ensuring the integrity and transparency of the executed on-chain action. +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + + +

+
+```python
+# Voucher creation process
+import requests
+import json
+from os import environ
+from eth_utils import function_signature_to_4byte_selector
+from eth_abi import decode, encode
+
+rollup_server = environ["ROLLUP_HTTP_SERVER_URL"]
+
+def emit_voucher(function_signature, destination, types, values):
+    selector = function_signature_to_4byte_selector(function_signature)    
+    encoded_params = encode(types, values)
+    payload = "0x" + (selector + encoded_params).hex()
+    response = requests.post(rollup_server + "/voucher", json={"payload": payload, "destination": destination, "value": '0x' + encode(["uint256"], [0]).hex()})
+    if response.status_code == 200 or response.status_code == 201:
+        logger.info(f"Voucher emitted successfully with data: {payload}")
+    else:
+        logger.error(f"Failed to emit Voucher with data: {payload}. Status code: {response.status_code}")
+
+
+emit_voucher("mint(address)", "0x784f0c076CC55EAD0a585a9A13e57c467c91Dc3a", ["address"], [data["metadata"]["msg_sender"]])
+```
+
+
+
+ + +

+
+```javascript
+import { stringToHex, encodeFunctionData, erc20Abi } from "viem";
+
+async function handle_advance(data) {
+  console.log("Received advance request data " + JSON.stringify(data));
+  const sender = data["metadata"]["msg_sender"];
+  const erc20Token = "0x784f0c076CC55EAD0a585a9A13e57c467c91Dc3a"; // Sample ERC20 token address
+
+    const call = encodeFunctionData({
+    abi: erc20Abi,
+    functionName: "transfer",
+    args: [sender, BigInt(10)],
+  });
+
+  let voucher = {
+    destination: erc20Token,
+    payload: call,
+    value: '0x',
+  };
+
+  await emitVoucher(voucher);
+  return "accept";
+}
+
+
+const emitVoucher = async (voucher) => {
+  try {
+    await fetch(rollup_server + "/voucher", {
+      method: "POST",
+      headers: {
+        "Content-Type": "application/json",
+      },
+      body: JSON.stringify(voucher),
+    });
+  } catch (error) {
+    //Do something when there is an error
+  }
+};
+
+```
+
+
+
+ +
+ :::note create a voucher [Refer to the documentation here](../../development/asset-handling.md) for asset handling and creating vouchers in your dApp. ::: diff --git a/cartesi-rollups_versioned_docs/version-2.0/development/asset-handling.md b/cartesi-rollups_versioned_docs/version-2.0/development/asset-handling.md index 76f71e24..4945f2a1 100644 --- a/cartesi-rollups_versioned_docs/version-2.0/development/asset-handling.md +++ b/cartesi-rollups_versioned_docs/version-2.0/development/asset-handling.md @@ -8,7 +8,7 @@ resources: Assets exist on the base layer, where they have actual meaning and value. -As with any execution layer solution, a Cartesi dApp that wants to manipulate assets needs a secure way of "teleporting" the assets from the base layer to the execution layer and then a way to "teleport" them back to the base layer. +As with any execution layer solution, a Cartesi Application that wants to manipulate assets needs a secure way of "teleporting" the assets from the base layer to the execution layer and when necessary, back to the base layer. Currently, Cartesi Rollups support the following types of assets: @@ -22,9 +22,9 @@ Currently, Cartesi Rollups support the following types of assets: ## Deposits -Portals enable the safe transfer of assets from the base layer to the execution layer. Users authorize portals to deduct assets from their accounts and initiate transfers to dApps. +Portals enable the safe transfer of assets from the base layer to the execution layer. Users authorize portals to deduct assets from their accounts and initiate transfers to the Application contract. -When an asset is deposited, it is on the base layer but gains a representation in the execution layer. The corresponding Portal contract sends an input via the `InputBox` contract describing the type of asset, amount, and some data the depositor might want the dApp to read. The off-chain machine will then interpret and validate the input payload. +When an asset is deposited, it is on the base layer but gains a representation in the execution layer. The corresponding Portal contract sends an input via the `InputBox` contract describing the type of asset, amount, and some data the depositor might want the application to read. The off-chain machine will then interpret and validate the input payload. Deposit input payloads are always specified as packed ABI-encoded parameters, as detailed below. @@ -42,13 +42,19 @@ Deposit input payloads are always specified as packed ABI-encoded parameters, as ## Withdrawing assets -Users can deposit assets to a Cartesi dApp, but only the dApp can initiate withdrawals. When a withdrawal request is made, it’s processed and interpreted off-chain by the Cartesi Machine running the dApp’s code. Subsequently, the Cartesi Machine creates a voucher containing the necessary instructions for withdrawal, which is executable when an epoch has settled. +Users can deposit assets to a Cartesi Application, but only the Application can initiate withdrawals. When a withdrawal request is made, it’s processed and interpreted off-chain by the Cartesi Machine running the application’s code. Subsequently, the Cartesi Machine creates a voucher containing the necessary instructions for withdrawal, which is executable when an epoch has settled. -Vouchers are crucial in allowing dApps in the execution layer to interact with contracts in the base layer through message calls. They are emitted by the off-chain machine and executed by any participant in the base layer. Each voucher includes a destination address and a payload, typically encoding a function call for Solidity contracts. +### Withdrawing Tokens -The dApp’s off-chain layer often requires knowledge of its address to facilitate on-chain interactions for withdrawals, for example: `transferFrom(sender, recipient, amount)`. In this case, the sender is the dApp itself. +Vouchers are crucial in allowing applications in the execution layer to interact with contracts in the base layer through message calls. They are emitted by the off-chain machine and executed by any participant in the base layer. Each voucher includes a destination address and a payload, typically encoding a function call for Solidity contracts. -Next, the off-chain machine uses the address of the application on the base layer to generate a voucher for execution at the [`executeVoucher()`](../api-reference/contracts/application.md/#executevoucher) function of the `CartesiDApp` contract. This address is known to the offchain machine because it is embedded in the metadata of every input sent to the application, though the developer will need to implement extra logic fetch this address from the metadata then properly store and retrieve it when needed in situations like generating the above Voucher. +The application’s off-chain layer often requires knowledge of its address to facilitate on-chain interactions for withdrawals, for example: `transferFrom(sender, recipient, amount)`. In this case, the sender is the application itself. + +Next, the off-chain machine uses the address of the application on the base layer to generate a voucher for execution at the [`executeOutput()`](../api-reference/json-rpc/application.md/#executeoutput) function of the `Application` contract. This address is known to the offchain machine because it is embedded in the metadata of every input sent to the application, though the developer will need to implement extra logic fetch this address from the metadata then properly store and retrieve it when needed in situations like generating the above Voucher. + +### Withdrawing Ether + +To execute Ether withdrawal it is important to emit a voucher with the necessary details as regarding whom you intend to send the Ether to and also the amount to send, nevertheless since the Application contract Executes vouchers by making a [safeCall](https://github.com/cartesi/rollups-contracts/blob/cb52d00ededd2da9f8bf7757710301dccb7d536d/src/library/LibAddress.sol#L18C14-L18C22) to the destination, passing a value (Ether amount to send along with the call) and a payload (function signature to call), it's acceptable to leave the payload section empty if you do not intend to call any functions in the destination address while sending just the specified value of Ether to the destination address. If you intend to call a payable function and also send Ether along, you can add a function signature matching the payable function you intend to call to the payload field. :::note epoch length By default, Cartesi nodes close one epoch every 7200 blocks. You can [manually set the epoch length](./cli-commands.md/#run) to facilitate quicker asset-handling methods. @@ -56,12 +62,12 @@ By default, Cartesi nodes close one epoch every 7200 blocks. You can [manually s Here are the function signatures used by vouchers to withdraw the different types of assets: -| Asset | Destination | Function signature | -| :------- | :------------- | :------------------------------------------------------------------------------------------------------------------------------------------ | -| Ether | dApp contract | `withdrawEther(address,uint256)` [:page_facing_up:](../api-reference/contracts/application.md/#withdrawether) | -| ERC-20 | Token contract | `transfer(address,uint256)` [:page_facing_up:](https://eips.ethereum.org/EIPS/eip-20#methods) | -| ERC-20 | Token contract | `transferFrom(address,address,uint256)` [:page_facing_up:](https://eips.ethereum.org/EIPS/eip-20#methods) | -| ERC-721 | Token contract | `safeTransferFrom(address,address,uint256)` [:page_facing_up:](https://eips.ethereum.org/EIPS/eip-721#specification) | -| ERC-721 | Token contract | `safeTransferFrom(address,address,uint256,bytes)` [:page_facing_up:](https://eips.ethereum.org/EIPS/eip-721#specification) | -| ERC-1155 | Token contract | `safeTransferFrom(address,address,uint256,uint256,data)` [:page_facing_up:](https://eips.ethereum.org/EIPS/eip-1155#specification) | -| ERC-1155 | Token contract | `safeBatchTransferFrom(address,address,uint256[],uint256[],data)` [:page_facing_up:](https://eips.ethereum.org/EIPS/eip-1155#specification) | +| Asset | Destination | Function signature | +| :------- | :------------------- | :------------------------------------------------------------------------------------------------------------------------------------------ | +| Ether | Receiver's Address | Optional | +| ERC-20 | Token contract | `transfer(address,uint256)` [:page_facing_up:](https://eips.ethereum.org/EIPS/eip-20#methods) | +| ERC-20 | Token contract | `transferFrom(address,address,uint256)` [:page_facing_up:](https://eips.ethereum.org/EIPS/eip-20#methods) | +| ERC-721 | Token contract | `safeTransferFrom(address,address,uint256)` [:page_facing_up:](https://eips.ethereum.org/EIPS/eip-721#specification) | +| ERC-721 | Token contract | `safeTransferFrom(address,address,uint256,bytes)` [:page_facing_up:](https://eips.ethereum.org/EIPS/eip-721#specification) | +| ERC-1155 | Token contract | `safeTransferFrom(address,address,uint256,uint256,data)` [:page_facing_up:](https://eips.ethereum.org/EIPS/eip-1155#specification) | +| ERC-1155 | Token contract | `safeBatchTransferFrom(address,address,uint256[],uint256[],data)` [:page_facing_up:](https://eips.ethereum.org/EIPS/eip-1155#specification) | diff --git a/cartesi-rollups_versioned_docs/version-2.0/development/building-a-dapp.md b/cartesi-rollups_versioned_docs/version-2.0/development/building-a-dapp.md deleted file mode 100644 index 226f1523..00000000 --- a/cartesi-rollups_versioned_docs/version-2.0/development/building-a-dapp.md +++ /dev/null @@ -1,163 +0,0 @@ ---- -id: building-a-dapp -title: Building a dApp -resources: - - url: https://github.com/Calindra/nonodo - title: NoNodo - - url: https://cartesiscan.io/ - title: CartesiScan ---- - - -## Creating the application -Cartesi CLI simplifies creating dApps on Cartesi. To create a new application, run: - -```shell -cartesi create --template -``` - -For example, create a Python project. - -```shell -cartesi create new-dapp --template python -``` - -This command creates a `new-dapp` directory with essential files for your dApp development. - -- `Dockerfile`: Contains configurations to build a complete Cartesi machine with your app's dependencies. Your backend code will run in this environment. - -- `README.md`: A markdown file with basic information and instructions about your dApp. - -- `dapp.py`: A Python file with template backend code that serves as your application's entry point. - -- `requirements.txt`: Lists the Python dependencies required for your application. - -Cartesi CLI has templates for the following languages – `cpp`, `cpp-low-level`, `go`, `javascript`, `lua`, `python`, `ruby`, `rust`, and `typescript`. - -After creating your application, you can start building your dApp by adding your logic to the `dapp.py` file. - - -:::note Building with Go? -For Go applications on Cartesi, we recommend using [Rollmelette](https://github.com/rollmelette/rollmelette). It’s a high-level Go framework and an alternative template that simplifies development and enhances input management, providing a smoother and more efficient experience. -::: - - -## Building the application - -“Building” in this context compiles your application into RISC-V architecture and consequently builds a Cartesi machine containing your application. This architecture enables computation done by your application to be reproducible and verifiable. - -With the Docker engine running, change the directory to your application and build by running: - -```shell -cartesi build -``` - -The successful execution of this step will log this in your terminal: - -```shell - . - / \ - / \ -\---/---\ /----\ - \ X \ - \----/ \---/---\ - \ / CARTESI - \ / MACHINE - ' - -[INFO rollup_http_server] starting http dispatcher service... -[INFO rollup_http_server::http_service] starting http dispatcher http service! -[INFO actix_server::builder] starting 1 workers -[INFO actix_server::server] Actix runtime found; starting in Actix runtime -[INFO rollup_http_server::dapp_process] starting dapp -INFO:__main__:HTTP rollup_server url is http://127.0.0.1:5004 -INFO:__main__:Sending finish - -Manual yield rx-accepted (0x100000000 data) -Cycles: 2767791744 -2767791744: b740d27cf75b6cb10b1ab18ebd96be445ca8011143d94d8573221342108822f5 -Storing machine: please wait -Successfully copied 288MB to /Users/michaelasiedu/Code/calculator/python/.cartesi/image -``` -### Memory - -To change the default memory size for the Cartesi Machine, you can personalize it by adding a specific label in your Dockerfile. - -The line below lets you define the memory size in megabytes (MB): - -```dockerfile -LABEL io.cartesi.rollups.ram_size=128Mi -``` - -:::note environment variables -You can create a `.cartesi.env` in the project's root and override any variable controlling the rollups-node. -::: - - -## Running the Application - -Running your application starts your backend on port `8080` and local Anvil node on port `8545`. - -In essence, the node also logs all outputs received by your backend. - -Here are the prerequisites to run the node: - -- Docker Engine must be active. -- Cartesi machine snapshot successfully built with `cartesi build`. - -To start the node, run: - -```shell -cartesi run -``` - -This command runs your backend compiled to RISC-V and packages it as a Cartesi machine. - -:::troubleshoot troubleshooting common errors - -#### Error: Depth Too High - -```shell -Attaching to 2bd74695-prompt-1, 2bd74695-validator-1 -2bd74695-validator-1 | Error: DepthTooHigh { depth: 2, latest: 1 } -2bd74695-validator-1 | Error: DepthTooHigh { depth: 2, latest: 1 } -``` - -This indicates that the node is reading blocks too far behind the current blockchain state. - -#### Solution - -Create or modify a `.cartesi.env` file in your project directory and set: - -```shell -TX_DEFAULT_CONFIRMATIONS=1 -``` - -This adjustment should align the node's block reading with the blockchain's current state. - -::: - -### Overview of Node Services - -The `cartesi run` command activates several services essential for node operation: - -- **Anvil Chain**: Runs a local blockchain available at `http://localhost:8545`. - -- **GraphQL Playground**: An interactive IDE at `http://localhost:8080/graphql` for exploring the GraphQL server. - -- **Blockchain Explorer**: Monitors node activity and manages transactions via `http://localhost:8080/explorer/`. - -- **Inspect**: A diagnostic tool accessible at `http://localhost:8080/inspect/` to inspect the node’s state. - - -### CartesiScan - -[CartesiScan](https://cartesiscan.io/) is a valuable tool for developers and users alike, offering a comprehensive overview of Cartesi Rollups applications and their interactions with the blockchain. - -Additionally, it provides expandable data regarding outputs, encompassing notices, vouchers, and reports. - -When you run your application with `cartesi run` , there is a local instance of CartesiScan on `http://localhost:8080/explorer`. - -:::note Testing tools -[NoNodo](https://github.com/Calindra/nonodo) is a Cartesi Rollups testing tool that works with host machine applications, eliminating the need for Docker or RISC-V compilation. -::: diff --git a/cartesi-rollups_versioned_docs/version-2.0/development/building-and-running-an-application.md b/cartesi-rollups_versioned_docs/version-2.0/development/building-and-running-an-application.md new file mode 100644 index 00000000..1e413be3 --- /dev/null +++ b/cartesi-rollups_versioned_docs/version-2.0/development/building-and-running-an-application.md @@ -0,0 +1,101 @@ +--- +id: building-and-running-an-application +title: Building and running an application +resources: + - url: https://cartesiscan.io/ + title: CartesiScan +--- + +## Building the application + +“Building” in this context compiles your application into RISC-V architecture, this architecture enables computation done by your application to be reproducible and verifiable. While "Running" encompasses the process of publishing your application to your local node running on docker and also deploying the necessary contracts for your application to a local Anvil devnet. + +With the Docker engine running, CD into your application and build by running: + +```shell +cartesi build +``` + +The successful execution of this step will log this in your terminal: + +```shell + + . + / \ + / \ +\---/---\ /----\ + \ X \ + \----/ \---/---\ + \ / CARTESI + \ / MACHINE + ' + +[INFO rollup_http_server] starting http dispatcher service... +[INFO rollup_http_server::http_service] starting http dispatcher http service! +[INFO actix_server::builder] starting 1 workers +[INFO actix_server::server] Actix runtime found; starting in Actix runtime +[INFO rollup_http_server::dapp_process] starting dapp: dapp +Sending finish + +Manual yield rx-accepted (1) (0x000020 data) +Cycles: 69709199 +69709199: 9e0420c0fda1a5dc9256b3f9783b09f207e5222a88429e91629cc2e495282b35 +Storing machine: please wait +``` + +### Memory + +To change the default memory size for the Cartesi Machine, you can personalize it by adding a specific label in your Dockerfile. + +The line below lets you define the memory size in megabytes (MB): + +```dockerfile +LABEL io.cartesi.rollups.ram_size=128Mi +``` + +:::note environment variables +You can create a `.cartesi.env` in the project's root and override any variable controlling the rollups-node. +::: + +## Deploying the application to devnet + +Running the deployment command compiles your application and publishes it to the node running in the devnet environment. It also deploys the required authority and application contracts to the local Anvil network. + +You can deploy multiple applications to this environment. For each application, you can either create a new authority contract or link it to an existing one. + +Prerequisites for Deployment +Before deploying your application, ensure the following: + +- Docker Engine is active. +- The Devnet environment is running. +- A Cartesi machine snapshot has been successfully built using `cartesi build`. + +Once these prerequisites are met, proceed to deploy your application by running: + +```shell +cartesi deploy +``` + +This command compiles your backend to RISC-V, packages it as a Cartesi machine, then publishes it to the node running on the devnet. + +During deployment, you'll have to specify: + +- Private key or Mnemonic to fund the deployment. +- The authority owner address. +- The application owner address. +- An application name (making it easier to identify your application instead of relying on the contract address). + +Once the deployment is complete, you should have logs similar to the following: + +```shell +✔ Cartesi machine template hash 0x9e0420c0fda1a5dc9256b3f9783b09f207e5222a88429e91629cc2e495282b35 +✔ Wallet Mnemonic +✔ Mnemonic test test test test test test test test test test test junk +✔ Account 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 9994.000195973381758124 ETH +✔ Authority Owner 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 +✔ Application Owner 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 +✔ Application 0x1Db6DdECF18095847f7099cfAc43A2671326d21c +✔ Machine snapshot /var/lib/cartesi-rollups-node/snapshots/0x9e0420c0fda1a5dc9256b3f9783b09f207e5222a88429e91629cc2e495282b35/ +✔ Application Name counter +✔ Registration counter +``` diff --git a/cartesi-rollups_versioned_docs/version-2.0/development/cli-commands.md b/cartesi-rollups_versioned_docs/version-2.0/development/cli-commands.md index 6d92fdaa..8baed5a1 100644 --- a/cartesi-rollups_versioned_docs/version-2.0/development/cli-commands.md +++ b/cartesi-rollups_versioned_docs/version-2.0/development/cli-commands.md @@ -3,10 +3,10 @@ id: cli-commands title: CLI commands --- - The Cartesi CLI provides essential tools for developing, deploying, and interacting with Cartesi applications. This page offers a quick reference to available commands and usage. ## Basic Usage + To use any command, run: ```bash @@ -21,135 +21,205 @@ cartesi help [COMMAND] ## Core Commands -| Command | Description | -|---------|-------------| -| `create` | Create a new application | -| `build` | Build the application | -| `run` | Run the application node | -| `send` | Send input to the application | -| `deploy` | Deploy application to a live network | -| `address-book` | Prints addresses of deployed smart contracts | -| `clean` | Clean build artifacts of the application | -| `doctor` | Verify the minimal system requirements | -| `hash` | Print the image hash generated by the build command | -| `shell` | Start a shell in the Cartesi machine of the application | - +| Command | Description | +| -------------- | --------------------------------------------------------------------------------- | +| `build` | Build the application | +| `send` | Send input to the application | +| `address-book` | Prints addresses of deployed smart contracts | +| `clean` | Deletes all cached build artifacts of application. | +| `doctor` | Verify the minimal system requirements | +| `hash` | Print the image hash generated by the build command | +| `shell` | Start a shell in the Cartesi machine of the application | +| `create` | Creates a new application template. | +| `logs` | Show logs of a local node environment. | +| `start` | Start a local node environment. | +| `status` | Shows the status of a local node environment. | +| `stop` | Stop a local node environment. | +| `deploy` | Deploy an application to a node. | --- -### `create` -Create a new Cartesi application from a template. +### `build` + +Compiles your application to RISC-V and builds a Cartesi machine snapshot. #### Usage: + ```bash -cartesi create NAME --template [--branch ] +cartesi build [--from-image ] [--target ] ``` #### Flags: -- `--template=