diff --git a/.github/workflows/daily_planner.yml b/.github/workflows/daily_planner.yml new file mode 100644 index 000000000..3c0c06622 --- /dev/null +++ b/.github/workflows/daily_planner.yml @@ -0,0 +1,29 @@ +name: daily_planner + +on: + push: + branches: + - master + pull_request: + paths: + - motoko/daily_planner/** + - .github/workflows/daily_planner.yml + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + motoko-daily_planner: + runs-on: ubuntu-24.04 + container: ghcr.io/dfinity/icp-dev-env-motoko:0.3.2 + env: + ICP_CLI_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 + - name: Deploy and test + working-directory: motoko/daily_planner + run: | + icp network start -d + icp deploy + make test diff --git a/motoko/daily_planner/.devcontainer/devcontainer.json b/motoko/daily_planner/.devcontainer/devcontainer.json deleted file mode 100644 index ebb0b8bcc..000000000 --- a/motoko/daily_planner/.devcontainer/devcontainer.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "ICP Dev Environment", - "image": "ghcr.io/dfinity/icp-dev-env-slim:22", - "forwardPorts": [4943, 5173], - "portsAttributes": { - "4943": { - "label": "dfx", - "onAutoForward": "ignore" - }, - "5173": { - "label": "vite", - "onAutoForward": "openBrowser" - } - }, - "customizations": { - "vscode": { - "extensions": ["dfinity-foundation.vscode-motoko"] - } - } -} diff --git a/motoko/daily_planner/BUILD.md b/motoko/daily_planner/BUILD.md deleted file mode 100644 index 24cfcb754..000000000 --- a/motoko/daily_planner/BUILD.md +++ /dev/null @@ -1,113 +0,0 @@ -# Continue building locally - -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. - -To migrate your ICP Ninja project off of the web browser and develop it locally, follow these steps. - -### 1. Install developer tools. - -You can install the developer tools natively or use Dev Containers. - -#### Option 1: Natively install developer tools - -> Installing `dfx` natively is currently only supported on macOS and Linux systems. On Windows, it is recommended to use the Dev Containers option. - -1. Install `dfx` with the following command: - -``` - -sh -ci "$(curl -fsSL https://internetcomputer.org/install.sh)" - -``` - -> On Apple Silicon (e.g., Apple M1 chip), make sure you have Rosetta installed (`softwareupdate --install-rosetta`). - -2. [Install NodeJS](https://nodejs.org/en/download/package-manager). - -3. For Rust projects, you will also need to: - -- Install [Rust](https://doc.rust-lang.org/cargo/getting-started/installation.html#install-rust-and-cargo): `curl https://sh.rustup.rs -sSf | sh` - -- Install [candid-extractor](https://crates.io/crates/candid-extractor): `cargo install candid-extractor` - -4. For Motoko projects, you will also need to: - -- Install the Motoko package manager [Mops](https://docs.mops.one/quick-start#2-install-mops-cli): `npm i -g ic-mops` - -Lastly, navigate into your project's directory that you downloaded from ICP Ninja. - -#### Option 2: Dev Containers - -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/). - -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). - -> 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. - -### 2. Start the local development environment. - -``` -dfx start --background -``` - -### 3. Create a local developer identity. - -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. - -To create a new identity, run the commands: - -``` - -dfx identity new IDENTITY_NAME - -dfx identity use IDENTITY_NAME - -``` - -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. - -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. - -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. - -[Learn more about ICP developer identities](https://internetcomputer.org/docs/building-apps/getting-started/identities). - -### 4. Deploy the project locally. - -Deploy your project to your local developer environment with: - -``` -npm install -dfx deploy - -``` - -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. - -### 5. Obtain cycles. - -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. - -> 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. - -> Learn how much a project may cost by using the [pricing calculator](https://internetcomputer.org/docs/building-apps/essentials/cost-estimations-and-examples). - -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). - -### 6. Deploy to the mainnet. - -Once you have cycles, run the command: - -``` - -dfx deploy --network ic - -``` - -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/). - -> If your project's canisters run out of cycles, they will be removed from the network. - -## Additional examples - -Additional code examples and sample applications can be found in the [DFINITY examples repo](https://github.com/dfinity/examples). diff --git a/motoko/daily_planner/Makefile b/motoko/daily_planner/Makefile new file mode 100644 index 000000000..5e8d4fa4f --- /dev/null +++ b/motoko/daily_planner/Makefile @@ -0,0 +1,39 @@ +.PHONY: test + +test: + @echo "=== Test 1/6: getDayData returns null for a date with no notes ===" + @result=$$(icp canister call backend getDayData '("2000-01-15")') && \ + echo "$$result" && \ + echo "$$result" | grep -q 'null' && \ + echo "PASS" || (echo "FAIL" && exit 1) + + @echo "=== Test 2/6: addNote returns ok result ===" + @result=$$(icp canister call backend addNote '("2000-01-15", "Buy groceries")') && \ + echo "$$result" && \ + echo "$$result" | grep -q 'ok' && \ + echo "PASS" || (echo "FAIL" && exit 1) + + @echo "=== Test 3/6: getDayData returns stored note ===" + @result=$$(icp canister call backend getDayData '("2000-01-15")') && \ + echo "$$result" && \ + echo "$$result" | grep -q 'Buy groceries' && \ + echo "PASS" || (echo "FAIL" && exit 1) + + @echo "=== Test 4/6: getMonthData returns entry for the stored month ===" + @result=$$(icp canister call backend getMonthData '(2000, 1)') && \ + echo "$$result" && \ + echo "$$result" | grep -q 'Buy groceries' && \ + echo "PASS" || (echo "FAIL" && exit 1) + + @echo "=== Test 5/6: completeNote marks note as completed ===" + @icp canister call backend completeNote '("2000-01-15", 0)' && \ + result=$$(icp canister call backend getDayData '("2000-01-15")') && \ + echo "$$result" && \ + echo "$$result" | grep -q 'isCompleted = true' && \ + echo "PASS" || (echo "FAIL" && exit 1) + + @echo "=== Test 6/6: getMonthData returns empty list for a different month ===" + @result=$$(icp canister call backend getMonthData '(1999, 12)') && \ + echo "$$result" && \ + echo "$$result" | grep -q 'vec {}' && \ + echo "PASS" || (echo "FAIL" && exit 1) diff --git a/motoko/daily_planner/README.md b/motoko/daily_planner/README.md index 9216c111e..a1506ce34 100644 --- a/motoko/daily_planner/README.md +++ b/motoko/daily_planner/README.md @@ -1,25 +1,42 @@ -# Daily planner +# Daily Planner -Daily planner features a monthly calender that can be used to track daily activities, appointments, or tasks. Data for each task is stored onchain. For each day, a historic fact can be queried using HTTPS outcalls, which is a feature that allows ICP canisters to obtain data from external sources. +Daily Planner is a full-stack ICP example featuring a monthly calendar that tracks daily notes and tasks stored on the network. For each day, a historic fact can be fetched from an external API using HTTPS outcalls, demonstrating how ICP canisters can access data from external services. -## Deploying from ICP Ninja +## Build and deploy from the command line -[![](https://icp.ninja/assets/open.svg)](https://icp.ninja/editor?g=https://github.com/dfinity/examples/tree/master/motoko/daily_planner) +### Prerequisites -## Build and deploy from the command-line +- Node.js +- icp-cli: `npm install -g @icp-sdk/icp-cli @icp-sdk/ic-wasm` -### 1. [Download and install the IC SDK.](https://internetcomputer.org/docs/building-apps/getting-started/install) +### Install -### 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/) +```bash +git clone https://github.com/dfinity/examples +cd examples/motoko/daily_planner +``` + +### Deploy and test -### 3. Navigate into the project's directory. +```bash +icp network start -d +icp deploy +make test +icp network stop +``` -### 4. Deploy the project to your local environment: +To run the frontend in development mode with hot reload: +```bash +npm run dev ``` -dfx start --background --clean && dfx deploy + +## Updating the Candid interface + +```bash +$(mops toolchain bin moc) --idl -o backend/backend.did backend/app.mo ``` ## Security considerations and best practices -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. +Refer to the [security best practices](https://docs.internetcomputer.org/guides/security/overview) for information on security and best practices for your ICP app. diff --git a/motoko/daily_planner/backend/app.mo b/motoko/daily_planner/backend/app.mo index cfae987ad..afb57f31f 100644 --- a/motoko/daily_planner/backend/app.mo +++ b/motoko/daily_planner/backend/app.mo @@ -8,7 +8,8 @@ import Result "mo:core/Result"; import JSON "mo:json"; import HashMap "mo:map/Map"; import { thash } "mo:map/Map"; -import IC "ic:aaaaa-aa"; +import { ic } "mo:ic"; +import IC "mo:ic/Types"; persistent actor DailyPlanner { // General types used by the planner @@ -43,9 +44,9 @@ persistent actor DailyPlanner { // Query function to get data for an entire month. // Returns a public query func getMonthData(year : Nat, month : Nat) : async [(Text, DayData)] { - let monthPrefix = year.toText() # "-" # month.toText() # "-"; - Iter.filter( - HashMap.entries(dayData), + let monthStr = if (month < 10) { "0" # month.toText() } else { month.toText() }; + let monthPrefix = year.toText() # "-" # monthStr # "-"; + HashMap.entries(dayData).filter( func((k, _) : (Text, DayData)) : Bool { k.startsWith(#text monthPrefix); }, @@ -121,9 +122,9 @@ persistent actor DailyPlanner { // "transform" is used to specify how the HTTP response is processed before consensus tries to agree on a response. // This is useful to e.g. filter out timestamps out of headers that will be different across the responses the different replicas receive. // You can read more about it here: https://internetcomputer.org/docs/current/developer-docs/smart-contracts/advanced-features/https-outcalls/https-outcalls-how-to-use - let http_request : IC.http_request_args = { + let http_request : IC.HttpRequestArgs = { // API must support IPv6 - url = "https://byabbe.se/on-this-day/" # Nat.toText(month) # "/" # Nat.toText(day) # "/events.json"; + url = "https://byabbe.se/on-this-day/" # month.toText() # "/" # day.toText() # "/events.json"; max_response_bytes = null; //optional for request headers = []; body = null; //optional for request @@ -138,10 +139,10 @@ persistent actor DailyPlanner { // Perform HTTPS outcall using roughly 100B cycles. // See https outcall cost calculator: https://7joko-hiaaa-aaaal-ajz7a-cai.icp0.io. // Unused cycles are returned. - let http_response : IC.http_request_result = await (with cycles = 100_000_000_000) IC.http_request(http_request); + let http_response : IC.HttpRequestResult = await (with cycles = 100_000_000_000) ic.http_request(http_request); // Parse response into JSON - let decoded_text : Text = switch (Text.decodeUtf8(http_response.body)) { + let decoded_text : Text = switch (http_response.body.decodeUtf8()) { case (null) { "No value returned" }; case (?y) { y }; }; @@ -186,8 +187,8 @@ persistent actor DailyPlanner { // Transforms the raw HTTPS call response to an HttpResponsePayload on which the nodes can run consensus on. public query func transform({ context : Blob; - response : IC.http_request_result; - }) : async IC.http_request_result { + response : IC.HttpRequestResult; + }) : async IC.HttpRequestResult { { response with headers = []; // not interested in the headers }; diff --git a/motoko/daily_planner/backend/backend.did b/motoko/daily_planner/backend/backend.did new file mode 100644 index 000000000..1cd12c1f2 --- /dev/null +++ b/motoko/daily_planner/backend/backend.did @@ -0,0 +1,27 @@ +type Note = record { + id : nat; + content : text; + isCompleted : bool; +}; + +type OnThisDay = record { + title : text; + year : text; + wikiLink : text; +}; + +type DayData = record { + notes : vec Note; + onThisDay : opt OnThisDay; +}; + +type AddNoteResult = variant { ok : text; err : text }; + +service : { + getDayData : (date : text) -> (opt DayData) query; + getMonthData : (year : nat, month : nat) -> (vec record { text; DayData }) query; + addNote : (date : text, content : text) -> (AddNoteResult); + completeNote : (date : text, noteId : nat) -> (); + fetchAndStoreOnThisDay : (date : text) -> (variant { ok : text; err : text }); + transform : (record { context : blob; response : record { status : nat; headers : vec record { name : text; value : text }; body : blob } }) -> (record { status : nat; headers : vec record { name : text; value : text }; body : blob }) query; +}; diff --git a/motoko/daily_planner/dfx.json b/motoko/daily_planner/dfx.json deleted file mode 100644 index d073ee09f..000000000 --- a/motoko/daily_planner/dfx.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "canisters": { - "backend": { - "main": "backend/app.mo", - "type": "motoko", - "args": "--enhanced-orthogonal-persistence" - }, - "frontend": { - "dependencies": ["backend"], - "frontend": { - "entrypoint": "frontend/index.html" - }, - "source": ["frontend/dist"], - "type": "assets" - } - }, - "output_env_file": ".env", - "defaults": { - "build": { - "packtool": "mops sources" - } - } -} diff --git a/motoko/daily_planner/frontend/package.json b/motoko/daily_planner/frontend/package.json index e618cdc5a..859836e9b 100644 --- a/motoko/daily_planner/frontend/package.json +++ b/motoko/daily_planner/frontend/package.json @@ -3,7 +3,7 @@ "private": true, "type": "module", "scripts": { - "prebuild": "npm i --include=dev && dfx generate backend", + "prebuild": "npm i --include=dev", "build": "vite build", "dev": "vite" }, @@ -13,10 +13,10 @@ "react-dom": "18.3.1" }, "devDependencies": { + "@icp-sdk/bindgen": "~0.2.2", "@types/react": "18.3.12", "@types/react-dom": "18.3.1", "@vitejs/plugin-react": "4.3.3", - "vite": "5.4.11", - "vite-plugin-environment": "1.1.3" + "vite": "5.4.11" } } diff --git a/motoko/daily_planner/frontend/src/App.jsx b/motoko/daily_planner/frontend/src/App.jsx index 01af4c0db..349a47fa3 100644 --- a/motoko/daily_planner/frontend/src/App.jsx +++ b/motoko/daily_planner/frontend/src/App.jsx @@ -1,6 +1,6 @@ import React, { useEffect, useState } from 'react'; import '../index.css'; -import { backend } from 'declarations/backend'; +import { backend } from './actor'; const App = () => { const [currentDate, setCurrentDate] = useState(new Date()); diff --git a/motoko/daily_planner/frontend/src/actor.js b/motoko/daily_planner/frontend/src/actor.js new file mode 100644 index 000000000..5d2f0478a --- /dev/null +++ b/motoko/daily_planner/frontend/src/actor.js @@ -0,0 +1,26 @@ +import { safeGetCanisterEnv } from "@icp-sdk/core/agent/canister-env"; +import { createActor } from "./bindings/backend"; + +// The ic_env cookie is set by the asset canister (SDK >=0.30.2) on all HTML +// responses. It contains the replica root key and any PUBLIC_* canister +// environment variables. In dev mode the vite dev server sets the same cookie +// via Set-Cookie header (see vite.config.js). +const canisterEnv = safeGetCanisterEnv(); + +// Resolve canister ID: cookie (icp-cli + dev server) -> env var (dfx build-time) +const canisterId = + canisterEnv?.["PUBLIC_CANISTER_ID:backend"] ?? + process.env.CANISTER_ID_BACKEND; + +if (!canisterId) { + throw new Error( + "Canister ID for 'backend' not found. Run 'icp deploy' or 'dfx deploy' first." + ); +} + +export const backend = createActor(canisterId, { + agentOptions: { + host: window.location.origin, + rootKey: canisterEnv?.IC_ROOT_KEY, + }, +}); diff --git a/motoko/daily_planner/frontend/vite.config.js b/motoko/daily_planner/frontend/vite.config.js index f9e04a9a9..de551a102 100644 --- a/motoko/daily_planner/frontend/vite.config.js +++ b/motoko/daily_planner/frontend/vite.config.js @@ -1,37 +1,88 @@ -import react from '@vitejs/plugin-react'; -import { defineConfig } from 'vite'; -import { fileURLToPath, URL } from 'url'; -import environment from 'vite-plugin-environment'; +import { defineConfig, loadEnv } from "vite"; +import { execSync } from "child_process"; +import react from "@vitejs/plugin-react"; +import { icpBindgen } from "@icp-sdk/bindgen/plugins/vite"; -export default defineConfig({ - base: './', - plugins: [react(), environment('all', { prefix: 'CANISTER_' }), environment('all', { prefix: 'DFX_' })], - envDir: '../', - define: { - 'process.env': process.env - }, - optimizeDeps: { - esbuildOptions: { - define: { - global: 'globalThis' - } - } - }, - resolve: { - alias: [ - { - find: 'declarations', - replacement: fileURLToPath(new URL('../src/declarations', import.meta.url)) - } - ] - }, - server: { - proxy: { - '/api': { - target: 'http://127.0.0.1:4943', - changeOrigin: true - } +function getDevServerConfig() { + // Try icp-cli first + try { + const canisterId = execSync("icp canister status backend -e local -i", { + encoding: "utf-8", + stdio: "pipe", + }).trim(); + const networkStatus = JSON.parse( + execSync("icp network status --json", { + encoding: "utf-8", + stdio: "pipe", + }) + ); + return { + headers: { + "Set-Cookie": `ic_env=${encodeURIComponent( + `ic_root_key=${networkStatus.root_key}&PUBLIC_CANISTER_ID:backend=${canisterId}` + )}; SameSite=Lax;`, + }, + proxy: { + "/api": { target: "http://127.0.0.1:8000", changeOrigin: true }, + }, + }; + } catch {} + + // Try dfx + try { + const pingResult = JSON.parse( + execSync("dfx ping", { encoding: "utf-8", stdio: "pipe" }) + ); + const rootKeyHex = Buffer.from(pingResult.root_key).toString("hex"); + const canisterId = execSync("dfx canister id backend", { + encoding: "utf-8", + stdio: "pipe", + }).trim(); + return { + headers: { + "Set-Cookie": `ic_env=${encodeURIComponent( + `ic_root_key=${rootKeyHex}&PUBLIC_CANISTER_ID:backend=${canisterId}` + )}; SameSite=Lax;`, + }, + proxy: { + "/api": { + target: "http://127.0.0.1:4943", + changeOrigin: true, + }, + }, + host: "127.0.0.1", + }; + } catch {} + + throw new Error( + "No local network running. Start with:\n icp network start -d && icp deploy\nor:\n dfx start --background && dfx deploy" + ); +} + +export default defineConfig(({ command, mode }) => { + // dfx generates ../.env with CANISTER_ID_* vars on deploy. Bake them into the + // bundle so actor.js can fall back to them when the ic_env cookie does not + // contain canister IDs (dfx does not inject PUBLIC_CANISTER_ID:* env vars + // into the asset canister, unlike icp-cli). + const env = loadEnv(mode, "..", ["CANISTER_"]); + + return { + base: "./", + plugins: [ + react(), + icpBindgen({ + didFile: "../backend/backend.did", + outDir: "./src/bindings", + }), + ], + define: { + "process.env.CANISTER_ID_BACKEND": JSON.stringify( + env.CANISTER_ID_BACKEND + ), + }, + optimizeDeps: { + esbuildOptions: { define: { global: "globalThis" } }, }, - host: '127.0.0.1' - } + server: command === "serve" ? getDevServerConfig() : undefined, + }; }); diff --git a/motoko/daily_planner/icp.yaml b/motoko/daily_planner/icp.yaml new file mode 100644 index 000000000..bd053999d --- /dev/null +++ b/motoko/daily_planner/icp.yaml @@ -0,0 +1,13 @@ +canisters: + - name: backend + recipe: + type: "@dfinity/motoko@v5.0.0" + + - name: frontend + recipe: + type: "@dfinity/asset-canister@v2.2.1" + configuration: + dir: frontend/dist + build: + - npm install --prefix frontend + - npm run build --prefix frontend diff --git a/motoko/daily_planner/mops.toml b/motoko/daily_planner/mops.toml index c0487992c..11df1f44a 100644 --- a/motoko/daily_planner/mops.toml +++ b/motoko/daily_planner/mops.toml @@ -1,15 +1,18 @@ -# Motoko dependencies (https://mops.one/) - [toolchain] -moc = "1.5.1" +moc = "1.9.0" [dependencies] -core = "2.4.0" +core = "2.5.0" +ic = "4.0.0" json = "1.0.0" map = "9.0.1" [moc] -# M0236: use context dot notation (e.g. map.get(k) instead of Map.get(map, compare, k)) -# M0237: redundant explicit implicit arguments (e.g. Nat.compare is inferred automatically) -# M0223: redundant type instantiation (e.g. Array.tabulate instead of Array.tabulate) -args = ["-W", "M0236", "-W", "M0237", "-W", "M0223"] +# M0236: use context dot notation +# M0237: redundant explicit implicit arguments +# M0223: redundant type instantiation +args = ["--default-persistent-actors", "-W=M0236,M0237,M0223"] + +[canisters.backend] +main = "backend/app.mo" +candid = "backend/backend.did" diff --git a/motoko/daily_planner/package.json b/motoko/daily_planner/package.json index b50e79683..199fc1ae9 100644 --- a/motoko/daily_planner/package.json +++ b/motoko/daily_planner/package.json @@ -1,5 +1,5 @@ { - "name": "example", + "name": "daily_planner", "scripts": { "build": "npm run build --workspaces --if-present", "prebuild": "npm run prebuild --workspaces --if-present",