Skip to content

Commit 82dd165

Browse files
authored
Merge pull request #1309 from dfinity/marc0olo/icp-cli-rust-hello-world
feat: add icp-cli support for rust/hello_world
2 parents d7a6012 + b8dc4f7 commit 82dd165

File tree

9 files changed

+203
-146
lines changed

9 files changed

+203
-146
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
build/
44
node_modules/
55
package-lock.json
6+
Cargo.lock
67
dist/
78
.DS_Store
89
_MACOSX

rust/hello_world/BUILD.md

Lines changed: 11 additions & 98 deletions
Original file line numberDiff line numberDiff line change
@@ -1,113 +1,26 @@
11
# Continue building locally
22

3-
Projects deployed through ICP Ninja are temporary; they will only be live for 20 minutes before they are removed. The command-line tool `dfx` can be used to continue building your ICP Ninja project locally and deploy it to the mainnet.
3+
Projects deployed through ICP Ninja are temporary; they will only be live for 30 minutes before they are removed. To continue building locally, follow these steps.
44

5-
To migrate your ICP Ninja project off of the web browser and develop it locally, follow these steps.
5+
### 1. Install developer tools
66

7-
### 1. Install developer tools.
8-
9-
You can install the developer tools natively or use Dev Containers.
10-
11-
#### Option 1: Natively install developer tools
12-
13-
> Installing `dfx` natively is currently only supported on macOS and Linux systems. On Windows, it is recommended to use the Dev Containers option.
14-
15-
1. Install `dfx` with the following command:
16-
17-
```
18-
19-
sh -ci "$(curl -fsSL https://internetcomputer.org/install.sh)"
20-
21-
```
22-
23-
> On Apple Silicon (e.g., Apple M1 chip), make sure you have Rosetta installed (`softwareupdate --install-rosetta`).
24-
25-
2. [Install NodeJS](https://nodejs.org/en/download/package-manager).
26-
27-
3. For Rust projects, you will also need to:
28-
29-
- Install [Rust](https://doc.rust-lang.org/cargo/getting-started/installation.html#install-rust-and-cargo): `curl https://sh.rustup.rs -sSf | sh`
30-
31-
- Install [candid-extractor](https://crates.io/crates/candid-extractor): `cargo install candid-extractor`
32-
33-
4. For Motoko projects, you will also need to:
34-
35-
- Install the Motoko package manager [Mops](https://docs.mops.one/quick-start#2-install-mops-cli): `npm i -g ic-mops`
36-
37-
Lastly, navigate into your project's directory that you downloaded from ICP Ninja.
38-
39-
#### Option 2: Dev Containers
40-
41-
Continue building your projects locally by installing the [Dev Container extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) for VS Code and [Docker](https://docs.docker.com/engine/install/).
42-
43-
Make sure Docker is running, then navigate into your project's directory that you downloaded from ICP Ninja and start the Dev Container by selecting `Dev-Containers: Reopen in Container` in VS Code's command palette (F1 or Ctrl/Cmd+Shift+P).
44-
45-
> Note that local development ports (e.g. the ports used by `dfx` or `vite`) are forwarded from the Dev Container to your local machine. In the VS code terminal, use Ctrl/Cmd+Click on the displayed local URLs to open them in your browser. To view the current port mappings, click the "Ports" tab in the VS Code terminal window.
46-
47-
### 2. Start the local development environment.
48-
49-
```
50-
dfx start --background
51-
```
52-
53-
### 3. Create a local developer identity.
54-
55-
To manage your project's canisters, it is recommended that you create a local [developer identity](https://internetcomputer.org/docs/building-apps/getting-started/identities) rather than use the `dfx` default identity that is not stored securely.
56-
57-
To create a new identity, run the commands:
58-
59-
```
60-
61-
dfx identity new IDENTITY_NAME
62-
63-
dfx identity use IDENTITY_NAME
64-
65-
```
66-
67-
Replace `IDENTITY_NAME` with your preferred identity name. The first command `dfx start --background` starts the local `dfx` processes, then `dfx identity new` will create a new identity and return your identity's seed phase. Be sure to save this in a safe, secure location.
68-
69-
The third command `dfx identity use` will tell `dfx` to use your new identity as the active identity. Any canister smart contracts created after running `dfx identity use` will be owned and controlled by the active identity.
70-
71-
Your identity will have a principal ID associated with it. Principal IDs are used to identify different entities on ICP, such as users and canisters.
72-
73-
[Learn more about ICP developer identities](https://internetcomputer.org/docs/building-apps/getting-started/identities).
74-
75-
### 4. Deploy the project locally.
76-
77-
Deploy your project to your local developer environment with:
78-
79-
```
80-
npm install
81-
dfx deploy
7+
Install [Node.js](https://nodejs.org/en/download/) and [icp-cli](https://cli.icp.build):
828

9+
```bash
10+
npm install -g @icp-sdk/icp-cli @icp-sdk/ic-wasm
8311
```
8412

85-
Your project will be hosted on your local machine. The local canister URLs for your project will be shown in the terminal window as output of the `dfx deploy` command. You can open these URLs in your web browser to view the local instance of your project.
86-
87-
### 5. Obtain cycles.
88-
89-
To deploy your project to the mainnet for long-term public accessibility, first you will need [cycles](https://internetcomputer.org/docs/building-apps/getting-started/tokens-and-cycles). Cycles are used to pay for the resources your project uses on the mainnet, such as storage and compute.
90-
91-
> This cost model is known as ICP's [reverse gas model](https://internetcomputer.org/docs/building-apps/essentials/gas-cost), where developers pay for their project's gas fees rather than users pay for their own gas fees. This model provides an enhanced end user experience since they do not need to hold tokens or sign transactions when using a dapp deployed on ICP.
92-
93-
> Learn how much a project may cost by using the [pricing calculator](https://internetcomputer.org/docs/building-apps/essentials/cost-estimations-and-examples).
13+
Then navigate into your project's directory that you downloaded from ICP Ninja.
9414

95-
Cycles can be obtained through [converting ICP tokens into cycles using `dfx`](https://internetcomputer.org/docs/building-apps/developer-tools/dfx/dfx-cycles#dfx-cycles-convert).
15+
### 2. Deploy locally
9616

97-
### 6. Deploy to the mainnet.
98-
99-
Once you have cycles, run the command:
100-
101-
```
102-
103-
dfx deploy --network ic
17+
Start the local network and deploy the project:
10418

19+
```bash
20+
icp network start -d
21+
icp deploy
10522
```
10623

107-
After your project has been deployed to the mainnet, it will continuously require cycles to pay for the resources it uses. You will need to [top up](https://internetcomputer.org/docs/building-apps/canister-management/topping-up) your project's canisters or set up automatic cycles management through a service such as [CycleOps](https://cycleops.dev/).
108-
109-
> If your project's canisters run out of cycles, they will be removed from the network.
110-
11124
## Additional examples
11225

11326
Additional code examples and sample applications can be found in the [DFINITY examples repo](https://github.com/dfinity/examples).

rust/hello_world/README.md

Lines changed: 60 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,77 @@
11
# Hello, world!
22

3-
"Hello, world!" projects are a common starting point for developers learning new languages or platforms, as it provides a simple demonstration of how a programming language can be written for an application.
3+
[View this sample's code on GitHub](https://github.com/dfinity/examples/tree/master/rust/hello_world)
4+
5+
## Overview
6+
7+
This example demonstrates a simple "Hello, world!" application for ICP with both a Rust backend canister and a frontend UI.
8+
9+
The backend canister stores a customizable greeting prefix (default: "Hello, ") in stable memory, and exposes two methods:
10+
11+
- `set_greeting(prefix)` — updates the greeting prefix (persisted across canister upgrades).
12+
- `greet(name)` — returns the greeting combined with the given name (e.g., "Hello, World!").
13+
14+
The frontend provides a simple form where users can enter their name and receive a personalized greeting from the backend canister.
15+
16+
## Project structure
17+
18+
The `/backend` folder contains the Rust canister source code. The `/frontend` folder contains web assets for the application's user interface. The user interface is written with plain JavaScript, but any frontend framework can be used.
419

520
## Deploying from ICP Ninja
621

7-
When viewing this project in ICP Ninja, you can deploy it directly to the mainnet for free by clicking "Run" in the upper right corner. Open this project in ICP Ninja:
22+
This example can be deployed directly from [ICP Ninja](https://icp.ninja), a browser-based IDE for ICP. To continue developing locally after deploying from ICP Ninja, see [BUILD.md](BUILD.md).
23+
24+
[![Open in ICP Ninja](https://icp.ninja/assets/open.svg)](https://icp.ninja/i?g=https://github.com/dfinity/examples/rust/hello_world)
25+
26+
> **Note:** ICP Ninja currently uses `dfx` under the hood, which is why this example includes a `dfx.json` configuration file. `dfx` is the legacy CLI, being superseded by [icp-cli](https://cli.icp.build), which is what developers should use for local development.
27+
28+
## Build and deploy from the command line
29+
30+
### Prerequisites
831

9-
[![](https://icp.ninja/assets/open.svg)](https://icp.ninja/i?g=https://github.com/dfinity/examples/rust/hello_world)
32+
- [x] Install [Node.js](https://nodejs.org/en/download/)
33+
- [x] Install [icp-cli](https://cli.icp.build): `npm install -g @icp-sdk/icp-cli @icp-sdk/ic-wasm`
1034

11-
## Build and deploy from the command-line
35+
### Install
1236

13-
### 1. [Download and install the IC SDK.](https://internetcomputer.org/docs/building-apps/getting-started/install)
37+
Clone the example project:
1438

15-
### 2. Download your project from ICP Ninja using the 'Download files' button on the upper left corner, or [clone the GitHub examples repository.](https://github.com/dfinity/examples/)
39+
```bash
40+
git clone https://github.com/dfinity/examples
41+
cd examples/rust/hello_world
42+
```
43+
44+
### Deployment
45+
46+
Start the local network:
1647

17-
### 3. Navigate into the project's directory.
48+
```bash
49+
icp network start -d
50+
```
1851

19-
### 4. Deploy the project to your local environment:
52+
Deploy the canisters:
2053

54+
```bash
55+
icp deploy
2156
```
22-
dfx start --background --clean && dfx deploy
57+
58+
Stop the local network when done:
59+
60+
```bash
61+
icp network stop
62+
```
63+
64+
## Updating the Candid interface
65+
66+
The `backend/backend.did` file defines the backend canister's public interface. The frontend TypeScript bindings are auto-generated from this file during the frontend build.
67+
68+
If you modify the backend's public API, rebuild the canister and regenerate the `.did` file:
69+
70+
```bash
71+
icp build backend
72+
candid-extractor target/wasm32-unknown-unknown/release/backend.wasm > backend/backend.did
2373
```
2474

2575
## Security considerations and best practices
2676

27-
If you base your application on this example, it is recommended that you familiarize yourself with and adhere to the [security best practices](https://internetcomputer.org/docs/building-apps/security/overview) for developing on ICP. This example may not implement all the best practices.
77+
If you base your application on this example, it is recommended that you familiarize yourself with and adhere to the [security best practices](https://docs.internetcomputer.org/building-apps/security/overview) for developing on ICP. This example may not implement all the best practices.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
service : { greet : (text) -> (text) query; set_greeting : (text) -> () }

rust/hello_world/frontend/index.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
</style>
2020
<script type="module">
2121
// Import the backend actor
22-
import { backend } from 'declarations/backend';
22+
import { backend } from './src/actor.js';
2323
// Add an event listener to the form
2424
document.querySelector('form').addEventListener('submit', async (e) => {
2525
e.preventDefault();

rust/hello_world/frontend/package.json

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,15 @@
33
"private": true,
44
"type": "module",
55
"scripts": {
6-
"prebuild": "npm i --include=dev && dfx generate backend",
6+
"prebuild": "npm i --include=dev",
77
"build": "vite build",
88
"dev": "vite"
99
},
1010
"dependencies": {
11-
"@dfinity/agent": "2.2.0"
11+
"@icp-sdk/core": "~5.0.0"
1212
},
1313
"devDependencies": {
14-
"vite": "5.4.11",
15-
"vite-plugin-environment": "1.1.3"
14+
"@icp-sdk/bindgen": "~0.2.2",
15+
"vite": "5.4.11"
1616
}
1717
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import { safeGetCanisterEnv } from "@icp-sdk/core/agent/canister-env";
2+
import { createActor } from "./bindings/backend";
3+
4+
// The ic_env cookie is set by the asset canister (SDK ≥0.30.2) on all HTML
5+
// responses. It contains the replica root key and any PUBLIC_* canister
6+
// environment variables. In dev mode the vite dev server sets the same cookie
7+
// via Set-Cookie header (see vite.config.js).
8+
const canisterEnv = safeGetCanisterEnv();
9+
10+
// Resolve canister ID: cookie (icp-cli + dev server) → env var (dfx build-time)
11+
const canisterId =
12+
canisterEnv?.["PUBLIC_CANISTER_ID:backend"] ??
13+
process.env.CANISTER_ID_BACKEND;
14+
15+
if (!canisterId) {
16+
throw new Error(
17+
"Canister ID for 'backend' not found. Run 'icp deploy' or 'dfx deploy' first."
18+
);
19+
}
20+
21+
export const backend = createActor(canisterId, {
22+
agentOptions: {
23+
host: window.location.origin,
24+
rootKey: canisterEnv?.IC_ROOT_KEY,
25+
},
26+
});
Lines changed: 83 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,86 @@
1-
import { defineConfig } from 'vite';
2-
import { fileURLToPath, URL } from 'url';
3-
import environment from 'vite-plugin-environment';
1+
import { defineConfig, loadEnv } from "vite";
2+
import { execSync } from "child_process";
3+
import { icpBindgen } from "@icp-sdk/bindgen/plugins/vite";
44

5-
export default defineConfig({
6-
base: './',
7-
plugins: [environment('all', { prefix: 'CANISTER_' }), environment('all', { prefix: 'DFX_' })],
8-
envDir: '../',
9-
define: {
10-
'process.env': process.env
11-
},
12-
optimizeDeps: {
13-
esbuildOptions: {
14-
define: {
15-
global: 'globalThis'
16-
}
17-
}
18-
},
19-
resolve: {
20-
alias: [
21-
{
22-
find: 'declarations',
23-
replacement: fileURLToPath(new URL('../src/declarations', import.meta.url))
24-
}
25-
]
26-
},
27-
server: {
28-
proxy: {
29-
'/api': {
30-
target: 'http://127.0.0.1:4943',
31-
changeOrigin: true
32-
}
5+
function getDevServerConfig() {
6+
// Try icp-cli first
7+
try {
8+
const canisterId = execSync("icp canister status backend -e local -i", {
9+
encoding: "utf-8",
10+
stdio: "pipe",
11+
}).trim();
12+
const networkStatus = JSON.parse(
13+
execSync("icp network status --json", {
14+
encoding: "utf-8",
15+
stdio: "pipe",
16+
})
17+
);
18+
return {
19+
headers: {
20+
"Set-Cookie": `ic_env=${encodeURIComponent(
21+
`ic_root_key=${networkStatus.root_key}&PUBLIC_CANISTER_ID:backend=${canisterId}`
22+
)}; SameSite=Lax;`,
23+
},
24+
proxy: {
25+
"/api": { target: "http://127.0.0.1:8000", changeOrigin: true },
26+
},
27+
};
28+
} catch {}
29+
30+
// Try dfx
31+
try {
32+
const pingResult = JSON.parse(
33+
execSync("dfx ping", { encoding: "utf-8", stdio: "pipe" })
34+
);
35+
const rootKeyHex = Buffer.from(pingResult.root_key).toString("hex");
36+
const canisterId = execSync("dfx canister id backend", {
37+
encoding: "utf-8",
38+
stdio: "pipe",
39+
}).trim();
40+
return {
41+
headers: {
42+
"Set-Cookie": `ic_env=${encodeURIComponent(
43+
`ic_root_key=${rootKeyHex}&PUBLIC_CANISTER_ID:backend=${canisterId}`
44+
)}; SameSite=Lax;`,
45+
},
46+
proxy: {
47+
"/api": {
48+
target: "http://127.0.0.1:4943",
49+
changeOrigin: true,
50+
},
51+
},
52+
host: "127.0.0.1",
53+
};
54+
} catch {}
55+
56+
throw new Error(
57+
"No local network running. Start with:\n icp network start -d && icp deploy\nor:\n dfx start --background && dfx deploy"
58+
);
59+
}
60+
61+
export default defineConfig(({ command, mode }) => {
62+
// dfx generates ../.env with CANISTER_ID_* vars on deploy. Bake them into the
63+
// bundle so actor.js can fall back to them when the ic_env cookie does not
64+
// contain canister IDs (dfx does not inject PUBLIC_CANISTER_ID:* env vars
65+
// into the asset canister, unlike icp-cli).
66+
const env = loadEnv(mode, "..", ["CANISTER_"]);
67+
68+
return {
69+
base: "./",
70+
plugins: [
71+
icpBindgen({
72+
didFile: "../backend/backend.did",
73+
outDir: "./src/bindings",
74+
}),
75+
],
76+
define: {
77+
"process.env.CANISTER_ID_BACKEND": JSON.stringify(
78+
env.CANISTER_ID_BACKEND
79+
),
80+
},
81+
optimizeDeps: {
82+
esbuildOptions: { define: { global: "globalThis" } },
3383
},
34-
host: '127.0.0.1'
35-
}
84+
server: command === "serve" ? getDevServerConfig() : undefined,
85+
};
3686
});

0 commit comments

Comments
 (0)