From 4af79cd4ad8467cce7ff7f83038001e6813e1891 Mon Sep 17 00:00:00 2001 From: dprats Date: Thu, 5 Aug 2021 11:27:45 -0700 Subject: [PATCH 1/4] create markdown versions of every asciidoc file --- modules/ROOT/nav.xml | 494 +++++++ modules/ROOT/pages/download.xml | 49 + modules/ROOT/pages/http-middleware.xml | 156 ++ modules/ROOT/pages/index.xml | 91 ++ modules/ROOT/pages/search.xml | 23 + modules/ROOT/pages/support.xml | 32 + modules/ROOT/pages/videos-tutorials.xml | 162 +++ modules/developers-guide/dev-nav.xml | 121 ++ .../developers-guide/examples/candid-ui.xml | 57 + .../pages/about-this-guide.xml | 13 + .../pages/basic-syntax-rules.xml | 732 ++++++++++ .../developers-guide/pages/cli-reference.xml | 70 + .../pages/cli-reference/dfx-bootstrap.xml | 104 ++ .../pages/cli-reference/dfx-build.xml | 119 ++ .../pages/cli-reference/dfx-cache.xml | 258 ++++ .../pages/cli-reference/dfx-canister.xml | 1287 +++++++++++++++++ .../pages/cli-reference/dfx-config.xml | 119 ++ .../pages/cli-reference/dfx-deploy.xml | 130 ++ .../pages/cli-reference/dfx-envars.xml | 50 + .../pages/cli-reference/dfx-help.xml | 46 + .../pages/cli-reference/dfx-identity.xml | 673 +++++++++ .../pages/cli-reference/dfx-ledger.xml | 601 ++++++++ .../pages/cli-reference/dfx-new.xml | 90 ++ .../pages/cli-reference/dfx-parent.xml | 204 +++ .../pages/cli-reference/dfx-ping.xml | 80 + .../pages/cli-reference/dfx-replica.xml | 76 + .../pages/cli-reference/dfx-start.xml | 92 ++ .../pages/cli-reference/dfx-stop.xml | 58 + .../pages/cli-reference/dfx-upgrade.xml | 81 ++ .../pages/cli-reference/dfx-wallet.xml | 855 +++++++++++ .../pages/computation-and-storage-costs.xml | 159 ++ .../pages/concepts/canisters-code.xml | 182 +++ .../pages/concepts/concepts-intro.xml | 29 + .../pages/concepts/data-centers.xml | 58 + .../pages/concepts/governance.xml | 31 + .../pages/concepts/nodes-subnets.xml | 35 + .../pages/concepts/tokens-cycles.xml | 104 ++ .../pages/concepts/what-is-IC.xml | 58 + .../pages/customize-projects.xml | 55 + .../developers-guide/pages/default-wallet.xml | 386 +++++ .../developers-guide/pages/design-apps.xml | 57 + modules/developers-guide/pages/glossary.xml | 112 ++ .../pages/install-upgrade-remove.xml | 117 ++ .../pages/lang-service-ide.xml | 102 ++ .../developers-guide/pages/sample-apps.xml | 124 ++ modules/developers-guide/pages/sdk-guide.xml | 32 + .../pages/troubleshooting.xml | 143 ++ .../pages/tutorials-intro.xml | 60 + .../pages/tutorials/access-control.xml | 400 +++++ .../pages/tutorials/at-a-glance.xml | 35 + .../pages/tutorials/calculator.xml | 233 +++ .../pages/tutorials/counter-tutorial.xml | 224 +++ .../pages/tutorials/custom-frontend.xml | 364 +++++ .../pages/tutorials/define-an-actor.xml | 230 +++ .../pages/tutorials/explore-templates.xml | 434 ++++++ .../pages/tutorials/hello-location.xml | 241 +++ .../pages/tutorials/intercanister-calls.xml | 414 ++++++ .../pages/tutorials/multiple-actors.xml | 235 +++ .../tutorials/multiple-factorial-actors.xml | 218 +++ .../pages/tutorials/my-contacts.xml | 313 ++++ .../pages/tutorials/phonebook.xml | 195 +++ .../pages/tutorials/scalability-cancan.xml | 110 ++ .../pages/tutorials/simple-cycles.xml | 232 +++ .../developers-guide/pages/webpack-config.xml | 246 ++++ .../pages/work-with-languages.xml | 383 +++++ .../pages/working-with-canisters.xml | 285 ++++ modules/integration/integration-nav.xml | 19 + .../integration/pages/ledger-quick-start.xml | 398 +++++ modules/introduction/pages/welcome.xml | 70 + .../languages/pages/languages-overview.xml | 58 + .../languages/pages/motoko-at-a-glance.xml | 579 ++++++++ modules/operators-guide/ops-nav.xml | 28 + modules/operators-guide/pages/ops-guide.xml | 13 + modules/quickstart/examples/vscode-plugin.xml | 32 + modules/quickstart/pages/local-quickstart.xml | 271 ++++ .../quickstart/pages/network-quickstart.xml | 385 +++++ modules/quickstart/pages/newcomers.xml | 130 ++ modules/quickstart/pages/quickstart-intro.xml | 61 + modules/release-notes/pages/0.6.20-rn.xml | 85 ++ modules/release-notes/pages/0.6.21-rn.xml | 60 + modules/release-notes/pages/0.6.22-rn.xml | 78 + modules/release-notes/pages/0.6.23-rn.xml | 15 + modules/release-notes/pages/0.6.24-rn.xml | 145 ++ modules/release-notes/pages/0.6.25-rn.xml | 40 + modules/release-notes/pages/0.6.26-rn.xml | 57 + modules/release-notes/pages/0.7.0-rn.xml | 171 +++ modules/release-notes/pages/0.7.1-rn.xml | 67 + modules/release-notes/pages/0.7.2-rn.xml | 22 + modules/release-notes/pages/0.7.7-rn.xml | 22 + modules/release-notes/pages/0.8.0-rn.xml | 92 ++ .../release-notes/pages/sdk-release-notes.xml | 49 + .../pages/custody-options-intro.xml | 90 ++ .../pages/nns-app-quickstart.xml | 602 ++++++++ .../token-holders/pages/seed-donations.xml | 462 ++++++ .../pages/self-custody-quickstart.xml | 185 +++ 95 files changed, 17845 insertions(+) create mode 100644 modules/ROOT/nav.xml create mode 100644 modules/ROOT/pages/download.xml create mode 100644 modules/ROOT/pages/http-middleware.xml create mode 100644 modules/ROOT/pages/index.xml create mode 100644 modules/ROOT/pages/search.xml create mode 100644 modules/ROOT/pages/support.xml create mode 100644 modules/ROOT/pages/videos-tutorials.xml create mode 100644 modules/developers-guide/dev-nav.xml create mode 100644 modules/developers-guide/examples/candid-ui.xml create mode 100644 modules/developers-guide/pages/about-this-guide.xml create mode 100644 modules/developers-guide/pages/basic-syntax-rules.xml create mode 100644 modules/developers-guide/pages/cli-reference.xml create mode 100644 modules/developers-guide/pages/cli-reference/dfx-bootstrap.xml create mode 100644 modules/developers-guide/pages/cli-reference/dfx-build.xml create mode 100644 modules/developers-guide/pages/cli-reference/dfx-cache.xml create mode 100644 modules/developers-guide/pages/cli-reference/dfx-canister.xml create mode 100644 modules/developers-guide/pages/cli-reference/dfx-config.xml create mode 100644 modules/developers-guide/pages/cli-reference/dfx-deploy.xml create mode 100644 modules/developers-guide/pages/cli-reference/dfx-envars.xml create mode 100644 modules/developers-guide/pages/cli-reference/dfx-help.xml create mode 100644 modules/developers-guide/pages/cli-reference/dfx-identity.xml create mode 100644 modules/developers-guide/pages/cli-reference/dfx-ledger.xml create mode 100644 modules/developers-guide/pages/cli-reference/dfx-new.xml create mode 100644 modules/developers-guide/pages/cli-reference/dfx-parent.xml create mode 100644 modules/developers-guide/pages/cli-reference/dfx-ping.xml create mode 100644 modules/developers-guide/pages/cli-reference/dfx-replica.xml create mode 100644 modules/developers-guide/pages/cli-reference/dfx-start.xml create mode 100644 modules/developers-guide/pages/cli-reference/dfx-stop.xml create mode 100644 modules/developers-guide/pages/cli-reference/dfx-upgrade.xml create mode 100644 modules/developers-guide/pages/cli-reference/dfx-wallet.xml create mode 100644 modules/developers-guide/pages/computation-and-storage-costs.xml create mode 100644 modules/developers-guide/pages/concepts/canisters-code.xml create mode 100644 modules/developers-guide/pages/concepts/concepts-intro.xml create mode 100644 modules/developers-guide/pages/concepts/data-centers.xml create mode 100644 modules/developers-guide/pages/concepts/governance.xml create mode 100644 modules/developers-guide/pages/concepts/nodes-subnets.xml create mode 100644 modules/developers-guide/pages/concepts/tokens-cycles.xml create mode 100644 modules/developers-guide/pages/concepts/what-is-IC.xml create mode 100644 modules/developers-guide/pages/customize-projects.xml create mode 100644 modules/developers-guide/pages/default-wallet.xml create mode 100644 modules/developers-guide/pages/design-apps.xml create mode 100644 modules/developers-guide/pages/glossary.xml create mode 100644 modules/developers-guide/pages/install-upgrade-remove.xml create mode 100644 modules/developers-guide/pages/lang-service-ide.xml create mode 100644 modules/developers-guide/pages/sample-apps.xml create mode 100644 modules/developers-guide/pages/sdk-guide.xml create mode 100644 modules/developers-guide/pages/troubleshooting.xml create mode 100644 modules/developers-guide/pages/tutorials-intro.xml create mode 100644 modules/developers-guide/pages/tutorials/access-control.xml create mode 100644 modules/developers-guide/pages/tutorials/at-a-glance.xml create mode 100644 modules/developers-guide/pages/tutorials/calculator.xml create mode 100644 modules/developers-guide/pages/tutorials/counter-tutorial.xml create mode 100644 modules/developers-guide/pages/tutorials/custom-frontend.xml create mode 100644 modules/developers-guide/pages/tutorials/define-an-actor.xml create mode 100644 modules/developers-guide/pages/tutorials/explore-templates.xml create mode 100644 modules/developers-guide/pages/tutorials/hello-location.xml create mode 100644 modules/developers-guide/pages/tutorials/intercanister-calls.xml create mode 100644 modules/developers-guide/pages/tutorials/multiple-actors.xml create mode 100644 modules/developers-guide/pages/tutorials/multiple-factorial-actors.xml create mode 100644 modules/developers-guide/pages/tutorials/my-contacts.xml create mode 100644 modules/developers-guide/pages/tutorials/phonebook.xml create mode 100644 modules/developers-guide/pages/tutorials/scalability-cancan.xml create mode 100644 modules/developers-guide/pages/tutorials/simple-cycles.xml create mode 100644 modules/developers-guide/pages/webpack-config.xml create mode 100644 modules/developers-guide/pages/work-with-languages.xml create mode 100644 modules/developers-guide/pages/working-with-canisters.xml create mode 100644 modules/integration/integration-nav.xml create mode 100644 modules/integration/pages/ledger-quick-start.xml create mode 100644 modules/introduction/pages/welcome.xml create mode 100644 modules/languages/pages/languages-overview.xml create mode 100644 modules/languages/pages/motoko-at-a-glance.xml create mode 100644 modules/operators-guide/ops-nav.xml create mode 100644 modules/operators-guide/pages/ops-guide.xml create mode 100644 modules/quickstart/examples/vscode-plugin.xml create mode 100644 modules/quickstart/pages/local-quickstart.xml create mode 100644 modules/quickstart/pages/network-quickstart.xml create mode 100644 modules/quickstart/pages/newcomers.xml create mode 100644 modules/quickstart/pages/quickstart-intro.xml create mode 100644 modules/release-notes/pages/0.6.20-rn.xml create mode 100644 modules/release-notes/pages/0.6.21-rn.xml create mode 100644 modules/release-notes/pages/0.6.22-rn.xml create mode 100644 modules/release-notes/pages/0.6.23-rn.xml create mode 100644 modules/release-notes/pages/0.6.24-rn.xml create mode 100644 modules/release-notes/pages/0.6.25-rn.xml create mode 100644 modules/release-notes/pages/0.6.26-rn.xml create mode 100644 modules/release-notes/pages/0.7.0-rn.xml create mode 100644 modules/release-notes/pages/0.7.1-rn.xml create mode 100644 modules/release-notes/pages/0.7.2-rn.xml create mode 100644 modules/release-notes/pages/0.7.7-rn.xml create mode 100644 modules/release-notes/pages/0.8.0-rn.xml create mode 100644 modules/release-notes/pages/sdk-release-notes.xml create mode 100644 modules/token-holders/pages/custody-options-intro.xml create mode 100644 modules/token-holders/pages/nns-app-quickstart.xml create mode 100644 modules/token-holders/pages/seed-donations.xml create mode 100644 modules/token-holders/pages/self-custody-quickstart.xml diff --git a/modules/ROOT/nav.xml b/modules/ROOT/nav.xml new file mode 100644 index 000000000..472d4f91d --- /dev/null +++ b/modules/ROOT/nav.xml @@ -0,0 +1,494 @@ + + + +
+ +Untitled +2021-08-05 + + + +Introduction + + +For: First-Timers + + +For: Developers + + +For: Protocol Enthusiasts + + + + +Quick Start + + +Local Development + + +Network Deployment + + + + +Developer Docs + + +Getting Started + + +Introducing the SDK + + +Install, upgrade, or remove software + + +Release notes + + +0.8.0 + + +0.7.7 + + +0.7.2 + + +0.7.1 + + +0.7.0 + + +0.6.26 + + +0.6.25 + + +0.6.24 + + +0.6.23 + + +0.6.22 + + +0.6.21 + + +0.6.20 + + + + + + +Introducing DFX + + +DFX commands + + +DFX environment variables + + +Glossary + + + + + + +Building on the Internet Computer + + +Learn how to: + + +Develop software on the IC + + +Design apps + + +Manage projects + + +Manage canisters + + +Use the default cycles wallet + + +Explore the default project + + +Query using an actor + + +Pass text arguments + + +Increment a natural number + + +Use integers in calculator functions + + +Import library modules + + +Use multiple actors + + +Make inter-canister calls + + +Add access control with identities + + +Accept cycles from a wallet + + +Troubleshoot issues + + + + +Explore our languages + + +Develop using different languages + + +Motoko + + +Motoko Playground + + +Motoko Base Library + + +Motoko Guide + + +About the language guide + + +Introduction + + +Basic concepts and terms + + +Mutable state + + +Local objects and classes + + +Actors and async data + + +Error handling + + +Pattern matching + + +Sharing data and behavior + + +Modules and imports + + +Imperative control flow + + +Structural equality + + +Actor classes + + +Principals and caller identification + + +Managing cycles + + +Stable variables and upgrade methods + + +Language quick reference + + +Compiler reference + + +Motoko grammar + + +Motoko style guidelines + + + + + + +Rust + + +Hello, World! Quick Start + + +Simple counter tutorial + + +Basic dependency tutorial + + +Profile tutorial + + +Optimize a Rust program + + + + +Candid + + +What is Candid? + + +How to + + +Reference + + +Supported types + + +Candid specification + + +Candid Rust crate + + + + + + + + +Introducing the Internet Identity + + +What is Internet Identity + + +How to use the Internet Identity + + + + +Frontend development + + +Add frontend assets + + +Customize the front-end + + +Add a stylesheet + + + + + + + + +Protocol Docs + + +.Concepts + + +What is the {IC} + + +Internet Computer Interface Specification + + +Nodes and sub-networks + + +Decentralized data centers + + +Canisters and code + + +Tokens and cycles + + +Neurons and governance + + + + + + +General Docs + + +Overview of self-custody + + +Choosing self-custody for digital assets + + +Self-custody quick start + + + + +Overview of ledger + + +Ledger quick start + + + + +Overview of the NNS App + + +NNS App quick start + + + + + + +Additional Resources + + +Developer videos + + +Internet Identity + + +Motoko + + +Building a multiplayer game for the Internet Computer + + +Deploying static sites to the Internet Computer + + +Zero to fullstack: web apps on the Internet Computer + + + + +Protocol videos + + +Technical library + + + + +Developer tooling + + +DFINITY Canister SDK + + +Rust CDK + + +Vessel Package Manager + + +Motoko VS Code Extension + + +Agent JS + + +Sudograph + + +Cycles Wallet + + +Motoko Playground + + +Quill + + + + +Examples + + +Awesome DFINITY + + +CanCan + + +Mini Motoko examples + + + + +Community created resources + + +ic.rocks (Block explorer) + + +Plug (Browser-based wallet extension) + + +Fleek (Netlify for the open web) + + +Cycles Faucet + + + + +Computation and Storage Costs + + + + +Community + + +Developer Discord + + +Developer Forum + + + + +
\ No newline at end of file diff --git a/modules/ROOT/pages/download.xml b/modules/ROOT/pages/download.xml new file mode 100644 index 000000000..3e653760f --- /dev/null +++ b/modules/ROOT/pages/download.xml @@ -0,0 +1,49 @@ + + + +
+ +Download center +2021-08-05 + +Currently, you can download the {sdk-long-name} directly from within a terminal shell on your local computer. +With this installation option, you can be logged on as any user and no additional software is required. +
+Install the latest directly from a terminal +To download and install from a terminal shell: + + +Open a terminal shell on your local computer. +For example, on macOS open the Applications folder, then open Utilities and double-click Terminal. + + +Download and install the SDK package by running the following curl command: +sh -ci "$(curl -fsSL https://sdk.dfinity.org/install.sh)" + + +
+
+Install a specific version from a terminal +If you want to install a specific version, for example, to test against a previous version, you can modify the installation command to include a version. +To download and install a specific version from a terminal shell: + + +Open a terminal shell on your local computer. + + +Set the DFX_VERSION environment variable to the version of the {sdk-short-name} package you want to install as a prefix to curl command. +For example, to install version 0.8.0, you would run the following command: +DFX_VERSION=0.8.0 sh -ci "$(curl -fsSL https://sdk.dfinity.org/install.sh)" + + + +If you are using the DFX_VERSION environment variable to install a version of the {sdk-short-name} not yet publicly available, see this article for an overview of what’s changed. + +
+
+Next steps +For information about the next steps to take, see Tutorials in the SDK Developer Tools. +To learn more about writing programs for the Internet Computer before you start experimenting with code, see Concepts. +For information about writing programs for the Internet Computer using Motoko, see the Motoko Programming Language Guide. +
+
\ No newline at end of file diff --git a/modules/ROOT/pages/http-middleware.xml b/modules/ROOT/pages/http-middleware.xml new file mode 100644 index 000000000..aeb5507c6 --- /dev/null +++ b/modules/ROOT/pages/http-middleware.xml @@ -0,0 +1,156 @@ + + + +
+ +Introducing a new approach to handling HTTP requests and serving assets +2021-08-05 + +If you are installing any 0.7.0 (or later) version of the {sdk-short-name}, you might have noticed that those versions have introduced some major improvements for handling HTTP queries and front-end assets. +When these changes are officially rolled into the next publicly-available release of the {sdk-short-name}, they will change how you build and deploy applications on the Internet Computer. +If you are creating new projects, the changes to the underlying architecture will have little, if any, effect on your development workflow. In fact, you might find that the new architecture makes building applications that run on the Internet Computer a more familiar experience. +If you have any existing projects, however, you’ll need to plan for a one-time migration to the new architecture. +Migration to the new architecture doesn’t have to be completed immediately, but updating your projects to take advantage of the changes will ultimately make it easier to upload and manage front-end assets. +
+Replacing the bootstrap code: a recap +Before we describe the new architecture, it’s useful to have some context about the old approach that we are replacing and how the code has worked up to this point. +Previously, developing a front-end on the Internet Computer involved adding a front-end assets canister with a retrieve() function. +The retrieve() function would take a path and return a blob. The blob returned by the retrieve() function would then have an index.js file that contained some JavaScript and static HTML called the bootstrap code. +After you deployed an application as smart contract—called a canister—on the Internet Computer, accessing the canister using the <CANISTER_ID>.ic0.app URL executed the bootstrap code, which in turn, performed the following steps: + + +Created a secure worker to contain your private key. + + +Polyfilled the window.ic to provide some mechanics to the running application so that it can communicate with the Internet Computer. + + +Called the canister’s retrieve() method with index.js as the path, and evaluate it. + + +Passed control of the document object model (DOM) and the page to the canister’s JavaScript code. + + +This bootstrap workflow is quite different from how people usually build web applications. +For example, this approach did not support loading HTML directly or downloading assets like PNG files. +Asset handling required either loading the assets from another domain (for example, an AWS bucket) or loading the assets in JavaScript, transforming them into data URI, then setting the src attribute accordingly. +Handling assets in this way led to problems in the browser, such as: + + +Not waiting for re-layout of pages. + + +Deferred loading of assets. + + +Executing JavaScript out of band. + + +The bootstrap approach provided advantages in terms of security and decentralization, but those advantages were offset by the poor HTTP and asset handling that front-end developers and application users didn’t expect to experience. +Over the last year, the {sdk-short-name} team has been gathering and evaluating feedback from the developer community. Based on that feedback, the team has decided to provide a more flexible developer experience while continuing to provide an equivalent security model. +
+
+Enabling canisters to respond to HTTP requests +After considering the advantages and disadvantages of different proposals, the team decided on an architecture that would allow canisters to answer HTTP requests directly. +With this new approach, the {sdk-short-name} implements an HTTP middleware server. +The HTTP middleware server handles the processing for the HTTP request by doing the following: + + +Receiving the HTTP request and converting its method, uri, headers and body into a Candid structure. + + +Resolving the canister identifier for the request. + + +Instantiating an agent to talk to the canister. + + +Calling an http_request() query method. + + +If the canister implements the http_request() method, the HTTP middleware decodes the response, takes the headers and body, and constructs an HTTP response. +If the canister does not implement the http_request() method, for backward compatibility, the middleware returns a bootstrap polyfill that points out the deprecation as a warning. +For any errors in the process, the HTTP middleware returns the following error codes: + + +400 Bad Request for any invalid requests (for example, if the HTTP middleware could not find or decode a canister ID). + + +500 Internal Server Error for errors from the HTTP middleware itself (for example, if it could not connect to a replica) + + +502 Bad Gateway if an error is coming from the replica itself (including canister trapping). + + +If any of these errors occur, the dfx command-line interface provides additional details in the response body. +
+
+Revisiting the asset storage canister +To make this transition easier, new and existing projects built with the newer version of dfx will include an improved asset canister that supports the http_request() method by default. This means that assets you upload—including binary assets like images—will be available directly from your browser using their URL. +For example, in a new project, the sample-asset.txt file would be uploaded and available after publishing to the Internet Computer at https://<CANISTER_ID>.raw.ic0.app/sample-asset.txt. +In the future, we will also provide additional support for managing the asset canister cache, handling default assets, and providing HTTP-specific features. +
+
+Routing +Both the /api (for replicas) and /_ (for tool purposes) routes are reserved by the HTTP request specification. +All other routes are available for you to use as needed within your application, eliminating the need to rely on a separate hash router. +
+
+Structure of a new DFX project +Before going into how to migrate an existing project, let’s take a look at a new project. +The front-end changes include the following: + + +The dfx.json includes a frontend key for the asset canister that now points to an index.html file instead of the index.js JavaScript entry point. + + +The package.json file now supports Webpack 5 by default. + + +The webpack.config.js file now generates the list of canister imports for for each canister that has a frontend key in a different way. + + +The src/<project_name>_assets/src/index.html file is a new template file that you can replace with your own index.html file for your front-end. It is served by default by the asset canister when a file isn’t found. + + +The index.js file has been modified to support agent and actor creation. + + +
+
+Agent and actor creation +With the new architecture, we explicitly create an agent instance, then create the actor that we’ll use for our canister. +In the index.js file, this means that where before there was only one import from files generated by dfx, now there are two. +For example, the new index.js file in a project provides code similar to this: +import { Actor, HttpAgent } from '@dfinity/agent'; +import { idlFactory as example_idl, canisterId as example_id } from 'dfx-generated/example'; + +const agent = new HttpAgent(); +const example = Actor.createActor(example_idl, { agent, canisterId: example_id }); +Explicitly creating the agent and actor like this example illustrates is better for a couple reasons: + + +First, the agent itself is entirely configurable by the application, and so is the actor. For example, authentication can only be set when the agent is constructed, so if you want to manage a user identity, you’ll need to do it before creating the agent. + + +Second, being explicit about creating the agent and actor gives you much more control over when you instantiate those objects. If you want a React hook or an Angular service to create the actor, this approach allows you to do so easily. + + +
+
+Migrating an existing project +If you have an existing project, chances are it will not work seamlessly after you update the {sdk-short-name}. +Unfortunately, a direct migration path isn’t possible in this case. +The best way to migrate your current front-end is to create a new project and move your code manually to the new structure. +
+Certified and uncertified front-end assets +With the launch of the Internet Computer main network Beta, all projects serve front-end assets use the new HTTP query architecture. +In addition, the Internet Computer launch introduces a new capability to serve front-end assets as certified data that has been signed and can be considered authenticated and secure or as raw, uncertified data. +Front-end assets that don’t go through the certification process are served using the raw.ic0.app URL suffix. +Certified front-end assets use the .ic0.app URL suffix. +All of the current tutorials illustrate applications that serve uncertified front-end assets. +Learning how to build an application that uses certified query results for front-end assets is an advanced development topic. +For information about how to return certified data in response to queries, see the Interface specification and connect with other developers through the DFINITY Developer Forum. +
+
+
\ No newline at end of file diff --git a/modules/ROOT/pages/index.xml b/modules/ROOT/pages/index.xml new file mode 100644 index 000000000..7c4c06710 --- /dev/null +++ b/modules/ROOT/pages/index.xml @@ -0,0 +1,91 @@ + + + +
+ +Developer Center | DFINITY +2021-08-05 + + + +
\ No newline at end of file diff --git a/modules/ROOT/pages/search.xml b/modules/ROOT/pages/search.xml new file mode 100644 index 000000000..a771b8d7b --- /dev/null +++ b/modules/ROOT/pages/search.xml @@ -0,0 +1,23 @@ + + + +
+ +Search DFINITY documentation +2020-06-05 + +Type a string of at least two characters, then click Search. + + +
+ + +
\ No newline at end of file diff --git a/modules/ROOT/pages/support.xml b/modules/ROOT/pages/support.xml new file mode 100644 index 000000000..a9407736a --- /dev/null +++ b/modules/ROOT/pages/support.xml @@ -0,0 +1,32 @@ + + + +
+ +Get support +2020-06-05 + +
+Search the Knowledge Base + +
+
+Featured articles + +
+
+Popular topics + +
+
+Submit a request for help + +
+
\ No newline at end of file diff --git a/modules/ROOT/pages/videos-tutorials.xml b/modules/ROOT/pages/videos-tutorials.xml new file mode 100644 index 000000000..4db8401a7 --- /dev/null +++ b/modules/ROOT/pages/videos-tutorials.xml @@ -0,0 +1,162 @@ + + + +
+ +Videos and tutorials +2021-05-09 + +The Fundamentals video series provides an introduction to building applications for the Internet Computer. +
+Building on the {IC}: Fundamentals +The Fundamentals video series provides an introduction to building applications for the Internet Computer. +The series consists of ten video segments. +Most of the segments have a running time of three to five minutes, but there are also deeper technical dives that explore the {proglang} programming language, front-end development, and how all of the pieces come together in a sample application. +

+
+ +
+What is the {IC} and why build apps for it? +This segment of the Fundamentals video series provides a basic introduction to the {IC} and how it supports the future of open internet services. +If you want to learn more after watching the video, check out What is the Internet Computer?. +

+
+
+
+ +
+
+Simplifying the developer experience +The {IC} makes it easier to build applications by reducing the ecosystem complexity. +If you want to learn more after watching the video, check out Building the next generation of software and services. +

+
+
+
+ +
+
+What is the DFINITY Canister SDK? +Wondering what a "canister" is? Not sure where to start? This video segment introduces the key tools for developing programs that run on the {IC}. +If you are ready to get started, visit the Download center. +

+
+
+
+ +
+
+Deploying your first application +This video segment walks through how to deploy your first application with the {IC} running locally. +To try it yourself, follow the steps in the Quick start tutorial. +

+
+
+
+ +
+
+Introducing Motoko: A language designed for the {IC} +This video segment offers an overview of the Motoko programming language and highlights a few key features that make it especially well-suited for writing applications that run on the {IC}. +If you want to learn more about using {proglang}, see the {proglang} Programming Language guide. +

+
+
+
+ +
+
+Integrating a front end +This video segment demonstrates how to integrate a front-end user interface using raw JavaScript, React, and React with TypeScript. +After watching the video, you can experiment on your own or follow the steps in Add a stylesheet to learn how to add a stylesheet when using React. +

+
+
+
+ +
+
+How Candid provides a common language for application interfaces +This video segment describes how Candid provides a common interface description language (IDL) for interacting with services running on the Internet Computer. +For more complete information about what Candid is and how to use it, see the Candid guide or Candid on crates.io. +

+
+
+
+ +
+
+Diving into the developer ecosystem +This video segment highlights additional tools and resources available for developing programs using {proglang}. +To start contributing to the community, take a look at the Motoko base library. +

+
+
+
+ +
+
+Building a multiplayer game +This video segment showcases a multiple-player Reversi game built to run on the {IC} and demonstrates many key concepts involved in building applications for the {IC}. +For a closer look at how the game was made, see Building a Multiplayer Reversi Game on the Internet Computer or check out the source code in the Reversi repository. +

+
+
+
+ +
+
+Join the {IC} developer community +This video segment summarizes the resources available and how you can get involved. +For further inspiration, check out the sample applications in the examples or awesome-dfinity repositories. +To be part of the conversation, join the Developer Forum or follow @dfinitydev on Twitter. +

+
+
+
+
+
+
+Tutorials +The Quick start provides a simplified introduction to the basic work flow for creating and deploying a new project without exploring the contents of the project directory or sample code. +If you want more hands-on experience creating programs that run on the {IC}, check out these tutorials: + + +Explore the default project + + +Query using an actor + + +Pass text arguments in a terminal + + +Increment a natural number + + +Use integers in calculator functions + + +Import library modules + + +Use multiple actors + + +Customize the front-end + + +Add a stylesheet + + +Make inter-canister calls + + +Create scalable apps + + +Add access control with identities + + +
+
\ No newline at end of file diff --git a/modules/developers-guide/dev-nav.xml b/modules/developers-guide/dev-nav.xml new file mode 100644 index 000000000..cd9f8ced7 --- /dev/null +++ b/modules/developers-guide/dev-nav.xml @@ -0,0 +1,121 @@ + + + +
+ +Untitled +2021-05-09 + + + +Concepts + + +What is the {IC} + + +Nodes and sub-networks + + +Decentralized data centers + + +Canisters and code + + +Tokens and cycles + + +Neurons and governance + + + + +How to + + +Install, upgrade, or remove software + + +Design apps + + +Manage projects + + +Develop using different backend languages + + +Add frontend assets + + +Manage canisters + + +Troubleshoot issues + + + + +Tutorials + + +Explore the default project + + +Query using an actor + + +Pass text arguments + + +Increment a natural number + + +Use integers in calculator functions + + +Import library modules + + +Use multiple actors + + +Customize the front-end + + +Add a stylesheet + + +Make inter-canister calls + + +Create scalable apps + + +Add access control with identities + + + + +Reference + + +DFX commands + + +Candid interface description language + + +Language server protocol client + + +Glossary + + + + +Examples + + +
\ No newline at end of file diff --git a/modules/developers-guide/examples/candid-ui.xml b/modules/developers-guide/examples/candid-ui.xml new file mode 100644 index 000000000..98c792ff9 --- /dev/null +++ b/modules/developers-guide/examples/candid-ui.xml @@ -0,0 +1,57 @@ + + + +
+ +Test functions in a browser +2021-08-05 + +
+Test functions in a browser +The canister interface description language—often referred to as Candid or more generally as the IDL—provides a common language for specifying the signature of a canister service. +Candid provides a unified way for you to interact with canisters that are written in different languages or accessed using different tools. +For example, Candid provides a consistent view of a service whether the underlying program is native Rust, JavaScript, or {proglang}. +Candid also enables different tools—such as the dfx command-line interface and the Network Nervous System application—to share a common description for a service. +Based on the type signature of the actor, Candid also provides a web interface that allows you to call canister functions for testing and debugging. +After you have deployed your project locally using the dfx deploy or dfx canister install command, you can access the Candid web interface endpoint in a browser. +This web interface—the Candid UI—exposes the service description in a form, enabling you to quickly view and test functions and experiment with entering different data types without writing any front-end code. +To use the Candid web interface to test canister functions: + + +Find the Candid UI canister identifier associated with the current project using the dfx canister id __Candid_UI command. +dfx canister id __Candid_UI +The command displays the canister identifier for the Candid UI with output similar to the following: +r7inp-6aaaa-aaaaa-aaabq-cai + + +Copy the Candid UI canister identifier so that it is available in the clipboard. + + +If you’ve stopped the {IC}, restart it locally by running the following command: +dfx start --background + + +Open a browser and navigate to the address and port number specified in the dfx.json configuration file. +By default, the local network binds to the 127.0.0.1:8000 address and port number. + + +Add the required canisterId parameter and the Candid UI canister identifier returned by the dfx canister id command to the URL. +For example, the full URL should look similar to the following but with the CANDID-UI-CANISTER-IDENTIFIER that was returned by the dfx canister id command: +http://127.0.0.1:8000/?canisterId=<CANDID-UI-CANISTER-IDENTIFIER> +The browser displays a form for you to specify a canister identifier or choose a Candid description (.did) file. +If you aren’t sure which canister identifier to use, you can run the dfx canister id command to look up the identifier for a specific canister name. + + +Specify the canister identifier or description file for your application into the Provide a canister ID field, then click Go to display the service description. + + +Review the list of function calls and types defined in the program. + + +Type a value of the appropriate type for a function or click Random to generate a value, then click Call or Query to see the result. +Note that depending on the data type, the Candid interface might display additional configuration settings for testing functions. +For example, if a function takes an array, you might need to specify the number of items in the array before entering values. + + +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/about-this-guide.xml b/modules/developers-guide/pages/about-this-guide.xml new file mode 100644 index 000000000..4b883102d --- /dev/null +++ b/modules/developers-guide/pages/about-this-guide.xml @@ -0,0 +1,13 @@ + + + +
+ +About this guide +2020-06-05 + +
+About this guide + +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/basic-syntax-rules.xml b/modules/developers-guide/pages/basic-syntax-rules.xml new file mode 100644 index 000000000..0716656bc --- /dev/null +++ b/modules/developers-guide/pages/basic-syntax-rules.xml @@ -0,0 +1,732 @@ + + + +
+ +Learning the basics of Motoko +2021-05-09 + + +December 2019 (Alpha) + + +D + +One key feature of the Internet Computer platform is the Motoko programming language. +The Motoko programming language is a high-level, general purpose language that is similar to other modern programming languages, but specifically designed to handle asynchronous messaging efficiently. +Although Motoko provides an interpreter that can be used interactively and a standalone compiler, you can write programs and compile your code without using either one directly. +Instead, in most cases, you interact with the programming language indirectly through an editor of your choice and using the dfx command-line execution tool. +To help you get started using this new language, this section provides a brief overview of the language and describes a few basic conventions for writing programs using Motoko. +For more complete information about programming in Motoko, including specific language features and detailed examples, see the Language Reference Guide. +
+Actors and asynchronous messaging +As you start to explore the Motoko programming language, you should keep in mind that each application consists of an actor that communicates with other actors by passing messages asynchronously. +An actor is a special kind of object that passes its messages in an isolated state. +When you define an actor, its messages are processed in sequence but in isolation from on each other. As an example of using actors, consider the following program: +let result1 = await service1.computeAnswer(params); +let result2 = await service2.computeAnswer(params); +finalStep(result1, result2) +In this example, the program makes two requests to two distinct +services. +Each service is implemented internally as an actor (object). +The program waits using the await keyword to wait for each result value in sequence. +The program then uses the result from each request them in the final step, calling the function finalStep. +The actor-based programming model is particularly well-suited for writing programs intended to run on the Internet Computer platform. +However, you can also write programs in Motoko to run on other platforms and inside of other frameworks. +If you are writing programs to run on other platforms, you might not use actor objects or asynchronous messaging at all. +
+
+Interface descriptions and Motoko +To support multiple languages and cross-language communication, the Motoko compiler automates the production and consumption of interface descriptions. +The Motoko compiler generates the interface descriptions using the type signatures in your Motoko programs and the structure of imported pre-defined interfaces. +
+
+Prelude and standard library functions +Like other languages, Motoko includes many common functions in predefined prelude and standard library files that you can import into your programs. +By importing the prelude or standard library, you can use common functions like println without explicitly defining them in your programs. +For example, you might include a line similar to the following to import list functions from the standard library: +import List "../../motoko/base/list"; +
+
+Basic language features +This section describes the basic language conventions you need to know for programming in Motoko. +
+Comments +You can use single-line, multi-line, or nested multi-line comments to include descriptive non-executable text in your code. +For example, use comments to add context about a code block as a note to yourself or as information you want to share with anyone reviewing or maintaining your code. +Properly-formatted comments are treated as whitespace and ignored by the compiler. +
+Single-line comments +Single-line comments begin with two forward-slashes (//) and consist of the characters following // to the end of the same line. +For example, you can have single-line comments above, below, or on the same line as the code to which the comment applies. +// This is a single-line comment on its own line above relevant code +import List = "ListLib"; +
+
+Multi-line and nested comments +You can also include single-line, multi-line, and nested multi-line comments by starting with a forward-slash followed by an asterisk (/*) and ending with an asterisk followed by a forward-slash (*/). +For example: +/* +This is a comment that is split into +multiple lines. +*/ +You can also write nested multi-line comments by starting a multi-line comment block, then starting a second multi-line comment within the first block. +For example: +/* This is the start of the first multi-line comment block. + /* This is the second, nested multi-line comment. */ +This is the end of the first multi-line comment block. */ +
+
+
+Programs, declarations, and expressions +Each Motoko program consists of zero or more declarations, followed by an optional expression. +For example, the following snippet consists of two declarations for the variables x and y followed by an expression, forming a single program: +let x = 1; +let y = x + 1; +x * y + x; +As illustrated in this example, you use a semi-colon (;) to terminate declarations and expressions. For example, to evaluate a simple equation: +1 + 3; // When executed, the result would be "4 : Nat" value and type +
+
+
+Numbers, text and operators +Motoko supports the following number types: + + +Natural numbers (Nat) are positive whole integers. + + +Integer numbers (Int) are positive, negative, or zero whole number values. + + +Floating point numbers (Float) are fractional numeric 32-bit or 64-bit values. + + +Basic arithmetic operators work as you would expect. For example: +1 + 1; // = 2 +0.1 + 0.2; // = 0.3 +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 +You can use double (") quotes to enclose text. For example: +let name = "Chris"; // let name : Text = "Chris" +
+Relational operators +You can use the following relational operators in Motoko programs. + + + + + + +Use this +To define this relationship + + + + +␣<␣ +Less than. The operator must be enclosed in whitespace. + + +␣>␣ +Greater than. The operator must be enclosed in whitespace. + + +== +Equals. + + +!= +Not equals. + + +<= +Less than or equal to. + + +>= +Greater than or equal to. + + + + +
+
+Numeric binary operators + + + + + + +Use this +For this operation + + + + ++ +Addition. + + +- +Subtraction. + + +* +Multiplication. + + +/ +Division. + + +% +Modulo. + + +** +Exponentiation. + + + + +
+
+Bitwise binary operators + + + + + + +Use this +For this operation + + + + +& +Bitwise AND. + + +| +Bitwise OR. + + +^ +Exclusive OR. + + +<< +Shift left. + + +␣>> +Shift right. The operator must be preceded by whitespace. + + +<<> +Rotate left. + + +<>> +Rotate right. + + + + +
+
+String operators + + + + + + +Use this +For this operation + + + + +# +Text concatenation. + + + + +
+
+Assignment operators + + + + + + +Use this +For this operation + + + + +:= +Assignment using an in-place update. + + ++= +In place addition. + + +-= +In place subtraction. + + +*= +In place multiplication. + + +/= +In place divide. + + +%= +In place modulo. + + +**= +In place exponentiation. + + +&= +In place logical AND. + + +|= +In place logical OR. + + +^= +In place exclusive OR. + + +<<= +In place shift left. + + +>>= +In place shift right. + + +<<>= +In place rotate left. + + +<>>= +In place rotate right. + + +#= +In place concatenation. + + + + +
+
+Variables +Variables enable you to relate static names and types with dynamic values that are present only when a program is executed. +You can declare variable names, and if necessary the data type, using the let keyword. For example, you can use the following notation to set the variable x to the natural number 1: +let x : Nat = 1; +In this example, the compiler can infer that the expression 1 has type Nat, and that x has the same type. Therefore, you can use the following annotation without changing the meaning of the program: +let x = 1 +
+
+Primitive values +Motoko supports the following primitive types: + + +Booleans (true, false) + + +Integers (…​,-2, -1, 0, 1, 2, …​) + + +Natural numbers (0, 1, 2, …​) + + +Words (fixed-width numbers) + + +Characters (Unicode code points) + + +Text values (strings of Unicode characters) + + +Integers and natural numbers do not silently over- or under-flow. +Instead, they use representations that grow to accommodate any finite number. There are also fixed-width integers and natural numbers (in 8-, 16-, 32-, and 64-bit) types that trap on arithmetic over- and under-flow. The fixed-width integers are signed. The fixed-width natural numbers are unsigned. +Word values have fixed width. Arithmetic for Word types is performed using modulo 2**N where N is the width of the word type in bits. +Motoko does not allow unchecked, uncaught overflows. +All primitive types are shareable so that they can be sent and received across remote function calls. +
+
+Non-primitive values +Building on the primitive values and types above, the language permits user-defined types, and each of the following non-primitive value forms and associated types: + + +Tuples, including the unit value (the empty tuple). + + +Arrays, in both immutable and mutable forms. + + +Objects, with named, unordered fields and methods. + + +Variants, with named constructors and optional payload values. + + +Function values, including shareable functions that can be called remotely. + + +Async values, otherwise known as futures or promises, that can be synchronized with using await. + + +Optional values, that can either be null or of the form ? v, for a proper value v. + + +Note that if your function is returning an optional value of type T, then the function’s return type should be of the form '? T': +prefixing a type with question mark (?) adds the null value. +For example, you would use the following syntax to indicate that the return value of the type identified by ?Phone is optional (for example, the return value can be null as well as a proper phone number): +public query func lookup(name: Name): async ?Phone { + return A.find(book, name, nameEq); + }; +
+
+Functions +First-class functions support multiple arguments and returns and can be polymorphic. + + +T -> U + + +(T, U) -> (V, W) + + +(x : T, y : U) -> V + + +<A, B>(x : T, y : U) -> (V, W) + + +Functions can be defined as public or private, shared, or locally-scoped. +
+
+Objects and actors +Objects are structural record types with fields that can be mutable or immutable. +Objects with immutable fields are shareable. +{var x : Int; color : Color} +{x : Int; color: Color} +Actors are restricted objects with the following characteristics: + + +State must be isolated. + + +Public methods are implicitly shared. + + +All interactions are asynchronous. + + +Actor objects are marked as actor with syntax similar to the +following: +actor { + private var c = 0; + public func inc() { c += 1 }; + public func get() : async Int { c } +} +The fields of an actor are functions that return either: + + +An empty unit return type () which is similar to a void return value. + + +An async return type, which is essentially a promise to return a future value. + + +
+
+Arrays +You can define immutable or mutable arrays. +The assignment syntax you use is the same for both immutable and mutable arrays, but you cannot change immutable arrays after allocation. +The following is an example of a simple, immutable array that holds three natural numbers, and has the type [Nat]: +let test_array : [Nat] = [1, 2, 3] ; +In general, an immutable array uses square brackets around the type of the array’s elements, which must share a single common type. +Because immutable arrays cannot be modified,immutable arrays are safe to send and share. +Unlike immutable arrays, each mutable array in Motoko introduces a private actor state which can be used locally but cannot be used in cases where immutable arrays are expected. +Mutable arrays cannot be shared or sent in messages. +For more information about working with arrays, see the Motoko Language Reference. +
+
+Tuples +A tuple is a data structure that contains a sequence of elements. +The number of element in the sequence is fixed, but the elements can consist of different data types. +Tuples are often used when you want to have a data structure for an object with specific properties, but you don’t want to create a separate type for it. +The following example defines a tuple for a three-dimensional point using integers to specify locations to represent the point on the x-axis, y-axis, and z-axis and a color. + type Point3D = (Int, Int, Int, Color); + let origin = (0, 0, 0, Color.Red); + let (x, y, z, _) = origin; + + func isOrigin(p : Point3D) : Bool { + switch p { + case (0, 0, 0, _) true; // pattern match + case _ false; + } + } +
+
+Conditional and switching +Motoko supports all the common constructs for expressing conditions and switching between cases. +For example, you can write if and if else conditions with syntax similar to the following: +if <exp> + ... +if <exp> + ... +else <exp> + ... +You can also use switch and case syntax similar to the following: +switch <exp> { + case 1 + ...; + case 2 + ...; + case 3 + ...} +
+
+While, Loops, and iteration + + +while (p()) ... + + +loop ... + + +loop ... while (p()) + + +for (x in f()) ... + + +
+
+Label, break, and continue +Labels help ensure control flow is structured and can be used with the break and continue keywords. + + +label l exp + + +break l (more generally, break l exp) + + +continue l + + +
+
+
+Identifiers +Identifiers are alphanumeric. +They must start with an uppercase or lowercase letter and can include a combination of uppercase or lowercase letters, numbers, and underscores. +
+
+Reserved keywords +The following keywords are reserved for specific purposes and cannot be used as identifiers or for any other purpose in Motoko code: + + + + + + + + + +This keyword +Is reserved for this purpose + + + + +actor +Declare actor identifiers, actor objects and actor classes. + + +and +Boolean conjunction (short-circuiting). + + +async +Declare an asynchronous function or create a future. + + +assert +Assert a Boolean property (trapping when false). + + +await +Await the result of an asynchronous computation. + + +break +Exit from a labelled expression or loop (possibly with a value). + + +case +Case of a preceding switch expression, consisting of a pattern and expression. + + +catch +Failure branch of a preceding try expression. + + +class +Class declaration (actor, object and module classes). + + +continue +Continue with the next iteration of loop or while or for. + + +debug +Conditional debug expressions, excluded from release code. + + +debug_show +Display a debug message. + + +else +False branch of a conditional expression. + + +false +Boolean literal value false. + + +for +Iterate over the items of an iterator. + + +func +Declare a name function or anonymous function value. + + +if +Branch on a Boolean value. + + +ignore +Discard the value of an expression. + + +import +Import a source file or other resource as a named module. + + +in +Indicate the domain of for loop. + + +module +Declare a module identifier or module expression. + + +not +Negate a Boolean value. + + +null +The literal value of type Null. + + +object +Declare an object identifier or object expression. + + +or +Boolean disjunction (short-circuiting). + + +label +Label an expression for early exit via break. + + +let +Bind an identifier (or pattern) to a value. + + +loop +Enter a loop (possibly with a guarded exit). + + +private +Restrict the visibility of a declaration to the enclosing +actor, object, module or class. + + +public +Publish a declaration as member(s) of the enclosing +actor, object, module or class. + + +query +A modifier on shared functions that return results without modifying state. + + +return +Exit from a function or async block (possibly with a value). + + +shared +Declare a function that can be called remotely. + + +switch +Conditional pattern matching, defined by cases. + + +throw +Exit from an expression with an error. + + +true +A Boolean value returned as the result of a comparison. + + +try +Declare a scoped error handler. + + +type +Declare a type abbreviation. + + +var +Specify a (mutable) variable, field or array that can be updated. + + +while +Enter a guarded loop. + + + + +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/cli-reference.xml b/modules/developers-guide/pages/cli-reference.xml new file mode 100644 index 000000000..9ce541b59 --- /dev/null +++ b/modules/developers-guide/pages/cli-reference.xml @@ -0,0 +1,70 @@ + + + +
+ +Command-line reference +2021-08-05 + +The DFINITY command-line execution environment (dfx) is the primary tool for creating, deploying, and managing the applications you develop for the Internet Computer platform. +You can use the dfx parent command with different flags and subcommands to perform different types of operations. +The basic syntax for running dfx commands is: +dfx [option] [subcommand] [flag] +Depending on the subcommand, the options and flags you specify might apply to the parent command or to a specific subcommand. +For example, the flags for enabling or suppressing verbose logging are specified for the dfx parent command, then applied to any subcommands. +When you have the {sdk-short-name} installed, you can use the following commands to specify the operation you want to perform. +For reference information and examples that illustrate using these commands, select an appropriate command. + + +dfx + + +dfx bootstrap + + +dfx build + + +dfx cache + + +dfx canister + + +dfx config + + +dfx deploy + + +dfx help + + +dfx identity + + +dfx ledger + + +dfx new + + +dfx ping + + +dfx replica + + +dfx start + + +dfx stop + + +dfx upgrade + + +dfx wallet + + +
\ No newline at end of file diff --git a/modules/developers-guide/pages/cli-reference/dfx-bootstrap.xml b/modules/developers-guide/pages/cli-reference/dfx-bootstrap.xml new file mode 100644 index 000000000..74cd187f8 --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-bootstrap.xml @@ -0,0 +1,104 @@ + + + +
+ +dfx bootstrap +2021-08-05 + +Use the dfx bootstrap command to start the bootstrap web server defined in the dfx.json configuration file or specified using command-line options. +The bootstrap web server you specify is used to serve the front-end static assets for your project. +
+Basic usage +dfx bootstrap [option] +
+
+Flags +You can use the following optional flags with the dfx bootstrap command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Options +You can specify the following options for the dfx bootstrap command. + + + + + + + + + +Option +Description + + + + +ip <ip_address> +Specifies the IP address that the bootstrap server listens on. +If you don’t specify an IP address, the address setting you have configured in the dfx.json configuration file is used. +By default, the server address is 127.0.0.1. + + +--network <network> +Specifies the network to connect to if you want to override the default local network endpoint (http://127.0.0.1:8080/api). + + +--port <port> +Specifies the port number that the bootstrap server listens on. +By default, port number 8081 is used. + + +--root <root> +Specifies the directory containing static assets served by the bootstrap server. +By default, the path to static assets is: +$HOME/.cache/dfinity/versions/$DFX_VERSION/js-user-library/dist/bootstrap. + + +--timeout <timeout> +Specifies the maximum amount of time, in seconds, the bootstrap server will wait for upstream requests to complete. +By default, the bootstrap server waits for a maximum of 30 seconds. + + + + +
+
+Examples +You can use the dfx bootstrap command to start a web server for your application using custom settings, including a specific server address, port number, and static asset location. +For example, to start the bootstrap server using a specific IP address and port number, you would run a command similar to the following: +dfx bootstrap --ip 192.168.47.1 --port 5353 +The command displays output similar to the following: +binding to: V4(192.168.47.1:5353) +replica(s): \http://127.0.0.1:8080/api +Webserver started... +To use the default server address and port number but specify a custom location for static assets and longer timeout period, you might run a command similar to the following: +dfx bootstrap --root $HOME/ic-projects/assets --timeout 60 +You can use CTRL-C to stop the bootstrap server. +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/cli-reference/dfx-build.xml b/modules/developers-guide/pages/cli-reference/dfx-build.xml new file mode 100644 index 000000000..8da0af6de --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-build.xml @@ -0,0 +1,119 @@ + + + +
+ +dfx build +2021-08-05 + +Use the dfx build command to compile your program into a WebAssembly module that can be deployed on the {IC}. +You can use this command to compile all of the programs that are defined for a project in the project’s dfx.json configuration file or a specific canister. +Note that you can only run this command from within the project directory structure. +For example, if your project name is hello_world, your current working directory must be the hello_world top-level project directory or one of its subdirectories. +The dfx build command looks for the source code to compile using the information you have configured under the canisters section in the dfx.json configuration file. +
+Basic usage +dfx build [flag] [option] [--all | canister_name] +
+
+Flags +You can use the following optional flags with the dfx build command. + + + + + + + + + +Flag +Description + + + + +--check +Builds canisters using a temporary, hard-coded, locally-defined canister identifier for testing that your program compiles without connecting to the {IC} network. + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Options +You can specify the following option for the dfx build command. + + + + + + + + + +Option +Description + + + + +--network <network> +Specifies the {IC} network you want to connect to. You can use this option to override the network specified in the dfx.json configuration file. + + + + +
+
+Arguments +You can specify the following arguments for the dfx build command. + + + + + + + + + +Argument +Description + + + + +--all +Builds all of the canisters configured in the project’s dfx.json file. + + +canister_name +Specifies the name of the canister you want to build. +If you are not using the --all option, you can continue to use dfx build or provide a canister name as an argument (the canister name must match at least one name that you have configured in the canisters section of the dfx.json configuration file for your project.) + + + + +
+
+Examples +You can use the dfx build command to build one or more WebAssembly modules from the programs specified in the dfx.json configuration file under the canisters key. +For example, if your dfx.json configuration file defines one hello_world canister and one hello_world_assets canister, then running dfx build compiles two WebAssembly modules: +Unresolved directive in dfx-build.adoc - include::example$sample-dfx.json[] +Note that the file name and path to the programs on your file system must match the information specified in the dfx.json configuration file. +In this example, the hello_world canister contains the main program code and the hello_world_assets canister store front-end code and assets. +If you want to keep the hello_world_assets canister defined in the dfx.json file, but only build the back-end program, you could run the following command: +dfx build hello_world +Building a specific canister is useful when you have multiple canisters defined in the dfx.json file, but want to test and debug operations for canisters independently. +To test whether a canister compiles without connecting to any {IC} network, you would run the following command: +dfx build --check +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/cli-reference/dfx-cache.xml b/modules/developers-guide/pages/cli-reference/dfx-cache.xml new file mode 100644 index 000000000..a267bc4f7 --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-cache.xml @@ -0,0 +1,258 @@ + + + +
+ +dfx cache +2021-08-05 + +Use the dfx cache command with flags and subcommands to manage the dfx version cache. +The basic syntax for running dfx cache commands is: +dfx cache [subcommand] [flag] +Depending on the dfx cache subcommand you specify, additional arguments, options, and flags might apply. +For reference information and examples that illustrate using dfx cache commands, select an appropriate command. + + + + + + + + + +Command +Description + + + + +delete +Deletes the specified version of dfx from the local cache. + + +help +Displays usage information message for a specified subcommand. + + +install +Installs the specified version of dfx from the local cache. + + +list +Lists the versions of dfx currently installed and used in current projects. + + +show +Show the path of the cache used by this version of the dfx executable. + + + + +To view usage information for a specific subcommand, specify the subcommand and the --help flag. +For example, to see usage information for dfx cache delete, you can run the following command: +dfx cache delete --help +
+dfx cache delete +Use the dfx cache delete command to delete a specified version of dfx from the version cache on the local computer. +
+Basic usage +dfx cache delete [version] [flag] +
+
+Flags +You can use the following optional flags with the dfx cache delete command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Arguments +You can specify the following argument for the dfx cache delete command. + + + + + + + + + +Command +Description + + + + +version +Specifies the version of dfx you to delete from the local cache. + + + + +
+
+Examples +You can use the dfx cache delete command to permanently delete versions of dfx that you no longer want to use. +For example, you can run the following command to delete dfx version 0.6.2: +dfx cache delete 0.6.2 +
+
+
+dfx cache install +Use the dfx cache install command to install dfx using the version currently found in the dfx cache. +
+Basic usage +dfx cache install [flag] +
+
+Flags +You can use the following optional flags with the dfx cache install command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Examples +You can use the dfx cache install command to force the installation of dfx from the version in the cache. +For example, you can run the following command to install dfx: ++ +dfx cache install +
+
+
+dfx cache list +Use the dfx cache list command to list the dfx versions you have currently installed and used in projects. +If you have multiple versions of dfx installed, the cache list displays an asterisk (*) to indicate the currently active version. +
+Basic usage +dfx cache list [flag] +
+
+Flags +You can use the following optional flags with the dfx cache list command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Examples +You can use the dfx cache list command to list the dfx versions you have currently installed and used in projects. +For example, you can run the following command to list versions of dfx found in the cache: +dfx cache list +This command displays the list of dfx versions found similar to the following: +0.6.4 * +0.6.3 +0.6.0 +
+
+
+dfx cache show +Use the dfx cache show command to display the full path to the cache used by the dfx version you are currently using. +
+Basic usage +dfx cache show [flag] +
+
+Flags +You can use the following optional flags with the dfx cache show command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Examples +You can use the dfx cache show command to display the path to the cache used by the dfx version you are currently using: +dfx cache show +This command displays the path to the cache used by the dfx version you are currently using: +/Users/pubs/.cache/dfinity/versions/0.6.4 +
+
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/cli-reference/dfx-canister.xml b/modules/developers-guide/pages/cli-reference/dfx-canister.xml new file mode 100644 index 000000000..4f6621f98 --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-canister.xml @@ -0,0 +1,1287 @@ + + + +
+ +dfx canister +2021-08-05 + +Use the dfx canister command with flags and subcommands to manage canister operations and interaction with the {platform}. +In most cases, you use dfx canister subcommands after you compile a program to manage the canister lifecycle and to perform key tasks such as calling program functions. +The basic syntax for running dfx canister commands is: +dfx canister [subcommand] [flag] +Depending on the dfx canister subcommand you specify, additional arguments, options, and flags might apply or be required. +To view usage information for a specific dfx canister subcommand, specify the subcommand and the --help flag. +For example, to see usage information for dfx canister call, you can run the following command: +dfx canister call --help +For reference information and examples that illustrate using dfx canister commands, select an appropriate command. + + + + + + + + + +Command +Description + + + + +call +Calls a specified method on a deployed canister. + + +create +Creates a new "empty" canister by registering a canister identifier on an {IC} network. + + +delete +Deletes a currently stopped canister. + + +help +Displays usage information message for a specified subcommand. + + +id +Displays the identifier for a canister. + + +install +Installs compiled code as a canister on the replica. + + +request-status +Requests the status of a call to a canister. + + +set-controller +Specifies the identity name or principal to use as the new controller for a specified canister on the Internet Computer network. + + +send +Send a previously-signed message.json to a specified canister identifier. For example, if you want to send a message that calls the network nervous system (NNS) governance canister to manage neurons, you might want to separate message signing from message delivery for security reasons. + + +sign +Create a signed message.json file before making a call to a specified canister identifier. For example, if you want to send a message that calls the network nervous system (NNS) governance canister to manage neurons, you might want to separate message signing from message delivery for security reasons. + + +start +Restarts a stopped canister. + + +status +Requests the running status of a canister. + + +stop +Stops a currently running canister. + + + + +
+Overriding the default network +By default, dfx canister commands run on the local network specified in the dfx.json file. +If you want to send a dfx canister subcommand to a specific network provider address and port number without changing the settings in your dfx.json configuration file, you can explicitly specify the URL for the network using the --network option. +For example, to register unique canister identifiers for a project when the {IC} runs on your local computer, you can run the following command: +dfx canister create --all +If you want to register unique canister identifiers for the same project when the {IC} runs on the network that uses the ic alias in the dfx.json file, you can run the following command: +dfx canister --network ic create --all +Similarly, you can call a canister and function running on a remote {IC} network using a command similar to the following: +dfx canister --network \http://192.168.3.1:5678 call counter get +Note that you must specify the --network parameter before the canister operation (create or call) and any additional arguments such as the canister name (counter), and function (get). +
+
+dfx canister call +Use the dfx canister call command to call a specified method on a deployed canister. +
+Basic usage +dfx canister call [option] canister_name method_name [argument] [flag] +
+
+Flags +You can use the following optional flags with the dfx canister call command. + + + + + + + + + +Flag +Description + + + + +--async +Enables you to continue without waiting for the result of the call to be returned by polling the replica. + + +-h, --help +Displays usage information. + + +--query +Enables you to send a query request to a deployed canister. +For best performance and network efficiency, you should use this flag when you explicitly want to use the query method to retrieve information. +For information about the difference between query and update calls, see Canisters include both program and state. + + +--update +Enables you to send an update request to a deployed canister. +By default, canister calls use the update method. + + +-V, --version +Displays version information. + + + + +
+
+Options +You can use the following options with the dfx canister call command. + + + + + + + + + +Option +Description + + + + +--output <output> +Specifies the output format to use when displaying a method’s return result. +The valid values are idl and raw. + + +--type <type> +Specifies the data format for the argument when making the call using an argument. +The valid values are idl and raw. + + + + +
+
+Arguments +You can specify the following arguments for the dfx canister call command. + + + + + + + + + +Argument +Description + + + + +canister_name +Specifies the name of the canister to call. The canister name is a required argument and should match the name you have configured for a project in the canisters section of the dfx.json configuration file. + + +method_name +Specifies the method name to call on the canister. +The canister method is a required argument. + + +argument +Specifies the argument to pass to the method. +Depending on your program logic, the argument can be a required or optional argument. +You can specify a data format type using the --type option if you pass an argument to the canister. +By default, you can specify arguments using the Candid (idl) syntax for data values. +For information about using Candid and its supported types, see Interact with a service in a terminal and Supported types. +You can use raw as the argument type if you want to pass raw bytes to a canister. + + + + +
+
+Examples +You can use the dfx canister call command to invoke specific methods—with or without arguments—after you have deployed the canister on the network using the dfx canister install command. +For example, to invoke the get method for a canister with a canister_name of counter, you can run the following command: +dfx canister call counter get --async +In this example, the command includes the --async option to indicate that you want to make a separate request-status call rather than waiting to poll the replica for the result. +The --async option is useful when processing an operation might take some time to complete. +The option enables you to continue performing other operations then check for the result using a separate dfx canister request-status command. +The returned result will be displayed as the IDL textual format. +
+Using the IDL syntax +You can explicitly specify that you are passing arguments using the IDL syntax by running commands similar to the following for a Text data type: +dfx canister call hello greet --type idl '("Lisa")' +("Hello, Lisa!") + +dfx canister call hello greet '("Lisa")' --type idl +("Hello, Lisa!") +You can also implicitly use the IDL by running a command similar to the following: +dfx canister call hello greet '("Lisa")' +("Hello, Lisa!") +To specify multiple arguments using the IDL syntax, use commas between the arguments. +For example: +dfx canister call contacts insert '("Amy Lu","01 916-335-2042")' + +dfx canister call hotel guestroom '("Deluxe Suite",42,true)' +You can pass raw data in bytes by running a command similar to the following: +dfx canister call hello greet --type raw '4449444c00017103e29883' +This example uses the raw data type to pass a hexadecimal to the greet function of the hello canister. +
+
+
+
+dfx canister create +Use the dfx canister create command to register one or more canister identifiers without compiled code on the {IC} network. +You must be connected to an {IC} network running locally or on a sub-network that you can access to run this command. +Note that you can only run this command from within the project directory structure. +For example, if your project name is hello_world, your current working directory must be the hello_world top-level project directory or one of its subdirectories. +The first time you run the dfx canister create command to register an identifier, your public/private key pair credentials are used to create a default user identity. +The credentials for the default user are migrated from $HOME/.dfinity/identity/creds.pem to $HOME/.config/dfx/identity/default/identity.pem. +
+Basic usage +dfx canister create [option] [flag] [--all | canister_name] +
+
+Flags +You can use the following optional flags with the dfx canister create command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Options +You can use the following options with the dfx canister create command. + + + + + + + + + +Option +Description + + + + +--with-cycles <number-of-cycles> +Enables you to specify the initial number of cycles in a canister when it is created by your wallet. + + + + +
+
+Arguments +You can use the following argument with the dfx canister create command. + + + + + + + + + +Argument +Description + + + + +--all +Enables you to create multiple canister identifiers at once if you have a project dfx.json file that defines multiple canisters. +Note that you must specify --all or an individual canister name. + + +canister_name +Specifies the name of the canister for which you want to register an identifier. +If you are not using the --all option, the canister name is a required argument and must match at least one name that you have configured in the canisters section of the dfx.json configuration file for your project. + + + + +
+
+Examples +You can use the dfx canister create command to register canister identifiers without first compiling any code. +For example, if you want to create the canister identifier for the project my_counter before writing the program, you can run the following command: +dfx canister create my_counter +You can use the dfx canister create command with the --with-cycles option to specify the initial balance upon the creation of one canister or all canisters in a project. For example, to specify an initial balance of 8000000000000 cycles for all canisters, run the following command: +dfx canister create --with-cycles 8000000000000 --all +
+
+
+dfx canister delete +Use the dfx canister delete command to delete a stopped canister from the local Internet Computer network or on a remote Internet Computer network. +Note that you can only run this command from within the project directory structure. +For example, if your project name is hello_world, your current working directory must be the hello_world top-level project directory or one of its subdirectories. +
+Basic usage +dfx canister delete [flag] [--all | canister_name] +
+
+Flags +You can use the following optional flags with the dfx canister delete command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Arguments +You can use the following arguments with the dfx canister delete command. + + + + + + + + + +Argument +Description + + + + +--all +Deletes all of the canisters configured in the dfx.json file. Note that you must specify --all or an individual canister name. + + +canister_name +Specifies the name of the canister you want to delete. +Note that you must specify either a canister name or the --all option. + + + + +
+
+Examples +You can use the dfx canister delete command to delete a specific canister or all canisters. +To delete the hello_world canister, you can run the following command: +dfx canister delete hello_world +To delete all of the canisters you have deployed on the ic Internet Computer network, you can run the following command: +dfx canister --network=ic delete --all +
+
+
+dfx canister id +Use the dfx canister id command to output the canister identifier for a specific canister name. +Note that you can only run this command from within the project directory structure. +For example, if your project name is hello_world, your current working directory must be the hello_world top-level project directory or one of its subdirectories. +
+Basic usage +dfx canister id [flag] canister_name +
+
+Flags +You can use the following optional flags with the dfx canister id command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Arguments +You can use the following argument with the dfx canister id command. + + + + + + + + + +Argument +Description + + + + +canister_name +Specifies the name of the canister for which you want to display an identifier. + + + + +
+
+Examples +You can use the dfx canister id command to display the canister identifier for a specific canister name. +To display the canister identifier for the hello_world canister, you can run the following command: +dfx canister id hello_world +The command displays output similar to the following: +75hes-oqbaa-aaaaa-aaaaa-aaaaa-aaaaa-aaaaa-q +
+
+
+dfx canister install +Use the dfx canister install command to install compiled code as a canister on the {IC} network running locally or on a sub-network that you can access. +
+Basic usage +dfx canister install [flag] [option] [--all | canister_name] +
+
+Flags +You can use the following optional flags with the dfx canister install command. + + + + + + + + + +Flag +Description + + + + +--async +Enables you to continue without waiting for the result of the installation to be returned by polling the replica. + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Options +You can use the following options with the dfx canister install command. + + + + + + + + + +Option +Description + + + + +--argument <argument> +Specifies an argument to pass to the canister during installation. + + +--argument-type <argument-type> +Specifies the data format for the argument when you install using the --argument option. The valid values are idl and raw. +By default, you can specify arguments using the Candid (idl) syntax for data values. +For information about using Candid and its supported types, see Interact with a service in a terminal and Supported types. +You can use raw as the argument type if you want to pass raw bytes to a canister. + + +-c, --compute-allocation <compute-allocation> +Defines a compute allocation—essentially the equivalent of setting a CPU allocation—for canister execution. +You can set this value as a percentage in the range of 0 to 100. + + +--memory-allocation <memory-allocation> +Specifies how much memory the canister is allowed to use in total. +You can set this value in the range of 0 to 8MB. + + +-m, --mode <mode> +Specifies whether you want to install, reinstall, or upgrade canisters. +For more information about installation modes and canister management, see Managing canisters. + + + + +
+
+Arguments +You can use the following arguments with the dfx canister install command. + + + + + + + + + +Argument +Description + + + + +--all +Enables you to install multiple canisters at once if you have a project dfx.json file that includes multiple canisters. +Note that you must specify --all or an individual canister name. + + +canister_name +Specifies the name of the canister to deploy. +If you are not using the --all option, the canister name is a required argument and should match the name you have configured for a project in the canisters section of the dfx.json configuration file. + + + + +
+
+Examples +You can use the dfx canister install command to deploy WebAssembly you have compiled using the dfx build command as a canister on the network. +The most common use case is to install all of the canisters by running the following command: +dfx canister install --all +
+Installing a specific canister +You can also use the dfx canister install command to deploy a specific canister instead of all of the canisters in your project. +For example, if you have a project with a hello_world canister and a hello_world_assets canister but only want to deploy the hello_world canister, you can deploy just that the canister by running the following command: +dfx canister install hello_world +
+
+Sending an asynchronous request +If you want to submit a request to install the canister and return a request identifier to check on the status of your request later instead of waiting for the command to complete, you can run a command similar to the following: +dfx canister install hello_world --async +This command submits a request to install the canister and returns a request identifier similar to the following: +0x58d08e785445dcab4ff090463b9e8b12565a67bf436251d13e308b32b5058608 +You can then use the request identifier to check the status of the request at a later time, much like a tracking number if you were shipping a package. +
+
+Overriding the default network provider +If you want to deploy a canister on a specific {IC} network without changing the settings in your dfx.json configuration file, you can explicitly specify the network you want to connect to by using the +--network option. +For example, you can specify a remote network URL by running a command similar to the following: +dfx canister --network \http://192.168.3.1:5678 install --all +Note that you must specify the network parameter before the canister operation (install) and before the canister name or --all flag. +
+
+Allocating message processing +The --compute-allocation options allows you to allocate computing resources as a percentage in the range of 0 to 100 to indicate how often your canister should be scheduled for execution. +For example, assume you run the following command: +dfx canister install --all --compute-allocation 50 +With this setting, all of the canisters in the current projects are assigned a 50% allocation. When canisters in the project receive input messages to process, the messages are scheduled for execution. +Over 100 execution cycles, each canister’s messages will be scheduled for processing at least 50 times. +The default value for this option is 0—indicating that no specific allocation or scheduling is in effect. +If all of your canisters use the default setting, processing occurs in a round-robin fashion. +
+
+
+
+dfx canister request-status +Use the dfx canister request-status command to request the status of a specified call to a canister. +This command requires you to specify the request identifier you received after invoking a method on the canister. +The request identifier is an hexadecimal string starting with 0x. +
+Basic usage +dfx canister request-status request_id +
+
+Flags +You can use the following optional flags with the dfx canister request-status command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Arguments +You can specify the following argument for the dfx canister request-status command. + + + + + + + + + +Argument +Description + + + + +request_id +Specifies the hexadecimal string returned in response to a dfx canister call or dfx canister install command. +This identifier is an hexadecimal string starting with 0x. + + + + +
+
+Examples +You can use the dfx canister request-status command to check on the status of a canister state change or to verify that a call was not rejected by running a command similar to the following: +dfx canister request-status 0x58d08e785445dcab4ff090463b9e8b12565a67bf436251d13e308b32b5058608 +This command displays an error message if the request identifier is invalid or refused by the canister. +
+
+
+dfx canister set-controller +Use the dfx canister set-controller command to specify the identity name or principal to use as the new controller for a specified canister on the Internet Computer network. +A controller identity has special rights to manage the canister it controls. +For example, only a controlling identity can be used to install, upgrade, or delete the canister under its control. +Note that you can specify either a user identity or a canister as a controller. +You can also specify the controller identity by using its name or its principal. +
+Basic usage +dfx canister set-controller [flag] canister new-controller +
+
+Flags +You can use the following optional flags with the dfx canister set-controller command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Arguments +You must use the following arguments with the dfx canister set-controller command. + + + + + + + + + +Argument +Description + + + + +<canister> +Specifies the canister name or canister identifier to be controlled by the identity you specify using the new_controller argument. + + +<new_controller> +Specifies the identity name or principal of the controller. + + + + +
+
+Examples +You can use the dfx canister set-controller command to specify a user or canister as the controlling identity for a specific canister. +For example, you might create a new identity called pubsadmin then run the dfx canister set-controller to specify that you want the pubsadmin identity to be the controller of the hello_world canister by running the following commands: +dfx identity new pubsadmin +dfx canister set-controller hello_world pubsadmin +To set the controlling identity using the textual representation of the identity principal, you might run a command similar to the following: +dfx canister set-controller hello_world wcp5u-pietp-k5jz4-sdaaz-g3x4l-zjzxa-lxnly-fp2mk-j3j77-25qat-pqe +Although specifying a user identity name or principal is one potential use case, a more common scenario is to specify the wallet canister that you want to use to send cycles to the canister. +The following steps illustrate this scenario when you are doing local development. For this example, assume you have created a project called open_sf with two canisters deployed on the {IC} running locally. + + +Create an identity—for example, sf-controller—to act as the controller. +dfx identity new sf-controller + +Creating identity: "sf-controller". +Created identity: "sf-controller". + + +Make the new identity the active identity. +dfx identity use sf-controller + +Using identity: "sf-controller". + + +Generate a wallet canister identifier for the new identity. +dfx identity get-wallet + +Creating a wallet canister on the local network. +r7inp-6aaaa-aaaaa-aaabq-cai +The wallet canister on the "local" network for user "sf-controller" is "r7inp-6aaaa-aaaaa-aaabq-cai" + + +Switch the active identity to the current controller of the canister. For example, if the default identity was used to create the canister, you would run the following command: +dfx identity use default + +Using identity: "default". + + +Set the controller for a specified canister to use the wallet associated wit the sf-controller identity. +dfx canister set-controller open_sf_assets r7inp-6aaaa-aaaaa-aaabq-cai + +Set "r7inp-6aaaa-aaaaa-aaabq-cai" as controller of "open_sf_assets". +You can now use the wallet canister r7inp-6aaaa-aaaaa-aaabq-cai to send cycles or add custodians to the open_sf_assets canister. + + +
+
+
+dfx canister send +Use the dfx canister send command after signing a message with the dfx canister sign command when you want to separate these steps, rather than using the single dfx canister call command. Using separate calls can add security to the transaction. +For example, when creating your neuron stake, you might want to use the dfx canister sign command to create a signed message.json file using an air-gapped computer, then use the dfx canister send command to deliver the signed message. +
+Basic usage +dfx canister send file_name +
+
+Flags +You can use the following optional flags with the dfx canister request-status command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Arguments +You can specify the following argument for the dfx canister send command. + + + + + + + + + +Argument +Description + + + + +file_name +Specifies the file name of the message. + + + + +
+
+Examples +Use the dfx canister send command to send a signed message created using the dfx canister sign command to the genesis token canister (GTC) to create a neuron on your behalf by running the following command: +dfx canister send message.json +
+
+
+dfx canister sign +Use the dfx canister sign command before sending a message with the dfx canister send command when you want to separate these steps, rather than using the single dfx canister call command. Using separate calls can add security to the transaction. +For example, when creating your neuron stake, you might want to use the dfx canister sign command to create a signed message.json file using an air-gapped computer, then use the dfx canister send command to deliver the signed message from a computer connected to the network. +
+Basic usage +dfx canister sign [flag] [option] canister-name method-name [argument] +
+
+Flags +You can use the following optional flags with the dfx canister sign command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +--query +Sends a query request to a canister. + + +--update +Sends an update request to the canister. This is the default method if the --query method is not used. + + +-V, --version +Displays version information. + + + + +
+
+Options +You can specify the following options for the dfx canister sign command. + + + + + + + + + +Option +Description + + + + +--expire-after <expire-after> +Specifies how long will will be valid before it expires and cannot be sent. Specify in seconds. If not defined, the default is 300s (5m) + + +--file <file> +Specifies the output file name. The default is message.json. + + +--random <random> +Specifies the configuration for generating random arguments. + + +--type <type> +Specifies the data type for the argument when making a call using an argument.By default, you can specify arguments using the Candid (idl) syntax for data values. +For information about using Candid and its supported types, see Interact with a service in a terminal and Supported types. +You can use raw as the argument type if you want to pass raw bytes. + + + + +
+
+Arguments +You can specify the following arguments for the dfx canister sign command. + + + + + + + + + +Argument +Description + + + + +canister_name +Specifies the name of the canister to call. The canister name is a required argument and should match the name you have configured for a project in the canisters section of the dfx.json configuration file. + + +method_name +Specifies the method name to call on the canister. +The canister method is a required argument. + + +argument +Specifies the argument to pass to the method. +Depending on your program logic, the argument can be a required or optional argument. +You can specify a data format type using the --type option if you pass an argument to the canister. +By default, you can specify arguments using the Candid (idl) syntax for data values. +For information about using Candid and its supported types, see Interact with a service in a terminal and Supported types. +You can use raw as the argument type if you want to pass raw bytes. + + + + +
+
+Examples +Use the dfx canister sign command to create a signed message.json file using the principal associated with the identity you created using the Privacy Enhanced Mail (PEM) file by running a command similar to the following: +dfx canister --no-wallet --network=ic sign --expire-after=1h rno2w-sqaaa-aaaaa-aaacq-cai create_neurons ‘(“PUBLIC_KEY”)’ +Currently, the --no-wallet command must be used to execute the command using the user identity instead of the cycles wallet canister identifier. +This command illustrates how to creates a message.json file to create neurons on the network stpecified by the ic alias, that is signed using your principal identifier as the message sender and with an expiration window that ends in one hour. +Note that the time allotted to send a signed message is a fixed 5-minute window. The --expire-after option enables you to specify the point in time when the 5-minute window for sending the signed message should end. For example, if you set the --expire-after option to one hour (1h), you must wait at least 55 minutes before you send the generated message and the signature for the message is only valid during the 5-minute window ending in the 60th minute. +In this example, therefore, you would need to send the message after 55 minutes and before 60 minutes for the message to be recognized as valid. +If you don’t specify the --expire-after option, the default expiration is five minutes. +Send the signed message to the genesis token canister (GTC) to create a neuron on your behalf by running the following command: +dfx canister send message.json +
+
+
+dfx canister start +Use the dfx canister start command to restart a stopped canister on the local Internet Computer network or on a remote Internet Computer network. +In most cases, you run this command after you have stopped a canister to properly terminate any pending requests as a prerequisite to upgrading the canister. +Note that you can only run this command from within the project directory structure. +For example, if your project name is hello_world, your current working directory must be the hello_world top-level project directory or one of its subdirectories. +
+Basic usage +dfx canister start [flag] [--all | canister_name] +
+
+Flags +You can use the following optional flags with the dfx canister start command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Arguments +You can use the following arguments with the dfx canister start command. + + + + + + + + + +Argument +Description + + + + +--all +Starts all of the canisters configured in the dfx.json file. Note that you must specify --all or an individual canister name. + + +canister_name +Specifies the name of the canister you want to start. +Note that you must specify either a canister name or the --all option. + + + + +
+
+Examples +You can use the dfx canister start command to start a specific canister or all canisters. +To start the hello_world canister, you can run the following command: +dfx canister start hello_world +To start all of the canisters you have deployed on the ic Internet Computer network, you can run the following command: +dfx canister --network=ic start --all +
+
+
+dfx canister status +Use the dfx canister status command to check whether a canister is currently running, in the process of stopping, or currently stopped on the local Internet Computer network or on a remote Internet Computer network. +Note that you can only run this command from within the project directory structure. +For example, if your project name is hello_world, your current working directory must be the hello_world top-level project directory or one of its subdirectories. +
+Basic usage +dfx canister status [flag] [--all | canister_name] +
+
+Flags +You can use the following optional flags with the dfx canister status command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Arguments +You can use the following arguments with the dfx canister status command. + + + + + + + + + +Argument +Description + + + + +--all +Returns status information for all of the canisters configured in the dfx.json file. Note that you must specify --all or an individual canister name. + + +canister_name +Specifies the name of the canister you want to return information for. +Note that you must specify either a canister name or the --all option. + + + + +
+
+Examples +You can use the dfx canister status command to check the status of a specific canister or all canisters. +To check the status of the hello_world canister, you can run the following command: +dfx canister status hello_world +To check the status for all of the canisters you have deployed on the ic Internet Computer network, you can run the following command: +dfx canister --network=ic status --all +
+
+
+dfx canister stop +Use the dfx canister stop command to stop a canister that is currently running on the local Internet Computer network or on a remote Internet Computer network. +In most cases, you run this command to properly terminate any pending requests as a prerequisite to upgrading the canister. +Note that you can only run this command from within the project directory structure. +For example, if your project name is hello_world, your current working directory must be the hello_world top-level project directory or one of its subdirectories. +
+Basic usage +dfx canister stop [flag] [--all | canister_name] +
+
+Flags +You can use the following optional flags with the dfx canister stop command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Arguments +You can use the following arguments with the dfx canister stop command. + + + + + + + + + +Argument +Description + + + + +--all +Stops all of the canisters configured in the dfx.json file. Note that you must specify --all or an individual canister name. + + +canister_name +Specifies the name of the canister you want to stop. +Note that you must specify either a canister name or the --all option. + + + + +
+
+Examples +You can use the dfx canister stop command to start a specific canister or all canisters. +To stop the hello_world canister, you can run the following command: +dfx canister stop hello_world +To stop all of the canisters you have deployed on the ic Internet Computer network, you can run the following command: +dfx canister --network=ic stop --all +
+
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/cli-reference/dfx-config.xml b/modules/developers-guide/pages/cli-reference/dfx-config.xml new file mode 100644 index 000000000..c76b65e59 --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-config.xml @@ -0,0 +1,119 @@ + + + +
+ +dfx config +2021-08-05 + +Use the dfx config command to view or configure settings in the configuration file for a current project. +Note that you can only run this command from within the project directory structure. +For example, if your project name is hello_world, your current working directory must be the hello_world top-level project directory or one of its subdirectories. +
+Basic usage +dfx config [config_path] [value] [flag] +
+
+Flags +You can use the following optional flags with the dfx config command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Options +You can use the following option with the dfx config command. + + + + + + + + + +Option +Description + + + + +--format +Specifies the format of the configuration file output. +By default, the file is displayed using JSON format. +The valid values are json and text. + + + + +
+
+Arguments +You can specify the following arguments for the dfx config command. + + + + + + + + + +Argument +Description + + + + +config_path +Specifies the name of the configuration option that you want to set or read. +You must specify the configuration file option using its period-delineated path to set or read the specific option you want to change or view. +If you don’t specify the path to a specific configuration option, the command displays the full configuration file. + + +value +Specifies the new value for the option you are changing. +If you don’t specify a value, the command returns the current value for the option from the configuration file. + + + + +
+
+Examples +You can use the dfx config command to change configuration settings such as the location of the default output directory or the name of your main program file. +For example, to change the default build output directory from canisters to staging, you can run the following command: +dfx config defaults.build.output "staging/" +To view the current value for a configuration setting, you can specify the path to the setting in the configuration file without specifying a value. +For example: +dfx config defaults.build.output +The command returns the current value for the configuration option: +"staging/" +Similarly, you can change the name of the main source file or the port number for the local network replica by running commands similar to the following: +dfx config canisters.hello.main "src/hello_world/hello-main.mo" +dfx config networks.local.bind 127.0.0.1:5050 +You can also verify your configuration changes by viewing the dfx.json configuration file after running the dfx config command. +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/cli-reference/dfx-deploy.xml b/modules/developers-guide/pages/cli-reference/dfx-deploy.xml new file mode 100644 index 000000000..27dee3889 --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-deploy.xml @@ -0,0 +1,130 @@ + + + +
+ +dfx deploy +2021-08-05 + +Use the dfx deploy command to register, build, and deploy an application locally or on a specified network. +By default, all canisters defined in the project dfx.json configuration file are deployed. +This command simplifies the developer workflow by enabling you to run one command instead of running the following commands as separate steps: +dfx canister create --all +dfx build +dfx canister install --all +Note that you can only run this command from within the project directory structure. +For example, if your project name is hello_world, your current working directory must be the hello_world top-level project directory or one of its subdirectories. +
+Basic usage +dfx deploy [flag] [option] [canister_name] +
+
+Flags +You can use the following optional flags with the dfx deploy command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Options +You can use the following options with the dfx deploy command. + + + + + + + + + +Option +Description + + + + +--network <network> +Overrides the network to connect to. +By default, the local network is used. + + +--argument <argument> +Specifies an argument using Candid syntax to pass to the canister during deployment. +Note that this option requires you to define an actor class in the {proglang} program. + + +--with-cycles <number-of-cycles> +Enables you to specify the initial number of cycles for a canister in a project. + + + + +
+Arguments +You can specify the following arguments for the dfx deploy command. + + + + + + + + + +Argument +Description + + + + +canister_name +Specifies the name of the canister you want to register, build, and deploy. +Note that the canister name you specify must match at least one name in the canisters section of the dfx.json configuration file for the project. +If you don’t specify a canister name, dfx deploy will deploy all canisters defined in the dfx.json file. + + + + +
+
+
+Examples +You can use the dfx deploy command to deploy all or specific canisters locally or on a specified network. +For example, to deploy the hello project on the ic-pubs network provider configured in the dfx.json configuration file, you can run the following command: +dfx deploy hello --network ic-pubs +To deploy a project locally and pass a single argument to the installation step, you can run a command similar to the following: +dfx deploy hello_actor_class --argument '("from DFINITY")' +Note that currently you must use an actor class in your {proglang} program. +In this example, the dfx deploy command specifies an argument to pass to the hello_actor_class canister. +The main program for the hello_actor_class canister looks like this: +actor class Greet(name: Text) { + public query func greet() : async Text { + return "Hello, " # name # "!"; + }; +}; +You can use the dfx deploy command with the --with-cycles option to specify the initial balance of a canister created by your wallet. If you don’t specify a canister, the number of cycles you specify will be added to all canisters by default. To avoid this, specify a specific canister by name. For example, to add an initial balance of 8000000000000 cycles to a canister called "hello-assets", run the following command: +dfx deploy --with-cycles 8000000000000 hello-assets +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/cli-reference/dfx-envars.xml b/modules/developers-guide/pages/cli-reference/dfx-envars.xml new file mode 100644 index 000000000..c0b8923b2 --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-envars.xml @@ -0,0 +1,50 @@ + + + +
+ +Environment variables +2021-08-05 + +You can configure certain properties for your {sdk-short-name} execution environment using environment variables. +This section lists the environment variables that are currently supported with examples of how to use them. +In most cases, you can set environment variables for a session by executing an command in the terminal or by adding a line similar to the following to your .profile file: +export DFX_TELEMETRY_DISABLED=1 +
+CANISTER_CANDID_PATH_{canister.name} +Use environment variables with the CANISTER_CANDID_PATH prefix to reference the path to the Candid description file for the canisters that are listed as dependencies in the dfx.json file for your project. +For example, if you have a whoami_assets canister that lists whoami under the dependencies key, you could use the CANISTER_CANDID_PATH_whoami_assets environment variable to refer to the location of the whoami.did file, which for local development might be: +$PROJECT_ROOT/.dfx/local/canisters/whoami/whoami.did +
+
+CANISTER_ID_{canister.name} +Use environment variables with the CANISTER_ID prefix to reference the canister identifier for each canister in the dfx.json file for your project. +For example, if you have a linkedup project that consists of the linkedup and connectd canisters, you could use the CANISTER_ID_linkedup and CANISTER_ID_connectd environment variables to refer to the canister identifiers—for example ryjl3-tyaaa-aaaaa-aaaba-cai and rrkah-fqaaa-aaaaa-aaaaq-cai—created for your project. +
+
+DFX_CONFIG_ROOT +Use the DFX_CONFIG_ROOT environment variable to specify a different location for storing the .cache and .config subdirectories for dfx. +By default, the .cache and .config directories are located in the home directory for your development environment. +For example, on macOS the default location is in the /Users/<YOUR-USER-NAME> directory. +Use the DFX_CONFIG_ROOT environment variable to specify a different location for these directories. +DFX_CONFIG_ROOT=~/ic-root +
+
+DFX_INSTALLATION_ROOT +Use the DFX_INSTALLATION_ROOT environment variable to specify a different location for the dfx binary if you are not using the default location for your operating system. +The .cache/dfinity/uninstall.sh script uses this environment variable to identify the root directory for your {sdk-short-name} installation. +
+
+DFX_TELEMETRY_DISABLED +Use the DFX_TELEMETRY_DISABLED environment variable to opt-out of having data collected about dfx usage. +By default, dfx is configured to collect anonymous—that is, no identifying information such as IP addresses or user information—data about dfx command activity and errors. +Collecting anonymous data is enabled by default in an effort to improve the developer experience based on usage patterns and behavior. +If you want to prevent the collection of data about dfx usage, however, you can explicitly opt-out by setting the DFX_TELEMETRY_DISABLED environment variable to one. +DFX_TELEMETRY_DISABLED=1 +
+
+DFX_VERSION +Use the DFX_VERSION environment variable to identify a specific version of the {sdk-short-name} that you want to install. +DFX_VERSION=0.8.0 sh -ci "$(curl -fsSL https://sdk.dfinity.org/install.sh)" +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/cli-reference/dfx-help.xml b/modules/developers-guide/pages/cli-reference/dfx-help.xml new file mode 100644 index 000000000..2dbfd1d2a --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-help.xml @@ -0,0 +1,46 @@ + + + +
+ +dfx help +2021-08-05 + +Use this command to view usage information for the dfx parent command or for any specified subcommand. +
+Basic usage +dfx help [subcommand] +
+
+Arguments +You can specify any dfx subcommand as an argument to view usage information for that subcommand using the dfx help command. + + + + + + + + + +Argument +Description + + + + +subcommand +Specifies the subcommand usage information you want to display. + + + + +
+
+Examples +To display the usage information for dfx, run the following command: +dfx help +To display the usage information for dfx bew, run the following command: +dfx help new +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/cli-reference/dfx-identity.xml b/modules/developers-guide/pages/cli-reference/dfx-identity.xml new file mode 100644 index 000000000..6cdfdb077 --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-identity.xml @@ -0,0 +1,673 @@ + + + +
+ +dfx identity +2021-08-05 + +Use the dfx identity command with subcommands and flags to manage the identities used to execute commands and communicate with the Internet Computer network. +Creating multiple user identities enables you to test user-based access controls. +The basic syntax for running dfx identity commands is: +dfx identity [subcommand] [flag] +Depending on the dfx identity subcommand you specify, additional arguments, options, and flags might apply or be required. +To view usage information for a specific dfx identity subcommand, specify the subcommand and the --help flag. +For example, to see usage information for dfx identity new, you can run the following command: +dfx identity new --help +For reference information and examples that illustrate using dfx identity commands, select an appropriate command. + + + + + + + + + +Command +Description + + + + +get-principal +Shows the textual representation of the principal associated with the current identity. + + +get-wallet +Shows the canister identifier for the wallet associated with your current identity principal on a network. + + +help +Displays this usage message or the help of the given subcommand(s). + + +import +Creates a new identity by importing a PEM file that contains the key information or security certificate for a principal. + + +list +Lists existing identities. + + +new +Creates a new identity. + + +remove +Removes an existing identity. + + +rename +Renames an existing identity. + + +set-wallet +Sets the wallet canister identifier to use for your current identity principal on a network. + + +use +Specifies the identity to use. + + +whoami +Displays the name of the current identity user context. + + + + +
+Creating a default identity +The first time you run the dfx canister create command to register an identifier, your public/private key pair credentials are used to create a default user identity. +The credentials for the default user are migrated from $HOME/.dfinity/identity/creds.pem to $HOME/.config/dfx/identity/default/identity.pem. +You can then use dfx identity new to create new user identities and store credentials for those identities in $HOME/.config/dfx/identity/<identity_name>/identity.pem files. +For example, you can create an identity named ic_admin by running the following command: +dfx identity new ic_admin +This command adds a private key for the ic_admin user identity in the ~/.config/dfx/identity/ic_admin/identity.pem file. +
+
+dfx identity get-principal +Use the dfx identity get-principal command to display the textual representation of a principal associated with the current user identity context. +If you haven’t created any user identities, you can use this command to display the principal for the default user. +The textual representation of a principal can be useful for establishing and testing role-based authorization scenarios. +
+Basic usage +dfx identity get-principal [flag] +
+
+Flags +You can use the following optional flags with the dfx identity get-principal command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Example +If you want to display the textual representation of a principal associated with a specific user identity context, you can run commands similar to the following: +dfx identity use ic_admin +dfx identity get-principal +In this example, the first command sets the user context to use the ic_admin identity. The second command then returns the principal associated with the ic_admin identity. +
+
+
+dfx identity get-wallet +Use the dfx identity get-wallet command to display the canister identifier for the wallet associated with your current identity principal on a network. +Note that you must be connected to the {IC} network or running the network locally to run this command. +In addition, you must be in a project directory to run the command. +For example, if your project name is hello_world, your current working directory must be the hello_world top-level project directory or one of its subdirectories to run the dfx identity get-wallet command. +
+Basic usage +dfx identity get-wallet [flag] +
+
+Flags +You can use the following optional flags with the dfx identity get-wallet command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Example +If you want to display the canister identifier for the wallet canister associated with your identity, you can run the following command: +dfx identity get-wallet +To display the canister identifier for the wallet canister associated with your identity on a specific network, you might run a command similar to the following: +dfx identity --network=https://192.168.74.4 get-wallet +
+
+
+dfx identity import +Use the dfx identity import command to create a user identity by importing the user’s key information or security certificate from a PEM file. +
+Basic usage +dfx identity import [flag] identity-name pem_file-name +
+
+Flags +You can use the following optional flags with the dfx identity import command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Examples +You can use the dfx identity import command to import a PEM file that contains the security certificate to use for an identity. +For example, you can run the following command to import the generated-id.pem file to create the user identity alice: +dfx identity import alice generated-id.pem +The command adds the generated-id.pem file to the ~/.config/dfx/identity/alice directory. +
+
+
+dfx identity list +Use the dfx identity list command to display the list of user identities available. +When you run this command, the list displays an asterisk (*) to indicate the currently active user context. +You should note that identities are global. They are not confined to a specific project context. +Therefore, you can use any identity listed by the dfx identity list command in any project. +
+Basic usage +dfx identity list [flag] +
+
+Flags +You can use the following optional flags with the dfx identity list command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Examples +You can use the dfx identity list command to list all of the identities you have currently available and to determine which identity is being used as the currently-active user context for running dfx commands. +For example, you can run the following command to list the identities available: +dfx identity list +This command displays the list of identities found similar to the following: +alice_auth +bob_standard * +default +ic_admin +In this example, the bob_standard identity is the currently-active user context. +After you run this command to determine the active user, you know that any additional dfx commands you run are executed using the principal associated with the bob_standard identity. +
+
+
+dfx identity new +Use the dfx identity new command to add new user identities. +You should note that the identities you add are global. They are not confined to a specific project context. +Therefore, you can use any identity you add using the dfx identity new command in any project. +
+Basic usage +dfx identity new [flag] _identity-name_ +
+
+Flags +You can use the following optional flags with the dfx identity new command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Arguments +You must specify the following argument for the dfx identity new command. + + + + + + + + + +Argument +Description + + + + +<identity_name> +Specifies the name of the identity to create. +This argument is required. + + + + +
+
+Examples +You can then use dfx identity new to create new user identities and store credentials for those identities in $HOME/.config/dfx/identity/<identity_name>/identity.pem files. +For example, you can create an identity named ic_admin by running the following command: +dfx identity new ic_admin +This command adds a private key for the ic_admin user identity in the ~/.config/dfx/identity/ic_admin/identity.pem file. +After adding the private key for the new identity, the command displays confirmation that the identity has been created: +Creating identity: "ic_admin". +Created identity: "ic_admin". +
+
+
+dfx identity remove +Use the dfx identity remove command to remove an existing user identity. +You should note that the identities you add are global. They are not confined to a specific project context. +Therefore, any identity you remove using the dfx identity remove command will no longer be available in any project. +
+Basic usage +dfx identity remove [flag] _identity-name_ +
+
+Flags +You can use the following optional flags with the dfx identity remove command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Arguments +You must specify the following argument for the dfx identity remove command. + + + + + + + + + +Argument +Description + + + + +<identity_name> +Specifies the name of the identity to remove. +This argument is required. + + + + +
+
+Examples +You can use the dfx identity remove command to remove any previously-created identity, including the default user identity. +For example, if you have added named user identities and want to remove the default user identity, you can run the following command: +dfx identity remove default +The command displays confirmation that the identity has been removed: +Removing identity "default". +Removed identity "default". +Although you can delete the default identity if you have created other identities to replace it, you must always have at least one identity available. +If you attempt to remove the last remaining user context, the dfx identity remove command displays an error similar to the following: +Identity error: + Cannot delete the default identity +
+
+
+dfx identity rename +Use the dfx identity rename command to rename an existing user identity. +You should note that the identities you add are global. They are not confined to a specific project context. +Therefore, any identity you rename using the dfx identity rename command is available using the new name in any project. +
+Basic usage +dfx identity rename [flag] _from_identity-name_ _to_identity-name_ +
+
+Flags +You can use the following optional flags with the dfx identity rename command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Arguments +You must specify the following arguments for the dfx identity rename command. + + + + + + + + + +Argument +Description + + + + +<from_identity_name> +Specifies the current name of the identity you want to rename. +This argument is required. + + +<to_identity_name> +Specifies the new name of the identity you want to rename. +This argument is required. + + + + +
+
+Example +You can rename the default user or any identity you have previously created using the dfx identity rename command. +For example, if you want to rename a test_admin identity that you previously created, you would specify the current identity name you want to change from and the new name you want to change to by running a command similar to the following: +dfx identity rename test_admin devops +
+
+
+dfx identity set-wallet +Use the dfx identity set-wallet command to specify the wallet canister identifier to use for your identity on a network. +
+Basic usage +dfx identity set-wallet [flag] [--canister-name canister-name] +
+
+Flags +You can use the following optional flags with the dfx identity set-wallet command. + + + + + + + + + +Flag +Description + + + + +force +Skips verification that the canister you specify is a valid wallet canister. +This option is only useful if you are connecting to the {IC} running locally. + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Example +If you have access to more than one {IC} network or use more than one principal for your identity, you might have access to more than one wallet canister identifier. +You can use the dfx identity set-wallet command to specify the wallet canister identifier to use for a given identity on a given network. +For example, you might store the wallet canister identifier in an environment variable, then invoke the dfx identity set-wallet command to use that wallet canister for additional operations by running the following: +export WALLET_CANISTER_ID=$(dfx identity get-wallet) +dfx identity --network=https://192.168.74.4 set-wallet --canister-name ${WALLET_CANISTER_ID} +
+
+
+dfx identity use +Use the dfx identity use command to specify the user identity you want to active. +You should note that the identities you have available to use are global. They are not confined to a specific project context. +Therefore, you can use any identity you have previously created in any project. +
+Basic usage +dfx identity use [flag] _identity-name_ +
+
+Flags +You can use the following optional flags with the dfx identity use command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Arguments +You must specify the following argument for the dfx identity use command. + + + + + + + + + +Argument +Description + + + + +<identity_name> +Specifies the name of the identity you want to make active for subsequent commands. +This argument is required. + + + + +
+
+Examples +If you want to run multiple commands with the same user identity context, you can run a command similar to the following: +dfx identity use ops +After running this command, subsequent commands use the credentials and access controls associated with the ops user. +
+
+
+dfx identity whoami +Use the dfx identity whoami command to display the name of the currently-active user identity context. +
+Basic usage +dfx identity whoami [flag] +
+
+Flags +You can use the following optional flags with the dfx identity whoami command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Example +If you want to display the name of the currently-active user identity, you can run the following command: +dfx identity whoami +The command displays the name of the user identity. +For example, you had previously run the command dfx identity use bob_standard, the command would display: +bob_standard +
+
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/cli-reference/dfx-ledger.xml b/modules/developers-guide/pages/cli-reference/dfx-ledger.xml new file mode 100644 index 000000000..980fbb038 --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-ledger.xml @@ -0,0 +1,601 @@ + + + +
+ +dfx ledger +2021-08-05 + +Use the dfx ledger command to interact with the ledger canister. +This command can be used to make ICP utlity token transactions from one to another, or top up canisters with cycles from ICP. +The basic syntax for running dfx ledger commands is: +dfx ledger [options] [subcommand] +Depending on the dfx ledger subcommand you specify, additional arguments, options, and flags might apply. For reference information and examples that illustrate using dfx ledger commands, select an appropriate command. + + + + + + + + + +Command +Description + + + + +account-id +Prints the selected identity’s Account Identifier. + + +balance +Prints the account balance of the user. + + +create-canister +Creates a canister from ICP. + + +help +Displays usage information message for a specified subcommand. + + +notify +Notifies the ledger when there is a send transaction to the cycles minting canister. + + +top-up +Tops up a canister with cycles minted from ICP. + + +transfer +Transfers ICP from the user to the destination Account Identifier. + + + + +To view usage information for a specific subcommand, specify the subcommand and the --help flag. +For example, to see usage information for dfx ledger transfer, you can run the following command: +dfx ledger transfer --help +
+dfx ledger account-id +Use the dfx ledger account-id command to display the account identifier associated with the currently-active identity. +Like the textual representation of your developer identity principal, the account identifier is derived from your private key and used to represent your identity in the ledger canister. +
+Basic usage +dfx ledger account-id [flag] +
+
+Flags +You can use the following optional flags with the dfx ledger account-id command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Examples +If you have created more than one identity, check the identity you are currently using by running the dfx identity whoami command or the dfx identity get-principal command. You can then check the account identifier for your currently-selected developer identity by running the following command: +dfx ledger account-id +The command displays output similar to the following: +03e3d86f29a069c6f2c5c48e01bc084e4ea18ad02b0eec8fccadf4487183c223 +
+
+
+dfx ledger balance +Use the dfx ledger balance command to print your account balance or that of another user. +
+Basic usage +dfx ledger --network ic balance [of] [flag] +
+
+Flags +You can use the following optional flags with the dfx ledger balance command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Arguments +You can specify the following argument for the dfx ledger balance command. + + + + + + + + + +Argument +Description + + + + +<of> +Specify an Account Identifier to get the balance. If this command is not specified, the command returns the balance of ICP tokens for the currently-selected user identity. + + + + +
+
+Examples +You can use the dfx ledger balance command to check the balance of another user. +For example, you can run the following command to see the ICP utlity tokens associated with a known Account Identifier: +dfx ledger --network ic balance 03e3d86f29a069c6f2c5c48e01bc084e4ea18ad02b0eec8fccadf4487183c223 +This command displays an ICP amount similar to the following: +2.49798000 ICP +
+
+
+dfx ledger create-canister +Use the dfx ledger create-canister command to convert ICP tokens to cycles and to register a new canister identifier on the {IC}. +
+Basic usage +dfx ledger --network ic create-canister controller [options] [flag] +
+
+Flags +You can use the following optional flags with the dfx ledger create-canister command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Arguments +You can specify the following argument for the dfx ledger create-canister command. + + + + + + + + + +Argument +Description + + + + +<controller> +Specifies the principal identifier to set as the controller of the new canister. + + + + +
+
+Options +You can specify the following argument for the dfx ledger create-canister command. + + + + + + + + + +Option +Description + + + + +--amount <amount> +Specify the number of ICP tokens to mint into cycles and deposit into destination canister. You can specify an amount as a number with up to eight (8) decimal places. + + +--e8s <e8s> +Specify ICP token fractional units—called e8s—as a whole number, where one e8 is smallest partition of an ICP token. For example, 1.05000000 is 1 ICP and 5000000 e8s. You can use this option on its own or in conjunction with the --icp option. + + +--fee <fee> +Specify a transaction fee. The default is 10000 e8s. + + +--icp <icp> +Specify ICP tokens as a whole number. You can use this option on its own or in conjunction with --e8s. + + +--max-fee <max-fee> +Specify a maximum transaction fee. The default is 10000 e8s. + + + + +
+
+Examples +To create a new canister with cycles, transfer ICP tokens from your ledger account by running a command similar to the following: +dfx ledger --network ic create-canister tsqwz-udeik-5migd-ehrev-pvoqv-szx2g-akh5s-fkyqc-zy6q7-snav6-uqe --amount 1.25 +This command converts the number of ICP tokens you specify for the --amount argument into cycles, and associates the cycles with a new canister identifier controlled by the principal you specify. +In this example, the command converts 1.25 ICP tokens into cycles and specifies the principal identifier for the default identity as the controller of the new canister. +If the transaction is successful, the ledger records the event and you should see output similar to the following: +Transfer sent at BlockHeight: 20 +Canister created with id: "53zcu-tiaaa-aaaaa-qaaba-cai" +You can create a new canister by specifying separate values for ICP tokens and e8s by running a command similar to the following: +dfx ledger --network ic create-canister tsqwz-udeik-5migd-ehrev-pvoqv-szx2g-akh5s-fkyqc-zy6q7-snav6-uqe --icp 3 --e8s 5000 +
+
+
+dfx ledger notify +Use the dfx ledger notify command to notify the ledger about a send transaction to the cycles minting canister. +This command should only be used if dfx ledger create-canister or dfx ledger top-up successfully sent a message to the ledger, and a transaction was recorded at some block height, but for some reason the subsequent notify failed. +
+Basic usage +dfx ledger notify [options] _block-height_ _destination-principal_ +
+
+Flags +You can use the following optional flags with the dfx ledger notify command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Arguments +You can specify the following argument for the dfx ledger notify command. + + + + + + + + + +Argument +Description + + + + +<block-height> +Specifies the block height at which the send transaction was recorded. + + +<destination-principal> +Specifies the principal of the destination, either a canister identifier or the textual representation of a user principal. +If the send transaction was for the create-canister command, specify the controller principal. +If the send transaction was for the top-up command, specify the canister ID. + + + + +
+
+Examples +The following example illustrates sending a notify message to the ledger in response to a _send+ transaction that was recorded at the block height 75948. +dfx ledger --network ic notify 75948 tsqwz-udeik-5migd-ehrev-pvoqv-szx2g-akh5s-fkyqc-zy6q7-snav6-uqe +
+
+
+dfx ledger top-up +Use the dfx ledger top-up command to top up a canister with cycles minted from ICP tokens. +
+Basic usage +dfx ledger --network ic top-up [options] canister [flag] +
+
+Flags +You can use the following optional flags with the dfx ledger top-up command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Arguments +You can specify the following argument for the dfx ledger top-up command. + + + + + + + + + +Argument +Description + + + + +canister +Specifies the canister identifier that you would like to top up. + + + + +
+
+Options +You can specify the following options for the dfx ledger top-up command. + + + + + + + + + +Option +Description + + + + +--amount <amount> +Specifies the number of ICP tokens to mint into cycles and deposit into the destination canister. +You can specify the amount as a number with up to eight (8) decimal places. + + +--e8s <e8s> +Specifies fractional units of an ICP token—called e8s—as a whole number, where one e8 is the smallest unit of an ICP token. For example, 1.05000000 is 1 ICP and 5000000 e8s. You can use this option on its own or in conjunction with the --icp option. + + +--fee <fee> +Specifies the transaction fee for the operation. The default is 10000 e8s. + + +--icp <icp> +Specifies ICP tokens as a whole number. You can use this option on its own or in conjunction with --e8s. + + +--max-fee <max-fee> +Specifies a maximum transaction fee. The default is 10000 e8s. + + + + +
+
+Examples +You can use the dfx ledger top-up command to top up the cycles of a specific canister from the balance of ICP tokens you control. +The canister identifier must be associated with a cycles wallet canister that is able to receive cycles. Alternatively, you can modify a non-cycles wallet canister to implement a method to receive cycles using system APIs described in the Internet Computer Interface Specification. +For example, you can run the following command to top-up a cycles wallet canister deployed on the Internet Computer with 1 ICP worth of cycles: +dfx ledger --network ic top-up --icp 1 5a46r-jqaaa-aaaaa-qaadq-cai +This command displays output similar to the following: +Transfer sent at BlockHeight: 59482 +Canister was topped up! +
+
+
+dfx ledger transfer +Use the dfx ledger transfer command to transfer ICP tokens from your account address in the ledger canister to a destination address. +
+Basic usage +dfx ledger transfer [options] to --memo memo +
+
+Flags +You can use the following optional flags with the dfx ledger transfer command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Arguments +You can specify the following argument for the dfx ledger transfer command. + + + + + + + + + +Argument +Description + + + + +<to> +Specify the Account Identifier or address to which you want to transfer ICP tokens. + + + + +
+
+Options +You can specify the following argument for the dfx ledger transfer command. + + + + + + + + + +Option +Description + + + + +--amount <amount> +Specifies the number of ICP tokens to transfer. +Can be specified as a number with up to eight (8) decimal places. + + +--e8s <e8s> +Specifies e8s as a whole number, where one e8 is smallest partition of an ICP token. For example, 1.05000000 is 1 ICP and 5000000 e8s. You can use this option alone or in conjunction with the --icp option. + + +--fee <fee> +Specifies a transaction fee. The default is 10000 e8s. + + +--icp <icp> +Specifies ICP as a whole number. You can use this option alone or in conjunction with --e8s. + + +--memo <memo> +Specifies a numeric memo for this transaction. + + + + +
+
+Examples +You can use the dfx ledger transfer command to send ICP to the Account Identifier of the destination. +For example, you can run the following command to check the account identifier associated with the principal you are currently using: +dfx ledger account-id +This command displays output similar to the following: +30e596fd6c5ff5ad7b7d70bbbda1187c833e646c6251464da7f82bc217bba397 +You can check the balance of this account by running the following command: +dfx ledger --network ic balance +This command displays output similar to the following: +64.89580000 ICP +Use the dfx ledger transfer command to send some of your ICP balance to another known destination using the following command: +dfx ledger --network ic transfer dfx ledger --network ic transfer dd81336dbfef5c5870e84b48405c7b229c07ad999fdcacb85b9b9850bd60766f --memo 12345 --icp 1 +This command displays output similar to the following: +Transfer sent at BlockHeight: 59513 +You can then use the dfx ledger --network ic balance command to check that your account balance reflects the transaction you just made. +
+
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/cli-reference/dfx-new.xml b/modules/developers-guide/pages/cli-reference/dfx-new.xml new file mode 100644 index 000000000..01c78f9bf --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-new.xml @@ -0,0 +1,90 @@ + + + +
+ +dfx new +2021-08-05 + +Use the dfx new command to create a new project for the {platform}. +This command creates a default project structure with template files that you can modify to suit your application. +You must specify the name of the project to you want to create. +You can use the --dry-run option to preview the directories and files to be created without adding them to the file system. +
+Basic usage +dfx new _project_name_ [flag] +
+
+Flags +You can use the following optional flags with the dfx new command: + + + + + + + + + +Flag +Description + + + + +--dry-run +Generates a preview the directories and files to be created for a new project without adding them to the file system. + + +--frontend +Installs the template frontend code for the default project canister. +The default value for the flag is true if node.js is currently installed on your local computer. +If node.js is not currently installed, you can set this flag to true to attempt to install node.js and the template file when creating the project or you can set the flag to false to skip the installation of template frontend code entirely. + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Arguments +You must specify the following argument for the dfx new command. + + + + + + + + + +Argument +Description + + + + +project_name +Specifies the name of the project to create. +This argument is required. + + + + +
+
+Examples +You can use dfx new to create a new project named my_social_network by running the following command: +dfx new my_social_network +The command creates a new project, including a default project directory structure under the new project name and a Git repository for your project. +If you want to preview the directories and files to be created without adding them to the file system, you can run the following command: +dfx new my_social_network --dry-run +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/cli-reference/dfx-parent.xml b/modules/developers-guide/pages/cli-reference/dfx-parent.xml new file mode 100644 index 000000000..5adebe50c --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-parent.xml @@ -0,0 +1,204 @@ + + + +
+ +dfx +2021-08-05 + +The DFINITY command-line execution environment (dfx) is the primary tool for creating, deploying, and managing the applications you develop for the {platform}. +Use the dfx parent command with flags and subcommands to specify the operations you want to perform with or without optional arguments. +
+Basic usage +dfx [option] [subcommand] [flag] +
+
+Flags +You can use the following optional flags with the dfx parent command or with any of the dfx subcommands. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-q`, --quiet +Suppresses informational messages. + + +-v, --verbose +Displays detailed information about operations. + + +-V, --version +Displays version information. + + + + +
+
+Options +You can use the following options with the dfx command. + + + + + + + + + +Option +Description + + + + +--identity <identity> +Specifies the user identity to use when running a command. + + +--logfile <logfile> +Writes log file messages to the specified log file name if you use the --log file logging option. + + +--log <logmode> +Specifies the logging mode to use. ++ +You can set the log mode to one of the following:- stderr to log messages to the standard error facility.- tee to write messages to both standard output and to a specified file name.- file to write messages to a specified file name.The default logging mode is stderr. + + + + +
+
+Subcommands +Use the following subcommands to specify the operation you want to perform or to view usage information for a specific command. +For reference information and examples, select an appropriate subcommand. + + + + + + + + + +Command +Description + + + + +bootstrap +Starts the bootstrap server you want to use to serve front-end assets for your project. + + +build +Builds canister output from the source code in your project. + + +cache +Manages the dfx cache on the local computer. + + +canister +Manages canisters deployed on a network replica. + + +config +Sets or changes configuration options for your current project. + + +deploy +Deploys all or a specific canister from the code in your project. +By default, all canisters are deployed. + + +help +Displays usage information for a specified subcommand. + + +identity +Enables you to create and manage the identities used to communicate with the Internet Computer network. + + +ledger +Enables you to interact with accounts in the ledger canister running on the Internet Computer. + + +new +Creates a new project. + + +ping +Sends a response request to a specified Internet Computer network to determine network connectivity. +If the connection is successful, the Internet Computer replies with its status. + + +replica +Starts a local network replica process. + + +start +Starts the local network replica and a web server for the current project. + + +stop +Stops the local network replica. + + +upgrade +Upgrades the version of dfx installed on the local computer to the latest version available. + + +dfx wallet +Enables you to manage cycles, controllers, custodians, and addresses for the default cycles wallet associated with the currently-selected identity. + + + + +
+
+Examples +You can use the dfx parent command to display usage information or version information. +For example, to display information about the version of dfx you currently have installed, you can run the following command: +dfx --version +To view usage information for a specific subcommand, specify the subcommand and the --help flag. +For example, to see usage information for dfx build, you can run the following command: +dfx build --help +
+Using logging options +You can use the --verbose and --quiet flags to increment or decrement the logging level. +If you don’t specify any logging level, CRITICAL, ERROR, WARNING, and INFO messages are logged by default. +Specifying one verbose flag (-v) increases the log level to include DEBUG messages. +Specifying two verbose flags (-vv)increases the logging level to include both DEBUG and TRACE messages. +Adding a --quiet flag decreases the logging level. +For example, to remove all messages, you can run a command similar the following: +dfx -qqqq build +Keep in mind that using TRACE level logging (--vv) generates a lot of log messages that can affect performance and should only be used when required for troubleshooting or analysis. +To output log messages to a file named newlog.txt and display the messages on your terminal when creating a new project, you can run a command similar to the following: +dfx --log tee --logfile newlog.txt new hello_world +
+
+Specifying a user identity +If you create user identities with the dfx identity new command, you can then use the --identity comment-line option to change the user context when running other dfx commands. +In the most common use case, you use the --identity option to call specific canister functions to test access controls for specific operations. +For example, you might want to test whether the devops user identity can call the modify_profile function for the accounts canister by running the following command: +dfx --identity devops canister call accounts modify_profile '("Kris Smith")' +
+
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/cli-reference/dfx-ping.xml b/modules/developers-guide/pages/cli-reference/dfx-ping.xml new file mode 100644 index 000000000..b6138c06b --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-ping.xml @@ -0,0 +1,80 @@ + + + +
+ +dfx ping +2021-08-05 + +Use the dfx ping command to check connectivity between a local computer and an {IC} network provider. +This command enables you to verify that you can connect to a specific {IC} network and that the remote network services are running. +Note that you can only run this command from within the project directory structure. +For example, if your project name is hello_world, your current working directory must be the hello_world top-level project directory or one of its subdirectories. +
+Basic usage +dfx ping [provider] [flag] +
+
+Flags +You can use the following optional flags with the dfx ping command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Arguments +You can specify the following argument for the dfx ping command. + + + + + + + + + +Argument +Description + + + + +provider +Specifies the network provider URL that you want to use. + + + + +
+
+Examples +You can use the dfx ping command to check whether the {IC} is currently available at a specific network address by running a command similar to the following: +dfx ping https://testgw.dfinity.network +If the {IC} is running on the specified network provider address, the command returns output similar to the following: +{ + "ic_api_version": "0.8" +} +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/cli-reference/dfx-replica.xml b/modules/developers-guide/pages/cli-reference/dfx-replica.xml new file mode 100644 index 000000000..d761d00f3 --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-replica.xml @@ -0,0 +1,76 @@ + + + +
+ +dfx replica +2021-08-05 + +Use the dfx replica command to start a {IC} replica process (without a web server) locally. +This command enables you to deploy canisters locally to simulate network deployment and to test your programs during development. +Note that you can only run this command from within the project directory structure. +For example, if your project name is hello_world, your current working directory must be the hello_world top-level project directory or one of its subdirectories. +
+Basic usage +dfx replica [option] [flag] +
+
+Flags +You can use the following optional flags with the dfx replica command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Options +You can use the following option with the dfx replica command. + + + + + + + + + +Option +Description + + + + +--port port +Specifies the port the local replica should listen to. + + + + +
+
+Examples +You can start the {IC} replica by running the following command: +dfx replica +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/cli-reference/dfx-start.xml b/modules/developers-guide/pages/cli-reference/dfx-start.xml new file mode 100644 index 000000000..e4d4ada5b --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-start.xml @@ -0,0 +1,92 @@ + + + +
+ +dfx start +2021-08-05 + +Use the dfx start command to start a local {IC} replica process and web server processes for the current project. +This command enables you to deploy canisters to the local {IC} network to test your programs during development. +Note that you can only run this command from within the project directory structure. +For example, if your project name is hello_world, your current working directory must be the hello_world top-level project directory or one of its subdirectories. +
+Basic usage +dfx start [option] [flag] +
+
+Flags +You can use the following optional flags with the dfx start command. + + + + + + + + + +Flag +Description + + + + +--background +Starts the {IC} replica and web server processes in the background and waits for a reply before returning to the shell. + + +--clean +Starts the {IC} replica and web server processes in a clean state by removing checkpoints from your project cache. +You can use this flag to set your project cache to a new state when troubleshooting or debugging. + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Options +You can use the following option with the dfx start command. + + + + + + + + + +Option +Description + + + + +--host host +Specifies the host interface IP address and port number to bind the frontend to. The default is 127.0.0.1:8000. + + + + +
+
+Examples +You can start the {IC} replica and web server processes in the current shell by running the following command: +dfx start +If you start the {IC} in the current shell, you need to open a new terminal shell to run additional commands. +Alternatively, you can start the {IC} in the background by running the following command: +dfx start --background +If you run the {IC} in the background, however, be sure to stop the network before uninstalling or reinstalling the dfx execution environment by running the following command: +dfx stop +You can view the current process identifier (pid) for the {IC} process started by dfx by running the following command: +more .dfx/pid +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/cli-reference/dfx-stop.xml b/modules/developers-guide/pages/cli-reference/dfx-stop.xml new file mode 100644 index 000000000..03d6a482f --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-stop.xml @@ -0,0 +1,58 @@ + + + +
+ +dfx stop +2021-08-05 + +Use the dfx stop command to stop the {IC} processes that you currently have running on your local computer. +In most cases, you run the {IC} locally so that you can deploy canisters and test your programs during development. +To simulate an external {IC} connection, these processes run continuously either in a terminal shell where you started them or the in the background until you stop or kill them. +Note that you can only run this command from within the project directory structure. +For example, if your project name is hello_world, your current working directory must be the hello_world top-level project directory or one of its subdirectories. +
+Basic usage +dfx stop [flag] +
+
+Flags +You can use the following optional flags with the dfx stop command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Examples +You can stop the {IC} network processes that are running in the background by changing to a project directory then running the following command: +dfx stop +If the local {IC} network is running in a current shell rather than in the background, open a new terminal shell, change to a project directory, then run the dfx stop command. +The current process identifier (pid) for the {IC} process started by dfx is recorded in the .dfx/pid file. +You can view the process identifier before running the dfx stop command by running the following command: +more .dfx/pid +This command displays a process identifier similar to the following: +1896 +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/cli-reference/dfx-upgrade.xml b/modules/developers-guide/pages/cli-reference/dfx-upgrade.xml new file mode 100644 index 000000000..432c3af61 --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-upgrade.xml @@ -0,0 +1,81 @@ + + + +
+ +dfx upgrade +2021-08-05 + +Use the dfx upgrade command to upgrade the {sdk-short-name} components running on your local computer. +This command checks the version of the {sdk-short-name} that you have currently installed against the latest publicly-available version specified in the manifest.json file. +If an older version of the {sdk-short-name} is detected locally, the dfx upgrade command automatically fetches the latest version from the CDN. +
+Basic usage +dfx upgrade [flag] [option] +
+
+Flags +You can use the following optional flags with the dfx upgrade command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Options +You can use the following option with the dfx upgrade command. + + + + + + + + + +Option +Description + + + + +--current-version <version> +Specifies the version you want to identify as the current version. +This option enables you to override the version of the software currently identified as the latest version with the version you pass on the command-line. + + + + +
+
+Examples +You can upgrade the version of the {sdk-short-name} that you have currently installed by running the following command: +dfx upgrade +This command checks the version of dfx you have currently installed and the latest version available published on the {sdk-short-name} website in a manifest file. +If a newer version of dfx is available, the command automatically downloads and installs the latest version. +Current version: 0.6.8 +Fetching manifest \https://sdk.dfinity.org/manifest.json +Already up to date +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/cli-reference/dfx-wallet.xml b/modules/developers-guide/pages/cli-reference/dfx-wallet.xml new file mode 100644 index 000000000..959dc7d2b --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-wallet.xml @@ -0,0 +1,855 @@ + + + +
+ +dfx wallet +2021-08-05 + +Use the dfx wallet command with subcommands and flags to manage the cycles wallets of your identities and to send cycles to the wallets of other account cycles wallet canisters. +The basic syntax for running the dfx wallet commands is: +dfx wallet [option] <subcommand> [flag] +Depending on the dfx wallet subcommand you specify, additional arguments, options, and flags might apply or be required. +To view usage information for a specific dfx wallet subcommand, specify the subcommand and the --help flag. +For example, to see usage information for dfx wallet send, you can run the following command: +dfx wallet send --help +For reference information and examples that illustrate using dfx wallet commands, select an appropriate command. + + + + + + + + + +Command +Description + + + + +add-controller +Add a controller using the selected identity’s principal. + + +addresses +Displays the address book of the cycles wallet. + + +authorize +Authorize a custodian by principal for the selected identity’s cycles wallet + + +balance +Displays the cycles wallet balance of the selected identity. + + +controllers +Displays a list of the selected identity’s cycles wallet controllers. + + +custodians +Displays a list of the selected identity’s cycles wallet custodians. + + +deauthorize +Deauthorize a cycles wallet custodian using the custodian’s principal. + + +help +Displays a usage message and the help of the given subcommand(s). + + +name +Returns the name of the cycles wallet if you’ve used the dfx wallet set-name command. + + +remove-controller +Removes a specified controller from the selected identity’s cycles wallet. + + +send +Sends a specified amount of cycles from the selected identity’s cycles wallet to another cycles wallet using the destination wallet canister ID. + + +set-name +Specify a name for your cycles wallet. + + +upgrade +Upgrade the cycles wallet’s Wasm module to the current Wasm bundled with DFX. + + + + +
+Using your wallet +After you have used the dfx identity deploy-wallet command to create a cycles wallet canister tied to an identity, you can use dfx wallet commands to modify your cycles wallet settings, send cycles to other cycles wallets, and add or remove controllers and custodians. +
+
+dfx wallet add-controller +Use the dfx wallet add-controller to add a controller to the wallet. An identity assigned the role of Controller has the most priviledges and can perform the flowing actions on the selected identity’s cycles wallet: + + +Rename the cycles wallet. + + +Add entries to the address book. + + +Add and remove controllers. + + +Authorize and deauthorize custodians. + + +A controller is also a custodian and can perform the following actions associated with that role: + + +Access wallet information. + + +Send cycles. + + +Forward calls. + + +Create canisters. + + +
+Basic usage +dfx wallet add-controller [option] [flag] +
+
+Flags +You can use the following optional flags with the dfx wallet add-controller command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Options +You can use the following options with the dfx canister call command. + + + + + + + + + +Option +Description + + + + +--network <network> +Specifies the network of the controller you want to add. + + + + +
+
+Arguments +You can specify the following arguments for the dfx wallet add-controller command. + + + + + + + + + +Argument +Description + + + + +controller +Specifies the principal of the controller to add to the wallet. + + + + +
+
+Examples +You can use the dfx wallet add-controller command to add a controller to your wallet. If the controller you want to add is on a different network on the {IC}, specify the network using the --network option. For example: +dfx wallet --network=https://192.168.74.4 add-controller hpff-grjfd-tg7cj-hfeuj-olrjd-vbego-lpcax-ou5ld-oh7kr-kl9kt-yae +
+
+
+dfx wallet addresses +Use the dfx wallet addresses command to display the wallet’s address book.The address entries contain the principal and role (Contact, Custodian, or Controller), and might contain a name, and kind (Unknown, User, or Canister) associated with the address. +
+Basic usage +dfx wallet addresses +
+
+Flags +You can use the following optional flags with the dfx wallet add-controller command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Examples +You can use the dfx wallet addresses command to retrieve information on the addresses in your wallet’s address book. For example: +dfx wallet addresses +Id: hpff-grjfd-tg7cj-hfeuj-olrjd-vbego-lpcax-ou5ld-oh7kr-kl9kt-yae, Kind: Unknown, Role: Controller, Name: ic_admin. +Id: e7ptl-4x43t-zxcvh-n6s6c-k2dre-doy7l-bbo6h-ok8ik-msiz3-eoxhl-6qe, Kind: Unknown, Role: Custodian, Name: alice_auth. +
+
+
+dfx wallet authorize +Use the dfx wallet authorize command to authorize a custodian for the wallet. An identity assigned the role of custodian can perform the following actions on the cycles wallet: + + +Access wallet information. + + +Send cycles. + + +Forward calls. + + +Create canisters. + + +
+Basic usage +dfx wallet authorize <custodian> [flag] +
+
+Flags +You can use the following optional flags with the dfx wallet authorize command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Arguments +Use the following necessary argument with the dfx wallet authorize command. + + + + + + + + + +Argument +Description + + + + +<custodian> +Specify the principal of the identity you would like to add as a custodian to the selected identity’s cycles wallet. + + + + +
+
+Example +For example, to add alice_auth as a custodian, specify her principal in the following command: +dfx wallet authorize dheus-mqf6t-xafkj-d3tuo-gh4ng-7t2kn-7ikxy-vvwad-dfpgu-em25m-2ae +
+
+
+dfx wallet balance +Use the dfx wallet balance command to display the balance of the cycles wallet of the selected identity. +
+Basic usage +dfx wallet balance +
+
+Flags +You can use the following optional flags with the dfx wallet balance command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Examples +Check the balance of the selected identity’s cycles wallet. +dfx wallet balance +This command displays the number of cycles in your cycles wallet. For example: +89000000000000 cycles. +
+
+
+dfx wallet controllers +Use the dfx wallet controllers command to list the principals of the identities that are controllers of the selected identity’s cycles wallet. +
+Basic usage +dfx wallet controllers +
+
+Flags +You can use the following optional flags with the dfx wallet controllers command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Examples +List the controllers of your selected identity’s cycles wallet. +dfx wallet controllers +The information returned should look similar to the following if there are two controllers: +dheus-mqf6t-xafkj-d3tuo-gh4ng-7t2kn-7ikxy-vvwad-dfpgu-em25m-2ae +hpnmi-qgxsv-tgecj-hmjyn-gmfft-vbego-lpcax-ou4ld-oh7kr-l3nu2-yae +
+
+
+dfx wallet custodians +Use the dfx wallet custodians command to list the principals of the identities that are custodians of the selected identity’s cycles wallet. Identities that are added as controllers are also listed as custodians. +
+Basic usage +dfx wallet custodians +
+
+Flags +You can use the following optional flags with the dfx wallet custodians command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Examples +List the custodians of your selected identity’s cycles wallet. +dfx wallet custodians +The information returned should look similar to the following if there are two custodians: +dheus-mqf6t-xafkj-d3tuo-gh4ng-7t2kn-7ikxy-vvwad-dfpgu-em25m-2ae +hpnmi-qgxsv-tgecj-hmjyn-gmfft-vbego-lpcax-ou4ld-oh7kr-l3nu2-yae +
+
+
+dfx wallet deauthorize +Use the dfx wallet deauthorize command to remove a custodian from the cycles wallet. + +that this will also remove the role of controller if the custodian is also a controller. + +
+Basic usage +dfx wallet deauthorize <custodian> [flag] +
+
+Flags +You can use the following optional flags with the dfx wallet deauthorize command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Arguments +Use the following necessary argument with the dfx wallet deauthorize command. + + + + + + + + + +Argument +Description + + + + +<custodian> +Specify the principal of the custodian you want to remove. + + + + +
+
+Example +For example, to remove "alice_auth" as a custodian, specify her principal in the following command: +dfx wallet deauthorize dheus-mqf6t-xafkj-d3tuo-gh4ng-7t2kn-7ikxy-vvwad-dfpgu-em25m-2ae +
+
+
+dfx wallet name +Use the dfx wallet name command to display the name of the selected identity’s cycles wallet if it has ben set using the dfx wallet set-name command. +
+Basic usage +dfx wallet name [flag] +
+
+Flags +You can use the following optional flags with the dfx wallet name command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Example +If you have named your cycles wallet "Terrances_wallet", then the command would return the following: +Terrances_wallet +
+
+
+dfx wallet remove-controller +Use the dfx wallet remove-controller command to remove a controller of your selected identity’s cycles wallet. +
+Basic usage +dfx wallet remove-controller <controller> [flag] +
+
+Flags +You can use the following optional flags with the dfx wallet remove-controller command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Arguments +Use the following necessary argument with the dfx wallet remove-controller command. + + + + + + + + + +Argument +Description + + + + +<controller> +Specify the principal of the controller you want to remove. + + + + +
+
+Example +For example, to remove alice_auth as a controller, specify her principal in the following command: +dfx wallet remove-controller dheus-mqf6t-xafkj-d3tuo-gh4ng-7t2kn-7ikxy-vvwad-dfpgu-em25m-2ae +
+
+
+dfx wallet send +Use the dfx wallet send command to send cycles from the selected identity’s cycles wallet to another cycles wallet using the destination cycle wallet’s Canister ID. +
+Basic usage +dfx wallet [network] send [flag] <destination> <amount> +
+
+Flags +You can use the following optional flags with the dfx wallet send command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Options +You can use the following option with the dfx wallet send command. + + + + + + + + + +Option +Description + + + + +--network +Override the compute network to connect to. By default, the local network is used. A valid URL (starting with http: or https:) can be specified here, and a special ephemeral network will be created specifically for this request. E.g. "http://localhost:12345/" is a valid network name. + + + + +
+
+Arguments +You must specify the following arguments for the dfx wallet send command. + + + + + + + + + +Argument +Description + + + + +<destination> +Specify the destination cycle wallet using its Canister ID. + + +<amount> +Specify the number of cycles to send. + + + + +
+
+Examples +Send cycles from the selected identity’s cycles wallet to another cycles wallet. +For example, to send 2,000,000,000 cycles from the cycles wallet of the selected identity, <ic_admin>, to the cycles wallet of the destination identity, <buffy_standard> with a wallet address r7inp-6aaaa-aaaaa-aaabq-cai, run the following command: +dfx wallet send r7inp-6aaaa-aaaaa-aaabq-cai 2000000000 +
+
+
+dfx wallet set-name +Use the dfx wallet set-name command to assign a name to the selected identity’s cycles wallet. +
+Basic usage + dfx wallet set-name [flag] <name> +
+
+Arguments +You must specify the following arguments for the dfx wallet set-name command. + + + + + + + + + +Argument +Description + + + + +<name> +Specify a name for the cycles wallet. + + + + +
+
+Flags +You can use the following optional flags with the dfx wallet set-name command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Example +If you want to set the name of the current identity’s cycles wallet to "Terrances_wallet" you can run the following command: +dfx wallet set-name Terrances_wallet +
+
+
+dfx wallet upgrade +Use the dfx wallet upgrade command to upgrade the cycle wallet’s Wasm module to the current Wasm bundled with DFX. +
+Basic usage + dfx wallet upgrade [flag] +
+
+Flags +You can use the following optional flags with the dfx wallet upgrade command. + + + + + + + + + +Flag +Description + + + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Example +To upgrade the Wasm module to the latest version, run the following command: +dfx wallet upgrade +
+
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/computation-and-storage-costs.xml b/modules/developers-guide/pages/computation-and-storage-costs.xml new file mode 100644 index 000000000..9d0a5ba28 --- /dev/null +++ b/modules/developers-guide/pages/computation-and-storage-costs.xml @@ -0,0 +1,159 @@ + + + +
+ +Computation and Storage Costs +2021-08-05 + +The Internet Computer requires computation operations and storage to be supported by cycles. Cycles are generated from the conversion of Internet Computer (ICP) utility tokens. +
+The Role of the Network Nervous System (NNS) in Defining Costs +The Internet Computer is a decentralized public utility, controlled by the NNS –– the network’s open, algorithmic governance system. The NNS fundamentally controls how many cycles are required for low-level computation actions for computation and storage. The number of cycles needed for individual computations will vary based on a number of factors considered by the NNS, including proposals from the community. +
+
+Details: Cost of Compute and Storage Transactions on the Internet Computer +See below for details on the cost of compute and storage transactions on the Internet Computer as of July 26, 2021. + +Cycles Cost per Transaction (as of July 26, 2021) + + + + + + +Transaction +Description +All Application Subnets + + + + +Canister Created +For creating canisters on a subnet +100,000,000,000 + + +Compute Percent Allocated Per Second +For each percent of the reserved compute allocation (a scarce resource). +100,000 + + +Update Message Execution +For every update message executed +590,000 + + +Ten Update Instructions Execution +For every 10 instructions executed when executing update type messages +4 + + +Xnet Call +For every inter-canister call performed (includes the cost for sending the request and receiving the response) +260,000 + + +Xnet Byte Transmission +For every byte sent in an inter-canister call (for bytes sent in the request and response) +1,000 + + +Ingress Message Reception +For every ingress message received +1,200,000 + + +Ingress Byte Reception +For every byte received in an ingress message +2,000 + + +GB Storage Per Second +For storing a GB of data per second +127,000 + + + +
+The $USD cost for transactions below is based on the above cycle costs. 1 XDR is equal to 1 Trillion cycles. As of July 26, 2021, the exchange rate for 1 XDR = $1.42. The exchange rate for USD <> XDR may vary and it will impact the conversion rate. For XDR exchange rates please visit: https://www.imf.org/external/np/fin/data/rms_sdrv.aspx +To derive the estimated GB Storage per month, we assume a 30 day month. + +Cost per Transaction in $USD (as of July 26, 2021) + + + + + + +Transaction +Description +All Application Subnets + + + + +Canister Created +For creating canisters on a subnet +$0.142 + + +Compute Percent Allocated Per Second +For each percent of the reserved compute allocation (a scarce resource). +$0.000000142 + + +Update Message Execution +For every update message executed +$0.0000008378 + + +Ten Update Instructions Execution +For every 10 instructions executed when executing update type messages +$0.00000000000568 + + +Xnet Call +For every inter-canister call performed (includes the cost for sending the request and receiving the response) +$0.0000003692 + + +Xnet Byte Transmission +For every byte sent in an inter-canister call (for bytes sent in the request and response) +$0.00000000142 + + +Ingress Message Reception +For every ingress message received +$0.000001704 + + +Ingress Byte Reception +For every byte received in an ingress message +$0.00000000284 + + +GB Storage Per Second +For storing a GB of data per second +$0.00000018034 + + + +
+Assuming a 30 day month —  + + + + + + + +GB Storage Per Month +For storing a GB of data per month +$0.467 + + + + +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/concepts/canisters-code.xml b/modules/developers-guide/pages/concepts/canisters-code.xml new file mode 100644 index 000000000..03ab6bdab --- /dev/null +++ b/modules/developers-guide/pages/concepts/canisters-code.xml @@ -0,0 +1,182 @@ + + + +
+ +Canisters and code +2021-08-05 + +One of the most important principles to keep in mind is that the Internet Computer is primarily a distributed and decentralized platform for running software. +When you write source code for an application that runs on the Internet Computer, you compile the source code into a WebAssembly module. +When you deploy the WebAssembly module that contains your program on an Internet Computer replica, the program is executed inside of a conceptual computational unit called a software canister. +Once deployed, end-users can interact with the software canister by accessing the entry point functions you have defined for that canister through a front-end client such as a browser. +
+Canisters include both program and state +A software canister is similar to a container in that both are deployed as a software unit that contains compiled code and dependencies for an application or service. +Containerization allows for applications to be decoupled from the environment, allowing for easy and reliable deployment. +The canister differs from a container, however, in that it also stores information about the current software state with a record of preceding events and user interactions. +While a containerized application might include information about the state of the environment in which the application runs, a software canister is able to persist a record of state changes that resulted from an application’s functions being used. +
+
+Query and update methods +This concept of a canister consisting of both program and state is an important one because when a canister function is invoked by sending a message to one of its entry points, there are only two types of calls: non-committing query calls and committing update calls. + + + + + + + + + +Type +Key points to remember + + + + +Query calls +Allow the user to query the current state of a canister or call a function that operates on the canister’s state without changing it. + + +Are synchronous and answered immediately. + + +Can be made to any node that holds the canister and do not require consensus to verify the result. +There is an inherent tradeoff between security and performance because the reply from a single node might be untrustworthy or inaccurate. + + +Do not allow changes to the state of the canister to be persisted. Essentially, programs use query calls to perform read-only operations. + + +Do not allow the called canister to invoke functions exposed by other canisters as inter-canister calls. (Note that this restriction is temporary and that canisters will be able to invoke functions exposed by other canisters when processing query calls in the future.) + + + + +Update calls +Allow the user to change the state of the canister and have changes persisted. + + +Are answered asynchronously. + + +Must pass through consensus to return the result. +Because consensus is required, changing the state of a canister can take time. Therefore, update calls use the actor-based programming model (with state isolation) to allow concurrent and asynchronous processing. +There is an inherent tradeoff between security and performance because two-thirds of the replicas in a subnet must agree on the result. + + +The called canister can invoke functions exposed by other canisters + + + + + + +As a developer, it is important to recognize this relationship between the calls that query the canister and the calls that change the canister state. +In particular, you should keep in mind the inherent tradeoff between security and performance. +
+
+How to develop applications for the Internet Computer +For programmers and software developers, the {platform} provides unique capabilities and opportunities within a framework that simplifies how you can design, build, and deploy applications. +A key part of this framework is a new, general purpose programming language, Motoko. +Motoko is a programming language that has been specifically designed to take full advantage of the unique features that the Internet Computer provides, including: + + +The ability to define programs directly using actor objects and classes. + + +The use of async and await syntax to enable programming asynchronous messaging as if it was synchronous processing. + + +Automatic support for message serialization and deserialization. + + +The ability to leverage orthogonal persistence using data structures without external databases or storage volumes. + + +As a modern, high-level programming language, Motoko provides some key features of its own, including: + + +Support for big integer operations and overflow protection. + + +A sound type system that statically checks each program to ensure it can execute without type errors on all possible inputs. + + +Support for function abstractions, user-defined type definitions, and user-defined actors. + + +For more detailed information about the Motoko programming language itself, including syntactical conventions and supported features, see the Motoko Programming Language Guide. +The following diagram provides a simplified drill-down view of the development environment as part of the Internet Computer ecosystem. + + + + +Your development environment as part of the Internet Computer ecosystem + +
+
+Canisters, actors, and the code you produce +One of the most important principles to keep in mind when preparing to write programs using the Motoko programming language is that Motoko uses an actor-based programming model. +An actor is a special kind of object that processes messages in an isolated state, enabling messages to be handled remotely and asynchronously. +Many key features of the {platform} depend on this type of secure and efficient asynchronous message handling. +In general, each software canister includes the compiled code for one actor object. +Each canister also includes some additional information such as interface descriptions or front-end assets. +You can create projects that include multiple canisters, but each canister can only include one actor. +
+
+Why your code is compiled into WebAssembly +When you compile Motoko code, the result is a WebAssembly module. +WebAssembly is a low-level computer instruction format that is portable and abstracts program execution cleanly over most modern computer hardware. +It is broadly supported for programs that run on the internet and a natural fit for deploying applications that are intended to run on the {platform}. +With Motoko, developers can compile to portable WebAssembly while still delivering secure applications using a simple and high-level language. +The Motoko language offers many of the features that are common to other higher-level modern languages—like type safety and pattern-matching. +In addition, Motoko provides built-in support for defining messaging services using actors in a way that is especially well-suited to the {platform} and is easy to learn whether you are a new or experienced programmer. +This guide provides an introduction to the basic features of the Motoko programming language in the context of writing programs using the SDK. +For more detailed information about the Motoko programming language itself, see the Motoko Programming Language Guide. +
+
+Identities and authentication +One of the main differences between a user-initiated canister operation and a canister-to-canister operation is that canisters have an explicitly registered identity on the [IC]. +There is no central registry for user principals. +Instead, user identifiers are associated specifically with the canisters each user accesses through one or more public-private key pairs. +The user’s private key is used to sign messages, which are sent along with their public key to a canister. +The [IC] authenticates the user and passes the principal to the canister for the authorization of their operation. +At a high level, first-time users generate an unsigned key pair and derive their principal identifier from the public key during their first interaction with the Internet Computer. +Returning users are authenticated using the private key (or keys) that have been stored securely by the user agent. +Users with access to multiple canisters can manage the keys and devices used for authentication associated with each canister. +A single user can have multiple public-private key pairs for accessing canisters from different devices—such as browsers running on different computers, mobile phones, or tablets—but these derived keys all map to a primary identifier. +
+
+Resource consumption and cycles +In general, all canisters consume resources in the form of CPU cycles for execution, bandwidth for routing messages, and memory for persisted data. +Canisters maintain an account balance of cycles to pay for the cost of communication, computation, and storage that their applications consume. +Cycles are intended to reflect the real cost of operations including physical hardware, rack space, energy, storage devices, and bandwidth in a stable or deflationary way so that the cost of program execution remains the same or decreases with operational efficiency. + + +Programs must be able to pay for complete execution (all or nothing), but the cost associated with a unit of cycles will make efficient programs cost-effective. + + +By setting limits on how many cycles a canister can consume, the platform can prevent malicious code from draining resources. + + +The relative stability of operational costs makes it easier to predict the cycles required to process, for example, a million messages. +The cycles available for program execution are held in a wallet canister. For local deployment, wallet canisters are automatically created and issued cycles. To deploy your application on the Internet Computer running on external nodes and subnets, however, you’ll need a principal with a cycles wallet to manage canister operations. +
+
+Want to learn more? +If you are looking for more information about canisters, check out the following related resources: + + +Introducing Canisters — An Evolution of Smart Contracts (video) + + +What is the DFINITY Canister SDK? (video) + + +Deploying your first application (video) + + +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/concepts/concepts-intro.xml b/modules/developers-guide/pages/concepts/concepts-intro.xml new file mode 100644 index 000000000..4b55e1dbb --- /dev/null +++ b/modules/developers-guide/pages/concepts/concepts-intro.xml @@ -0,0 +1,29 @@ + + + +
+ +Concepts +2021-08-05 + +You don’t need to know much about the inner workings of the {platform} to write programs that run successfully on it. +However, learning a few key concepts will help you get the most out of the unique features that the Internet Computer provides. +Knowing a little about the design and architecture of the {platform} can make it easier for you to realize the benefits that align with your goals and inform the types of applications you develop. +The topics in this section introduce key components and terminology to help you understand the architecture and operation of the Internet Computer. +If you want to get right to developing code, though, you can skip this introductory material—key concepts and terminology—and look them up later when you need them either in this section or in the glossary. +If you are looking for more introductory information, check out the following related resources: + + +Overview of the Internet Computer (video) + + +Building on the Internet Computer: Fundamentals (video) + + +Introducing Canisters — An Evolution of Smart Contracts (video) + + +Frequently Asked Questions (video and short articles) + + +
\ No newline at end of file diff --git a/modules/developers-guide/pages/concepts/data-centers.xml b/modules/developers-guide/pages/concepts/data-centers.xml new file mode 100644 index 000000000..1eb345dbc --- /dev/null +++ b/modules/developers-guide/pages/concepts/data-centers.xml @@ -0,0 +1,58 @@ + + + +
+ +Decentralized data centers +2021-08-05 + +The Internet Computer is not physical hardware that exists in any physical location. +Instead, the Internet Computer combines computing resources provided by independently-operated data centers around the world. +Unlike a public or private cloud, the Internet Computer is not owned and operated by a single private company. +Instead, the Internet Computer is a public utility with updates and operations that are managed through an algorithmic, decentralized governance system defined in the protocol. +Its architecture enables multiple computers to operate like one, very powerful, virtual machine. +The computers that make up the virtual machine are organized into sub-networks of data centers around the globe. +The distributed architecture enables secure communication without firewalls or technologies that are vulnerable to attack. +Independent data centers receive remuneration for contributing computing capacity and hosting services to support applications running on the {platform}. +
+Subnets and data centers +To provide a truly decentralized blockchain that can withstand potential service disruptions, the physical nodes that make up any given subnet are distributed across data centers in diverse locations. +The nodes themselves might be owned or provided by different parties in partnership or unaffiliated with the data center location where they operate. +The following diagram provides a simplified view of a subnet with nodes in four data centers. + + + + +data center simplified + +In this simplified scenario: + + +There are four geographically-independent data centers. + + +Each data center has hardware supplied by multiple node providers. + + +Any single node provider might have equipment in multiple data centers. + + +Although this example represents one subnet with nodes in multiple data centers, any of the nodes could be moved out of this subnet to form a new subnet, if needed. +Changes to the network topology are managed through the Internet Computer governance system called the Network Nervous System (NNS). +
+
+Node providers and data center operators +In most cases, node providers—or the data center operators they partner with—are responsible for monitoring and maintaining the compute capacity of the equipment on which the Internet Computer runs. +For example, node providers or data center operators might need to repair or replace equipment if there’s a hardware failure or if a system under-performs. +Network operations and upgrades, however, are monitored and managed through the decentralized governance system, the Network Nervous System (NNS). +
+
+Want to learn more? +If you are looking for more information about data center operations and node providers, check out the following related resources: + + +Internet Computer Help Center for Node Providers (FAQ and articles) + + +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/concepts/governance.xml b/modules/developers-guide/pages/concepts/governance.xml new file mode 100644 index 000000000..df957381e --- /dev/null +++ b/modules/developers-guide/pages/concepts/governance.xml @@ -0,0 +1,31 @@ + + + +
+ +Neurons and governance +2021-08-05 + +As a decentralized platform, all changes to the configuration and behavior of the Internet Computer are controlled by a governance body called the Network Nervous System (NNS). The NNS controls many aspects of the Internet Computer platform including the following: + + +which data center providers participate in the network + + +the number, location, and ownership of the nodes accepted from a data center provider + + +assignment of nodes to subnets + + +whether upgrades to smart contract canister software or management services are allowed or not + + +In addition, only members of the governance body can vote to approve or deny requests to upgrade Internet Computer replicas or modify the Internet Computer protocol. +
+Voting rights for stakeholders +Because tokens on the Internet Computer are generally liquid, they do not represent a stable enough commitment on the part of their holders for them to be used for governance purposes. To provide the stability required for responsible governance, tokens can be converted to neurons. A neuron represents a number of ICP tokens that cannot be exchanged for a minimum period of time (the lock-up period). +When a person or organization has some number of ICP tokens locked up in a neuron, the neuron holder has the right to vote on governance issues, and to be paid for voting in proportion to the number of ICP locked up and the length of the lock-up period. +The Internet Computer tracks the number of ICP tokens that are locked up in neurons and provides the logic necessary for voting in conjunction with managing ICP token account balances. +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/concepts/nodes-subnets.xml b/modules/developers-guide/pages/concepts/nodes-subnets.xml new file mode 100644 index 000000000..c68964781 --- /dev/null +++ b/modules/developers-guide/pages/concepts/nodes-subnets.xml @@ -0,0 +1,35 @@ + + + +
+ +Nodes and subnet blockchains +2021-08-05 + +Internet Computer subnet blockchains provide physical hardware and resources—like CPU and memory—for performing software operations. Each subnet is a blockchain that consists of some number of individual machines—connected peer computers called nodes—that run the software components of the Internet Computer protocol. +The Internet Computer software components that run on each node are called a replica because they replicate state and computation across all of the nodes in a subnet blockchain. +The core components of a replica are organized into the following logical layers: + + +A peer-to-peer (P2P) networking layer that collects and advertises messages from users, from other nodes in its subnet blockchain, and from other sub-networks. Messages received by the peer-to-peer layer are replicated to all of the nodes in the subnet to ensure the security, reliability, and resiliency of the platform. + + +A consensus layer that selects and sequences messages received from users and from different subnets to create input blocks that can be notarized and finalized before being delivered to the message routing layer. + + +A message routing layer that routes user- and system-generated messages between subnets, manages the input and output queues for applications, and schedules messages for execution. + + +An execution environment that calculates the deterministic computation involved in executing a program and processes the messages it receives from the message routing layer. + + +The following diagram provides a simplified overview of the Internet Computer protocol components deployed as a local replica in a development environment. + + + + +Internet Computer components in a developer’s environment + +As a developer, it isn’t necessary to know the details about how your applications and user interactions with your applications are routed through the Internet Computer architecture or replicated on the network. +However, a general understanding of the key components can be useful because the development environment includes the replica components to provide a local test network for deployment and a realistic sense of the workflow for a production deployment. +
\ No newline at end of file diff --git a/modules/developers-guide/pages/concepts/tokens-cycles.xml b/modules/developers-guide/pages/concepts/tokens-cycles.xml new file mode 100644 index 000000000..f8c5beb6c --- /dev/null +++ b/modules/developers-guide/pages/concepts/tokens-cycles.xml @@ -0,0 +1,104 @@ + + + +
+ +Tokens and cycles +2021-08-05 + +Within the Internet Computer ecosystem, Internet Computer Protocol tokens (ICP tokens) are a native utility token with a value determined on the open market. +ICP tokens play a key role in both the governance and economics of the Internet Computer. +
+How you can get ICP tokens +As a utility token for the Internet Computer, there are a few different ways you might acquire ICP tokens. +For example, you might: + + +Purchase ICP tokens directly through an exchange that lists ICP tokens available for trade. + + +Claim tokens as a result of your investment. + + +Receive a grant of tokens through the Internet Computer Association (ICA) or the DFINITY Foundation. + + +Receive tokens as remuneration for providing computing capacity as a node provider or data center. + + +
+
+How you can use ICP tokens +If you have ICP tokens, but aren’t sure how to use them, the following diagram provides a simplified overview to illustrate the three most common scenarios. + + + + +icp tokens how to use + +As this diagram suggests, how you use ICP tokens depends primarily on your goals in acquiring them. +For example, if you are a developer or entrepreneur, ICP tokens can be converted to cycles. Cycles can then be used to build and deploy applications to deliver products and services to the market. +If you are a member of the community interested in participating in governance and influencing the the direction of the Internet Computer, you can lock up ICP tokens in a stake—called a neuron—so that you can submit and vote on proposals. +
+
+How cycles work +For developers, ICP tokens are important because they can be converted to cycles that, in turn, are used to pay for computation and resource consumption. +As an example, imagine you have a house where propane is used for a water heater, kitchen stove, dryer, and space heater. As you use these appliances, you deplete the supply of gas you have on hand, so periodically you contact a provider to refill your supply so you can continue to use your appliances without interruption. This is similar to smart contract canisters in that each canister must have an account with cycles available to pay for the communication, computation, and storage that the canister’s application consumes. +Internet Computer Protocol token holders can exchange tokens when they need to replenish the cycles available in each canister’s account. +
+
+Cost of computation + + +Cycles reflect the real costs of operations for applications hosted in the Internet Computer platform including resources such physical hardware, rack space, energy, storage devices, and bandwidth. + + +In simple terms, cycles represent the cost of executing each application’s WebAssembly instructions. + + +Programs must be able to pay for complete execution (all or nothing), but the platform sets limits on how many cycles a canister can hold and consume to prevent malicious code from draining resources. + + +The relative stability of operational costs makes it easier to predict the cycles required to process, for example, a million messages. + + +The costs associated with communication, computation, and storage are more likely to decrease than to increase over time—for example, because disk space becomes cheaper or hardware more efficient. + + +Although Internet Computer Protocol tokens can be used to add cycles to canisters, cycles themselves are not currency and have no liquidity or value as an asset. + + +Cycles cannot be converted back to value in the form of Internet Computer Protocol tokens, but they can be transferred between canisters to enable canisters to pay for operations. + + +
+
+Token value and volatility + + +Tokens reflect the value of the Internet Computer and can fluctuate. To prevent the token value from affecting the number of messages a canister can process, tokens are not used to pay for resources directly. + + +Tokens can be exchanged between token holders or locked up in neurons to secure voting rights as part of the platform governance system. + + +Tokens are used to reward data centers for providing compute capacity and platform stakeholders for participating in secure operation of the Internet Computer by voting on proposals submitted to the governance system. + + +
+
+Payment to data centers and node providers +With this model, the Internet Computer platform provides data center providers with a predictable economic model for computing power capacity to ensure resources are available when and where they are needed. Data center providers receive compensation for both active and spare nodes so that the Internet Computer has capacity to handle both normal traffic and workload spikes. +If the Internet Computer network requires additional capacity, it can request bids from potential data center providers. If a bid is accepted, a data center provider might be contracted to provide a given number of servers with an acceptable level of service availability for a specific period of time. For example, a data center provider might be contracted to provide ten servers with 99% uptime for 30 days. Even if those nodes do not host any canisters and are only used as spare nodes, the data center provider receives compensation for availability as part of the network. +The Internet Computer economic model places much of the power and responsibility of managing capacity on the governance system—the Network Nervous System. Specific details about compensation and service level requirements are outside the scope of this document. +
+
+Want to learn more? +If you are looking for more information about tokens and cycles, check out the following related resources: + + +Overview of Token Economics (video) + + +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/concepts/what-is-IC.xml b/modules/developers-guide/pages/concepts/what-is-IC.xml new file mode 100644 index 000000000..8015c9164 --- /dev/null +++ b/modules/developers-guide/pages/concepts/what-is-IC.xml @@ -0,0 +1,58 @@ + + + +
+ +What is the Internet Computer? +2021-08-05 + +The Internet Computer is a blockchain that enables developers, organizations, and entrepreneurs to build and deploy secure, autonomous, and tamper-proof software programs. +As an application developer, you might find it useful to think of the Internet Computer as providing the following key elements: + + +An open communication protocol that enables general-purpose computations to run transparently directly on the internet + + +A network that runs the protocol to provide computing capacity—for example, the hardware, CPU, and memory required to run programs—through independent data centers. + + +A globally-accessible and scalable blockchain platform for running software applications. + + +
+Open blockchain platform +The Internet Computer is not physical hardware that exists in any physical location. +Instead, the Internet Computer combines computing resources provided by independent data centers around the world to give users and organizations secure access to applications and transaction processing services. +The {platform} enables multiple computers to operate like one, very powerful, virtual machine. +The computers that make up the virtual machine are organized into sub-networks—subnet blockchains—with data centers around the world. +The distributed architecture enables secure communication without firewalls or technologies that are vulnerable to attack. +Independent data centers receive remuneration for contributing computing capacity and hosting services to support applications running on the {platform}. +
+
+Building the next generation of software and services +The Internet Computer protocol reduces platform-based risks and paves the way for innovation by re-imagining how software is built, deployed, and accessed. +For example, with the Internet Computer, developers can focus on writing code using smart contracts without environment-related distractions such as: + + +physical or virtual network configuration requirements + + +load balancing services + + +firewalls, network topology, or port management + + +database configuration and maintenance + + +storage volumes and devices + + +By enabling developers to focus on building applications and delivering value, the Internet Computer helps simplify the development process, reduce time to market, and foster innovation. +For end-users, the Internet Computer provides a secure environment for accessing applications with fewer risks. +Because of the inherent security of the blockchain, programs running on the Internet Computer cannot be hijacked by malicious code, which also reduces the total cost of ownership for both application end-users or organizations. +In addition, because software services can be "autonomous" and public, developers can write services that communicate with each other and share functions in ways that increase productivity and efficiency while leaving room to innovate and improve projects with confidence. +The Internet Computer also enables developers to use cryptographically-secure identities to enforce access controls, reducing the need to rely on user names and passwords or external identity management plug-ins. +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/customize-projects.xml b/modules/developers-guide/pages/customize-projects.xml new file mode 100644 index 000000000..d2cb0cabc --- /dev/null +++ b/modules/developers-guide/pages/customize-projects.xml @@ -0,0 +1,55 @@ + + + +
+ +Manage projects +2021-08-05 + +You can modify some key settings for individual projects by modifying each project’s dfx.json configuration file. +You can use the dfx config command to change these settings programmatically or manually edit the dfx.json file directly. +
+How to change your source directory +Before you compile source code for your project using the dfx build command, you might want to check the default location for storing the source code for your program. +By default, the name you use to create a new project is the name used for one data smart contract canister (canister_name) and one assets canister (canister_name_assets), and program source code is expected to be in the src/canister_name directory. Similarly, the default location for front-end source code is in the src/canister_name_assets/src directory and front-end output is located in the dist/canister_name_assets directory. +Depending on your application’s complexity and architecture, however, you might want to modify the default location for the program source code, the front-end source code, or front-end output. +For example, for a simple program, you might want to eliminate one directory level and place the source code in the src directory: + "main": "src/main.mo", +For more complex applications, you might want to use a multi-tiered directory structure: +"canisters": { + "profiles": { + "main": "src/profiles/utils/main.mo" + }, + "events": { + "main": "src/events/calendar/main.mo" + }, + "media": { + "main": "src/events/reports/main.mo" + } +} + +If you modify the default settings for a source code directory, be sure that the settings in the dfx.json configuration file match the directory location on the file system. + +
+
+How to change the main program file name +Before you compile source code for your project using the dfx build command, you should verify the location and file name used for your program’s source code. +For example, if you want to build a smart contract canister for the factorial program and the source code for the program is located in src/math/factorial.mo, you should be sure that you have the correct +path specified for the main setting in the canisters section of the configuration file. +For example: +"main": "src/math/factorial.mo", +Keep in mind that changing the configuration setting for the program file name only affects where the dfx build command looks for the source code to compile. Making changes in the configuration file does not rename any files or directories on the file system. +If you change the path to the main program file or the name of the file itself, be sure to change the name and location within your project directory. +
+
+How to change the location for serving the application front-end +You can change the default host name and port number for serving the application front-end by modifying the local network settings in the dfx.json configuration file. +For example, you can change the IP address for the local network by modifying the bind setting: +"networks": { + "local": { + "bind": "192.168.47.1:8000", + "type": "ephemeral" + } +} +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/default-wallet.xml b/modules/developers-guide/pages/default-wallet.xml new file mode 100644 index 000000000..5d879d335 --- /dev/null +++ b/modules/developers-guide/pages/default-wallet.xml @@ -0,0 +1,386 @@ + + + +
+ +Use the default cycles wallet +2021-08-05 + +As discussed in Tokens and cycles, ICP tokens can be converted into cycles to power canister operations. +Cycles provide a largely stable value proposition and represent the operational cost of communication, computation, and storage that applications consume. +For example, cycles reflect the actual cost of physical hardware, rack space, energy, storage devices, and network bandwidth required by applications running on the Internet Computer. +Unlike ICP tokens, cycles are only associated with canisters and not user or developer principals. +Because only canisters require and consume cycles—to perform operations and to pay for the resources they use—users and developers manage the distribution and ownership of cycles through a special type of canister called a cycles wallet. Because the cycles wallet holds the cycles required to perform operations such as creating new canisters, these operations are executed by default using the canister identifier for the cycles wallet instead of your user principal. +For the purposes of local development, the {sdk-short-name} automatically creates a default cycles wallet for you in every project and most of the operations performed using the cycles wallet happen behind the scenes. +For example, the cycles wallet acts on your behalf to register canister identifiers and deploy canisters on the local network. +In a production environment, however, you often need to explicitly register and transfer cycles to new canisters, specify the principals that can act as custodians, and manage the principals with ownership rights. +You can perform some of these tasks using the default cycles wallet application running in a web browser. +Depending on the specific action you want to take, you can also perform these cycle and canister management tasks by running dfx wallet commands in a terminal or by calling methods in the default cycles wallet canister directly. +You should keep in mind, however, that calls to the cycles wallet canister are executed using the cycles wallet identifier associated with the currently-selected user identity. +Depending on your currently-selected identity and whether the principal associated with that identity has been added as a controller or a custodian for a wallet, you might see different results or be denied access to a specific method. +To check the identity you are currently using, run the following command: +dfx identity whoami +
+Controller and custodian roles +A user principal or canister identifier can be assigned to a controller or custodian role. +A controller is the most privileged role and a principal assigned to the controller role can perform privileged tasks including the following: + + +Add and remove other principals as controllers. + + +Authorize and de-authorize other principals as custodians. + + +Add entries to the cycles wallet address book. + + +Access the cycles wallet balance and all other wallet-related information. + + +Send cycles to other canisters. + + +Receive cycles from other canisters. + + +Act as the "message-caller" principal in calls to other canisters. + + +Create canisters and additional cycles wallets. + + +Rename the cycles wallet. + + +A principal assigned to the custodian role can only perform a subset of cycles wallet management tasks, including the following: + + +Access the cycles wallet balance and all other wallet-related information. + + +Send cycles to other canisters. + + +Receive cycles from other canisters. + + +Act as the "message-caller" principal in calls to other canisters. + + +Create canisters. + + + +Authorizing a principal as a custodian does not automatically grant the principal access to a cycles wallet. The identity assigned to the custodian role must also be assigned a cycles wallet canister identifier. For example, if you authorize the identity alice_custodian as a custodian of a cycles wallet (rwlgt-iiaaa-aaaaa-aaaaa-cai) in a local project, that user would also need to be assigned to use that wallet with the dfx identity set-wallet rwlgt-iiaaa-aaaaa-aaaaa-cai command. + +
+
+Check the cycle balance +If you are doing local development, your cycles wallet is created when you register a new canister identifier using dfx canister create or when you register, build, and deploy a canister with dfx deploy. +If you are deploying on the Internet Computer, you typically create your cycles wallet by converting ICP tokens to cycles, transferring the cycles to a new canister identifier, and updating the canister with the default cycles wallet WebAssembly module (WASM). +After you have a cycles wallet on the local or remote network, you can use the dfx wallet balance command or the wallet_balance method to check the current cycle balance. +
+Check you cycles balance when developing locally +If you are doing local development, you can use the dfx wallet balance command to check the current cycles balance on a project-by-project basis. +To check the cycles balance in a local project: + + +Open a terminal and navigate to the root directory of the project. + + +Start the Internet Computer locally by running the following command: +dfx start --background + + +Display the cycles balance from the cycles wallet associated with the currently-selected identity by running the following command: +dfx wallet balance +The command displays output similar to the following: +78000000000000 cycles. + + +
+
+Check the cycles balance on the Internet Computer +If you have deployed a cycles wallet on the Internet Computer main network, you can use the dfx wallet balance command to check the current cycles balance on the network. +To check the cycles balance on the Internet Computer: + + +Open a terminal and navigate to a directory that contains a dfx.json configuration file. + + +Check your connection to the Internet Computer by running the following command: +dfx ping ic + + +Display the cycle balance from the cycles wallet associated with the currently-selected identity by running the following command: +dfx wallet --network ic balance +The command displays output similar to the following: +67991783875995 cycles. + + +
+
+Call the cycles wallet_balance method +You can also check the cycles balance by calling the wallet_balance method in the cycles wallet canister directly. +For example, if your principal is a controller for the h5aet-waaaa-aaaab-qaamq-cai cycles wallet, you can check the current cycle balance by running the following command: +dfx canister --network ic call h5aet-waaaa-aaaab-qaamq-cai wallet_balance +The command returns the balance using Candid format as a record with an amount field (represented by the hash 3_573_748_184) and a balance of +6,895,656,625,450 cycles like this: +(record { 3_573_748_184 = 6_895_656_625_450 }) +
+
+
+Add a controller +If you are the controller of a cycles wallet, you can add other principals or canister identifiers to the controller role. +Adding a principal to the controller role also automatically adds the principal to the custodian role. +To add a controller to a cycles wallet in a local project: + + +Open a terminal and navigate to the root directory of the project. + + +Start the Internet Computer locally by running the following command: +dfx start --background + + +Display the cycles balance from the cycles wallet associated with the currently-selected identity by running a command similar to the following: +dfx wallet add-controller <controller-principal-identifier> +For example, you would run the following command to add the user represented by the principal identifier b5quc-npdph-l6qp4-kur4u-oxljq-7uddl-vfdo6-x2uo5-6y4a6-4pt6v-7qe as a controller of the local cycles wallet: +dfx wallet add-controller b5quc-npdph-l6qp4-kur4u-oxljq-7uddl-vfdo6-x2uo5-6y4a6-4pt6v-7qe +The command displays output similar to the following: +Added b5quc-npdph-l6qp4-kur4u-oxljq-7uddl-vfdo6-x2uo5-6y4a6-4pt6v-7qe as a controller. + + +
+
+List the current controllers +You can use the dfx wallet controllers command or the get_controllers method to list the principals that have full control over a specified cycles wallet canister. +To list the controllers for a cycles wallet in a local project: + + +Open a terminal and navigate to the root directory of the project. + + +Start the Internet Computer locally by running the following command: +dfx start --background + + +List the principal identifiers that have full control over the cycles wallet in the current project by running the following command: +dfx wallet controllers +The command displays the textual representation of the principals that have control over the cycles wallet with output similar to the following: +tsqwz-udeik-5migd-ehrev-pvoqv-szx2g-akh5s-fkyqc-zy6q7-snav6-uqe +b5quc-npdph-l6qp4-kur4u-oxljq-7uddl-vfdo6-x2uo5-6y4a6-4pt6v-7qe + + +
+
+Remove a controller +You can use the dfx wallet remove-controller command or the remove_controller method to remove a principal as a controller. +To remove a controller for a cycles wallet in a local project: + + +Open a terminal and navigate to the root directory of the project. + + +Start the Internet Computer locally by running the following command: +dfx start --background + + +Specify the principal identifier to remove from the controller role in the current project by running a command similar to the following: +dfx wallet remove-controller b5quc-npdph-l6qp4-kur4u-oxljq-7uddl-vfdo6-x2uo5-6y4a6-4pt6v-7qe +The command output similar to the following: +Removed b5quc-npdph-l6qp4-kur4u-oxljq-7uddl-vfdo6-x2uo5-6y4a6-4pt6v-7qe as a controller. + + +
+
+Authorize a custodian +You can use the dfx wallet authorize command or the authorize method to authorize a principal as a custodian of a cycles wallet. +To authorize a principal as a custodian for the cycles wallet in a local project: + + +Open a terminal and navigate to the root directory of the project. + + +Start the Internet Computer locally by running the following command: +dfx start --background + + +Specify the principal identifier to authorize as a custodian in the current project and for the current identity by running a command similar to the following: +dfx wallet authorize b5quc-npdph-l6qp4-kur4u-oxljq-7uddl-vfdo6-x2uo5-6y4a6-4pt6v-7qe +The command output similar to the following: +Authorized b5quc-npdph-l6qp4-kur4u-oxljq-7uddl-vfdo6-x2uo5-6y4a6-4pt6v-7qe as a custodian. + + +
+
+List current custodians +You can use the dfx wallet custodians command or the get_custodians method to return the list of principals that are currently defined as custodians for the cycles wallet. +To list the custodians for a cycles wallet in a local project: + + +Open a terminal and navigate to the root directory of the project. + + +Start the Internet Computer locally by running the following command: +dfx start --background + + +List the principal identifiers that have the custodian role for the cycles wallet in the current project by running the following command: +dfx wallet custodians +The command displays output similar to the following: +tsqwz-udeik-5migd-ehrev-pvoqv-szx2g-akh5s-fkyqc-zy6q7-snav6-uqe +b5quc-npdph-l6qp4-kur4u-oxljq-7uddl-vfdo6-x2uo5-6y4a6-4pt6v-7qe + + +
+
+Remove authorization for a custodian +You can use the dfx wallet deauthorize command or the deauthorize method to remove a principal as a custodian for a cycles wallet. +De-authorizing a principal that was previously added as a controller also automatically removes the principal from the controller role. +To remove a custodian for a cycles wallet in a local project: + + +Open a terminal and navigate to the root directory of the project. + + +Start the Internet Computer locally by running the following command: +dfx start --background + + +Specify the principal identifier to remove from the custodian role in the current project by running a command similar to the following: +dfx wallet deauthorize b5quc-npdph-l6qp4-kur4u-oxljq-7uddl-vfdo6-x2uo5-6y4a6-4pt6v-7qe +The command output similar to the following: +Deauthorized b5quc-npdph-l6qp4-kur4u-oxljq-7uddl-vfdo6-x2uo5-6y4a6-4pt6v-7qe as a custodian. + + +
+
+Send cycles to a canister +You can use dfx wallet send command of the wallet_send method to send a specific number of cycles to a specific canister. +Keep in mind that the canister you specify must be a cycles wallet or have a wallet_receive method to accept the cycles. +If you have deployed a cycles wallet on the Internet Computer main network, you can use the dfx wallet send command to send cycles between canisters running on the network. +To send cycles to another canister running on the Internet Computer: + + +Open a terminal and navigate to a directory that contains a dfx.json configuration file. + + +Check your connection to the Internet Computer by running the following command: +dfx ping ic + + +Get the canister identifier for the canister that you want to receive the cycles. +For example, run the following command to display the cycles wallet identifier associated with the current user identity on the Internet Computer: +dfx identity --network ic get-wallet +The command displays the cycles wallet canister identifier with output similar to the following: +gastn-uqaaa-aaaae-aaafq-cai + + +Send cycles to the canister identifier by running a command similar to the following: +dfx wallet --network ic send <destination> <amount> +For example: +dfx wallet --network ic send gastn-uqaaa-aaaae-aaafq-cai 10000000000 +If the transfer is successful, the command does not displays any output. + +The maximum number of cycles that can be stored in a cycles wallet is +two to the power of sixty-four (264 or 18,446,744,073,709,551,616 cycles). + + + +Check the cycles wallet balance to see the updated number of cycles available by running the following command: +dfx wallet --network ic balance +For example: +67991699387090 cycles. + + +
+
+List address book entries +You can use the dfx wallet addresses command or the list_addresses method to list the principal identifiers and roles that have been configured for the cycles wallet. +To view address book entries for a cycles wallet running on the Internet Computer: + + +Open a terminal and navigate to a directory that contains a dfx.json configuration file. + + +Check your connection to the Internet Computer by running the following command: +dfx ping ic + + +Get the address book entries for the cycles wallet by running the following command : +dfx wallet --network ic addresses +The command displays the controllers and custodians for the cycles wallet with output similar to the following: +Id: tsqwz-udeik-5migd-ehrev-pvoqv-szx2g-akh5s-fkyqc-zy6q7-snav6-uqe, Kind: Unknown, Role: Controller, Name: No name set. +Id: ejta3-neil3-qek6c-i7rdw-sxreh-lypfe-v6hjg-6so7x-5ugze-3iohr-2qe, Kind: Unknown, Role: Custodian, Name: No name set. +Id: b5quc-npdph-l6qp4-kur4u-oxljq-7uddl-vfdo6-x2uo5-6y4a6-4pt6v-7qe, Kind: Unknown, Role: Controller, Name: No name set. + + +
+
+Additional methods in the default cycles wallet +The default cycles wallet canister includes additonal methods that are not exposed as dfx wallet commands. +The additional methods support more advanced cycles management tasks such as creating new canisters and managing events. +
+Create a new cycles wallet +Use the wallet_create_wallet method to create a new cycles wallet canister with an initial cycle balance and, optionally, with a specific principal as its controller. +If you don’t specify a controlling principal, the cycles wallet you use to create the new wallet will be the new wallet’s controller. +For example, you can run a command similar to the following to create a new wallet and assign a principal as a controller: +dfx canister --network call f3yw6-7qaaa-aaaab-qaabq-cai wallet_create_wallet '(record { cycles = 5000000000000 : nat64; controller = principal "vpqee-nujda-46rtu-4noo7-qnxmb-zqs7g-5gvqf-4gy7t-vuprx-u2urx-gqe"})' +The command returns the principal for the new wallet: +(record { 1_313_628_723 = principal "dcxxq-jqaaa-aaaab-qaavq-cai" }) +
+
+Register a new canister identifier +Use the wallet_create_canister method to register a new canister identifier on the Internet Computer. +This method creates a new "empty" canister placeholder with an initial cycle balance and, optionally, with a specific principal as its controller. +After you have registered the canister identifier, you can install code for your application as a separate step. +For example, you can run a command similar to the following to create a new wallet and assign a principal as a controller: +dfx canister --network call f3yw6-7qaaa-aaaab-qaabq-cai wallet_create_canister '(record { cycles = 5000000000000 : nat64; controller = principal "vpqee-nujda-46rtu-4noo7-qnxmb-zqs7g-5gvqf-4gy7t-vuprx-u2urx-gqe"})' +The command returns the principal for the new canister you created: +(record { 1_313_628_723 = principal "dxqg5-iyaaa-aaaab-qaawa-cai" }) +
+
+Receive cycles from a canister +Use the wallet_receive method as an endpoint to receive cycles. +
+
+Forward calls from a wallet +Use the wallet_call method to forward calls using the cycles wallet identifier. +
+
+Manage addresses +Use the following methods to manage address book entries: + + +add_address: (address: AddressEntry) → (); + + +remove_address: (address: principal) → (); + + +
+
+Manage events +Use the following methods to retrieve event and chart information. + + +get_events: (opt record { from: opt nat32; to: opt nat32; }) → (vec Event) query; + + +get_chart: (opt record { count: opt nat32; precision: opt nat64; } ) → (vec record { nat64; nat64; }) query; + + +For example, you can use the get_events method to return canister_create and other events by running a command similar to the following: +dfx canister call <cycles-wallet-identifier> get_events '(record {from = null; to = null})' +If the cycles wallet (gastn-uqaaa-aaaae-aaafq-cai) is deployed on the Internet Computer main network, you could run a command that looks like this to return events: +dfx canister --network ic call gastn-uqaaa-aaaae-aaafq-cai get_events '(record {from = null; to = null})' +The output from the command is in Candid format similar to the following: +( + vec { record { 23_515 = 0; 1_191_829_844 = variant { 4_271_600_268 = record { 23_515 = principal "tsqwz-udeik-5migd-ehrev-pvoqv-szx2g-akh5s-fkyqc-zy6q7-snav6-uqe"; 1_224_700_491 = null; 1_269_754_742 = variant { 4_218_395_836 };} }; 2_781_795_542 = 1_621_456_688_636_513_683;}; record { 23_515 = 1; 1_191_829_844 = variant { 4_271_600_268 = record { 23_515 = principal "ejta3-neil3-qek6c-i7rdw-sxreh-lypfe-v6hjg-6so7x-5ugze-3iohr-2qe"; 1_224_700_491 = null; 1_269_754_742 = variant { 2_494_206_670 };} }; 2_781_795_542 = 1_621_461_468_638_569_551;}; record { 23_515 = 2; 1_191_829_844 = variant { 1_205_528_161 = record { 2_190_693_645 = 11_000_000_000_000; 2_631_180_839 = principal "gvvca-vyaaa-aaaae-aaaga-cai";} }; 2_781_795_542 = 1_621_462_573_993_647_258;}; record { 23_515 = 3; 1_191_829_844 = variant { 1_205_528_161 = record { 2_190_693_645 = 11_000_000_000_000; 2_631_180_839 = principal "gsueu-yaaaa-aaaae-aaagq-cai";} }; 2_781_795_542 = 1_621_462_579_193_578_440;}; record { 23_515 = 4; 1_191_829_844 = variant { 1_955_698_212 = record { 2_190_693_645 = 0; 2_374_371_241 = "install_code"; 2_631_180_839 = principal "aaaaa-aa";} }; 2_781_795_542 = 1_621_462_593_047_590_026;}; record { 23_515 = 5; 1_191_829_844 = variant { 1_955_698_212 = record { 2_190_693_645 = 0; 2_374_371_241 = "install_code"; 2_631_180_839 = principal "aaaaa-aa";} }; 2_781_795_542 = 1_621_462_605_779_157_885;}; record { 23_515 = 6; 1_191_829_844 = variant { 1_955_698_212 = record { 2_190_693_645 = 0; 2_374_371_241 = "authorize"; 2_631_180_839 = principal "gsueu-yaaaa-aaaae-aaagq-cai";} }; 2_781_795_542 = 1_621_462_609_036_146_536;}; record { 23_515 = 7; 1_191_829_844 = variant { 1_955_698_212 = record { 2_190_693_645 = 0; 2_374_371_241 = "greet"; 2_631_180_839 = principal "gvvca-vyaaa-aaaae-aaaga-cai";} }; 2_781_795_542 = 1_621_463_144_066_333_270;}; record { 23_515 = 8; 1_191_829_844 = variant { 4_271_600_268 = record { 23_515 = principal "ejta3-neil3-qek6c-i7rdw-sxreh-lypfe-v6hjg-6so7x-5ugze-3iohr-2qe"; 1_224_700_491 = null; 1_269_754_742 = variant { 2_494_206_670 };} }; 2_781_795_542 = 1_621_463_212_828_477_570;}; record { 23_515 = 9; 1_191_829_844 = variant { 1_955_698_212 = record { 2_190_693_645 = 0; 2_374_371_241 = "wallet_balance"; 2_631_180_839 = principal "gastn-uqaaa-aaaae-aaafq-cai";} }; 2_781_795_542 = 1_621_878_637_071_884_946;}; record { 23_515 = 10; 1_191_829_844 = variant { 4_271_600_268 = record { 23_515 = principal "b5quc-npdph-l6qp4-kur4u-oxljq-7uddl-vfdo6-x2uo5-6y4a6-4pt6v-7qe"; 1_224_700_491 = null; 1_269_754_742 = variant { 4_218_395_836 };} }; 2_781_795_542 = 1_621_879_473_916_547_313;}; record { 23_515 = 11; 1_191_829_844 = variant { 313_999_214 = record { 1_136_829_802 = principal "gastn-uqaaa-aaaae-aaafq-cai"; 3_573_748_184 = 10_000_000_000;} }; 2_781_795_542 = 1_621_977_470_023_492_664;}; record { 23_515 = 12; 1_191_829_844 = variant { 2_171_739_429 = record { 25_979 = principal "gastn-uqaaa-aaaae-aaafq-cai"; 3_573_748_184 = 10_000_000_000; 4_293_698_680 = 0;} }; 2_781_795_542 = 1_621_977_470_858_839_320;};}, +) +In this example, there are twelve event records. The Role field (represented by the hash 1_269_754_742) specifies whether a principal is a controller (represented by the hash 4_218_395_836) or a custodian (represented by the hash 2_494_206_670). The events in this example also illustrate an amount field (represented by the hash 3_573_748_184) with a transfer of 10,000,000,000 cycles. +
+
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/design-apps.xml b/modules/developers-guide/pages/design-apps.xml new file mode 100644 index 000000000..654e08048 --- /dev/null +++ b/modules/developers-guide/pages/design-apps.xml @@ -0,0 +1,57 @@ + + + +
+ +Design apps +2021-08-05 + +As you come up with ideas for applications, you are going to make many design decisions about how to structure and organize your project. +Most of these design decisions are independent of whether you deploy your app on a traditional cloud service or on the Internet Computer. +However, if you are going to deploy on the Internet Computer, there are a few design decisions that you should pay particular attention to as you plan the implementation for your app. + +This section is work-in-progress and incomplete. As best practices and design patterns evolve for building applications that run on the Internet Computer, the information included here will also evolve and change accordingly. + +
+Single or multiple canister architecture +One of the first decisions you might want to consider when designing your application is whether it should be encapsulated in a single canister or consist of multiple canisters. +For example, if you are writing a simple service with no front-end, you might want to use a single canister to simplify project management and maintenance and focus on adding features. +If your application has both front-end assets and back-end business logic, your project is likely to consist of at least two canisters, with one canister for managing user interface components and another canister for the backend services the application provides. +In planning, you might also consider placing some common reusable services in their own canister so that they can be imported and called from other more-specialized canisters or made available for other developers to use. +The LinkedUp sample application illustrates this approach by splitting the professional service application into two canisters. +In the LinkedUp example, the functions that establish social connections are defined in the connectd canister and separate from the functions used to set up professional profiles that are defined in the linkedup canister. +It is easy to imagine extending the application with a third canister, for example to schedule events based on profile attributes or shared connections. +
+
+Segregating actors from types and utilities +In planning the architecture for your project, one common practice is to place the code for the main actor in one file with separate additional files for defining the types you program uses and utility functions that don’t require an actor. +For example, you might set up the back-end logic for your application to consist of the following files: + + +Main.mo or main.rs with the functions that require an actor to send query and update calls. + + +Util.mo or util.rs with helper functions that can be imported for the actor to use. + + +Types.mo or types.rs with all of the data type definitions for your application. + + +
+
+Using query calls +As discussed in Query and update methods, queries return results faster than update calls. Therefore,explicitly marking a function as a query is an effective strategy for improving application performance. +In the planning and design phase, you should consider how best to use query calls instead of functions that can perform queries or updates. +That is a good general rule to follow and can be applied broadly to most categories of applications. +However, you should also consider the security and performance trade-off that queries don’t go through consensus. +For some applications, that trade-off might be appropriate. For example, if you are developing a blogging platform, queries that retrieve articles matching a tag probably don’t warrant going through consensus to ensure that a majority of nodes agree on the results. +However, if your application is retrieving sensitive information—like financial data—you might want more assurance about your results than a basic query provides. +As an alternative to basic queries, the Internet Computer also supports certified queries. Certified queries enable you to receive authenticated responses that you can trust. Using certified queries is an advanced technique that is not covered in the tutorials or other developer-focused documentation, but you can learn about how the authentication works and what you need to do to configure your program to return certified data in response to queries in the Interface specification. +
+
+Data storage and retrieval +For many applications, databases are primarily used to provide long term storage of records that can be retrieved efficiently using one or more key fields. On the Internet Computer, this use case is usually addressed through data structures like hash tables. +Instead of a traditional database, the Internet Computer enables you to use stable memory to handle long-term data storage—often referred to as orthogonal persistance—and to use query calls to retrieve your data. +Although this approach works for most applications and simple key value database requests it doesn’t fully emulate a relational database. +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/glossary.xml b/modules/developers-guide/pages/glossary.xml new file mode 100644 index 000000000..54baccb23 --- /dev/null +++ b/modules/developers-guide/pages/glossary.xml @@ -0,0 +1,112 @@ + + + +
+ +Glossary +2021-08-05 + + + +actor + +An actor is a special kind of object in modern programming languages that processes messages in an isolated state, enabling them to be handled remotely and asynchronously. + + + + + +canister + +A canister is a conceptual object similar to a smart contract with a universally-unique identifier and an owner that defines the boundaries of a specific application, service, or micro-site. +A canister encapsulates all of the programming logic, public entry methods, the interface description for the provided message types, and state information for the application, service, or micro-service it describes. + + + + + +controller + +A controller is an identity that has special rights to manage the canister it controls. +For example, only a controlling identity can be used to install, upgrade, or delete the canister under its control. +You can specify the controller identity using the textual representation of a principal—often referred to as the principal identifier—associated with a user or with a canister. + + + + + +ledger + +The Internet Computer records all transactions involving ICP tokens in a specialized management canister, called the ledger canister.The ledger canister is a simplified parallel blockchain that runs on the Internet Computer in a subnet with other network management canisters. +The ledger canister implements a smart contract that holds accounts and balances and keeps a history of the transactions that affect accounts and balances. The transactions are recorded to track the following specific events: + + +Mint ICP tokens for accounts. + + +Transfer ICP tokens from one account to another. + + +Burn ICP tokens to eliminate them from existence. + + + + + + + +node + +A physical computer that is a registered member of the {platform} network and running the Internet Computer replica processes. + + + + + +principal + +The first time you use the {sdk-short-name}, the dfx command-line tool creates a default developer identity for you with a public/private key pair in a PEM file. This Internet Computer developer identity is represented internally by a derived principal data type and a textual representation of the principal often referred to as your principal identifier. +The developer identity can also be used to derive an account identifier—similar to a Bitcoin or Ethereum address—to hold ICP tokens on your behalf in the Internet Computer ledger canister. + + + + + +replica + +In the context of the {platform}, a replica refers to the Internet Computer processes (for example, the replica, nodemanager, and other lower-level Internet Computer protocol processes) running on a physical computer node in the network. +For the {sdk-short-name}, you use the dfx start and dfx stop commands to start and stop the replica process locally to provide a local network for development. + + + + + +smart contract + +A smart contract is software that enables trusted transactions and agreements to be carried out across a distributed, decentralized blockchain network without the need for any central authority or legal system. +With a smart contract, the terms of a transaction or agreement are written directly into lines of code that are executed on the blockchain network. +The code controls the execution, and the transactions are tamper-proof, traceable, and irreversible. +On the Internet Computer, smart contracts are deployed as canisters. + + + + + +wallet + +On the Internet Computer, a wallet is a specialized application that allows you to store and retrieve your digital assets. +The wallet application is implemented as a canister that runs on the Internet Computer. A wallet enables you to manage your ICP token balances, convert ICP token into cycles, and distribute cycles to your own or other users' canisters as a means for accessing or providing internet services. + + + + + +WebAssembly + +WebAssembly (Wasm) is a low-level computer instruction format. +Because WebAssembly defines a portable,open-standard, binary format that abstracts cleanly over most modern computer hardware, it is broadly supported for programs that run on the internet. +Programs written in Motoko are compiled to WebAssembly code for execution on Internet Computer replicas. + + + +
\ No newline at end of file diff --git a/modules/developers-guide/pages/install-upgrade-remove.xml b/modules/developers-guide/pages/install-upgrade-remove.xml new file mode 100644 index 000000000..b603f79a0 --- /dev/null +++ b/modules/developers-guide/pages/install-upgrade-remove.xml @@ -0,0 +1,117 @@ + + + +
+ +Install, upgrade, or remove software +2021-08-05 + +As described in the Quick start, you can download and install the latest version of the {sdk-short-name} package by running a command in a terminal shell. +The topics in this section provide additional information about installing, upgrading, and removing the {sdk-short-name}. +ROOT:page$download.adoc +
+Reviewing the license agreement +The installation script prompts you to read and accept the DFINITY Canister SDK License Agreement before installing the dfx command-line interface executable and its dependencies on your local computer. +You must type y and press Enter to continue with the installation. +After you accept the license agreement, the installation script displays information about the components being installed on the local computer. +
+
+What gets installed +The {sdk-short-name} installation script installs several components in default locations on your local computer. +The following table describes the development environment components that the installation script installs: + + + + + + + +Component +Description +Default location + + + + +dfx +DFINITY execution command-line interface (CLI) +/usr/local/bin/dfx + + +moc +Motoko runtime compiler +~/.cache/dfinity/versions/<VERSION>/moc + + +replica +Internet Computer local network binary +~/.cache/dfinity/versions/<VERSION>/replica + + +uninstall.sh +Script to remove the {sdk-short-name} and all of its components +~/.cache/dfinity + + +versions +Cache directory that contains a subdirectory for each version of the {sdk-short-name} you install. +~/.cache/dfinity/versions + + + + +
+Core components in a versioned directory +The ~/.cache/dfinity/versions directory stores one or more versioned subdirectories of the {sdk-short-name}. +Each versioned subdirectory contains the all of the directories and files required for a specific version of the {sdk-short-name}. +For example, if you list the contents of the ~/.cache/dfinity/versions/0.8.0 directory you would see the following core components: +total 349192 +drwxr-xr-x 17 pubs staff 544 Mar 15 11:55 . +drwxr-xr-x 4 pubs staff 128 Mar 25 14:36 .. +drwxr-xr-x 49 pubs staff 1568 Mar 15 11:55 base +drwxr-xr-x 20 pubs staff 640 Mar 15 11:55 bootstrap +-r-x------ 1 pubs staff 66253292 Mar 15 11:55 dfx +-r-x------ 1 pubs staff 10496256 Dec 31 1969 ic-ref +-r-x------ 1 pubs staff 5663644 Dec 31 1969 ic-starter +-r-x------ 1 pubs staff 9604 Dec 31 1969 libcharset.1.0.0.dylib +-r-x------ 1 pubs staff 38220 Dec 31 1969 libffi.7.dylib +-r-x------ 1 pubs staff 668300 Dec 31 1969 libgmp.10.dylib +-r-x------ 1 pubs staff 958248 Dec 31 1969 libiconv.2.4.0.dylib +-r-x------ 1 pubs staff 4200 Dec 31 1969 libiconv.dylib +-r-x------ 1 pubs staff 96900 Dec 31 1969 libz.1.2.11.dylib +-r-x------ 1 pubs staff 15417684 Dec 31 1969 mo-doc +-r-x------ 1 pubs staff 14634020 Dec 31 1969 mo-ide +-r-x------ 1 pubs staff 15111508 Dec 31 1969 moc +-r-x------ 1 pubs staff 49404128 Dec 31 1969 replica +
+
+Motoko base directory +The base directory in the versioned subdirectory of the {sdk-short-name} contains the Motoko base library modules that are compatible with that version of the {sdk-short-name}. +Because the Motoko base library is evolving rapidly, you should only use the base modules that are packaged with the version of the {sdk-short-name} that you have installed. +
+
+Bootstrap directory +The bootstrap directory contains web server code that is deprecated. +Beginning with version 0.7.0, agents can call an HTTP middleware server instead of the bootstrap code. +This change enables canisters to respond to HTTP requests directly and operate more like traditional web-based applications. +
+
+
+Upgrading to the latest version +If a new version of the {sdk-short-name} is available for download after your initial installation, you should install the updated version at your earliest convenience to get the latest fixes and enhancements as soon as possible. +You can use the dfx upgrade command to compare the version you have currently installed against the latest version available for download. +If a newer version of dfx is available, the dfx upgrade command automatically downloads and installs the latest version. +Note that you don’t need to uninstall the software before installing the new version. +However, if you want to perform a clean installation rather than an upgrade, you can first uninstall the software as described in Removing the software, then re-run the download and installation command. +For information about the features and fixes in the latest release, see the Release notes. +
+
+Removing the software +When you install the {sdk-short-name}, the installation script puts the required binary files in a local directory and creates a cache. +You can remove the SDK binaries and cache from your local computer by running the uninstall script located in the .cache folder. +For example: +~/.cache/dfinity/uninstall.sh +If you are uninstalling because you want to immediately reinstall a clean version of dfx, you can run the following command: +~/.cache/dfinity/uninstall.sh && sh -ci "$(curl -sSL https://sdk.dfinity.org/install.sh)" +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/lang-service-ide.xml b/modules/developers-guide/pages/lang-service-ide.xml new file mode 100644 index 000000000..38ed3f6d9 --- /dev/null +++ b/modules/developers-guide/pages/lang-service-ide.xml @@ -0,0 +1,102 @@ + + + +
+ +Language server and development client support +2021-08-05 + + +December 2019 (Alpha 3) + + +D + +The Language Server Protocol (LSP)—originally developed by Microsoft—provides a common language to add broadly-useful features like automatic code complete, GoTo definition, and hover-over tool tips +to development tools. +Using the Language Server Protocol, a language server enables standardized inter-process communication between a programming language and any editor, integrated development environment (IDE), or client endpoint tool. +Because the Language Server Protocol (LSP) standardizes the protocol for how language-specific servers and development tools communicate, a single language server can be re-used in multiple development tools with minimal effort. +
+Adding a language server for Motoko +With the {sdk-short-name}, you can add a language server for Motoko to your editor or development environment client by invoking the dfx _language-service programmatically when you open Motoko programs in an editor or development environment configured to recognize the language server. +You can use any editor or integrated development environment that supports the Language Server Protocol to invoke the dfx _language-service programmatically. Once invoked, the language server ensures that your development environment reports Motoko compiler errors and provides code completion and refactoring tools. +For example, if you use Visual Studio Code (VSCode) or Emacs as your development environment, you can install a plugin extension that enables those editors to automatically invoke the Motoko language server. + +Only the Visual Studio Code (VSCode) plugin extension is currently available for Motoko. +For information about installing the plugin, see Install the language editor plug-in. + +
+
+Invoking the language service manually +Although it is extremely rare that you would start the Motoko language server directly in a terminal shell. it is possible to do so by running the following command: +dfx _language-service --force-tty +Note that you can only run this command from within a project directory. +For example, if your project name is hello_world, your current working directory must be the hello_world top-level project directory or one of its subdirectories. +
+Basic usage +dfx _language-service [canister_name] [flag] +
+
+Flags +You can use the following optional flags with the dfx _language-service command. + + + + + + +Flag +Description + + + + +--force-tty +Starts the the Motoko language server directly in a terminal shell. + + +-h, --help +Displays usage information. + + +-V, --version +Displays version information. + + + + +
+
+Arguments +You can specify the following arguments for the dfx _language-service command. + + + + + + + + + +Argument +Description + + + + +canister_name +Specifies the name of the canister that the compiler should monitor. +If you specify a canister name, the name should match a canister name you have configured in the dfx.json configuration file for your project. +If you don’t specify a canister name, the first canister specified in the dfx.json configuration file is used as the target. + + + + +
+
+Examples +If you want to use an integrated development environment to develop code for the canister my-canister you should have the development environment invoke the language service using the following dfx _language-service command: +dfx _language-service my-canister +
+
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/sample-apps.xml b/modules/developers-guide/pages/sample-apps.xml new file mode 100644 index 000000000..412b39c17 --- /dev/null +++ b/modules/developers-guide/pages/sample-apps.xml @@ -0,0 +1,124 @@ + + + +
+ +Sample code, applications, and microservices +2021-08-05 + + +May 2020 (Alpha) + + +M + +Sample code, applications, and microservices that have been developed by DFINITY or contributed by the community are available from the DFINITY public repository. +By accessing the public repository, you can directly download, clone, fork, or share sample projects. +You will also be able to contribute by suggesting updates or reporting issues for the published projects using the standard GitHub work flow. +Sample projects provide a way for you to experiment and collaborate with other developers. +The projects and sample code are not, however, intended to be used as commercial applications and do not provide any explicit or implied support or warranty of any kind. +This section provides a preliminary look at some sample code for applications and microservices that you can copy and modify to jump-start your own projects. +
+C +For examples of projects written in the C programming language for the Internet Computer, see C++ sample projects. + + +Adventure game + + +QR code generator + + +Reverse game + + +
+
+Motoko +For projects that use the Motoko programming language, see Motoko sample projects. + + +Calculator - simple functions + + +Counter + + +Echo + + +Factorial + + +Hello, world + + +Hello, cycles + + +Game of Life - upgrades + + +Phone book + + +Publish/subscribe + + +Quicksort + + +Random maze - cryptographic randomness + + +To-do checklist + + +Superheroes database + + +whoami + + +
+
+Additional sample applications +This section includes sample code from projects that are not currently available in the public repository. +
+Hex encoding and decoding +The mo-hex project implements hexadecimal encoding and decoding routines for the Motoko programming language. +
+Source code +The project includes the following hex.mo source code. +
+hex.mo +Unresolved directive in sample-apps.adoc - include::example$hex/hex.mo[] +
+
+
+
+Polynomial long-division in GF(256) +This program performs polynomial long division for a Galois field GF(256) element. +
+Source code +In addition to standard libraries, this project uses two main Motoko source code files. + + +The Galois.mo file contains the core programming logic. + + +The Nat.mo file contains additional functions that are imported for use in the Galois.mo file. + + +
+Galois.mo +Unresolved directive in sample-apps.adoc - include::example$galois/Galois.mo[] +
+
+Nat.mo +Unresolved directive in sample-apps.adoc - include::example$galois/Nat.mo[] +
+
+
+
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/sdk-guide.xml b/modules/developers-guide/pages/sdk-guide.xml new file mode 100644 index 000000000..e34aa7e80 --- /dev/null +++ b/modules/developers-guide/pages/sdk-guide.xml @@ -0,0 +1,32 @@ + + + +
+ +{IC} SDK - Developer Tools +2021-08-05 + +The {platform} is poised to help you start a revolution with a new way to design, build, and release software. +
+Developing open internet applications +Conceptually, the Internet Computer is an extension of the existing internet that enables a global network of computers to provide the computing power for running application software. +In much the same way that the adoption of the transport control protocol (TCP) and Internet protocol (IP) provided rules for transferring data between endpoints that helped to establish the “network of networks” that we know as the internet of today, the Internet Computer relies on a decentralization protocol called the Internet Computer protocol to define the software components that enable a global network of computers to combine their resources to read, replicate, modify, and return application state. +
+
+Developer workflow at-a-glance +At a high-level, there are three possible workflows for building applications that run on the Internet Computer. + + + + +Development paths + +The first path is the most common: you connect to the Internet Computer running locally, then write, compile, and deploy iteratively in a local development environment. +If you prefer to do all of your development work without connecting to a local or remote network, you can follow the second path and only connect to the network when you are ready to compile and deploy. +With this option, you only connect to the Internet Computer network and register for a unique identifier after you have a program ready to deploy. +In the third path, you connect to the Internet Computer running on a remote network, then register for a unique identifier before you have a program ready to compile. +With this option, you can preregister with the network to receive a unique identifier, then compile and deploy using a known identifier when you are ready to move your application to the network. +Regardless of the development workflow you choose, keep in mind that you must connect to the Internet Computer network running locally or on a remote subnet to register your smart contract canister and that registering your canister creates a unique, network-specific identifier for the canister. +For example, if you do all of your initial development work locally using a local canister identifier and later want to deploy your application on an Internet Computer network running remotely, you will need to connect to the remote network and register an identifier on that network before you can deploy the application. +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/troubleshooting.xml b/modules/developers-guide/pages/troubleshooting.xml new file mode 100644 index 000000000..5f3352ab9 --- /dev/null +++ b/modules/developers-guide/pages/troubleshooting.xml @@ -0,0 +1,143 @@ + + + +
+ +Troubleshoot issues +2021-08-05 + + +December 2019 (Alpha) + + +D + +This section provides information to help you troubleshoot and resolve or work around common issues that are related to the following tasks: + + +downloading and installing the {sdk-short-name} + + +creating, building, or deploying canisters + + +using the dfx command-line interface + + +running the Internet Computer network locally in a development environment + + +developers-guide:page$webpack-config.adoc +
+Migrating an existing project +Currently, there is no automatic migration or backward compatibility for any projects that you might have created using previous versions of the dfx command-line interface. +After upgrading to the latest version, you might see error or failure messages if you attempt to build or install a project created with a previous version of the dfx command-line interface. +In many cases, however, you can continue to work with projects from a previous release by manually changing the dfx setting in the dfx.json configuration file, then rebuilding the project to be compatible with the version of the dfx command-line interface you have currently installed. +For example, if you have a project that was created with dfx version 0.4.9, open the dfx.json file in a text editor and change the dfx setting to the latest version or remove the section entirely. +
+
+Restarting the local Internet Computer network +In some cases, starting the Internet Computer network locally fails because of replicated state errors. +If you encounter issues when running dfx start to start the local Internet Computer network: + + +In the terminal that displays network operations, press Control-C to interrupt the local network process. + + +Stop the Internet Computer network by running the following command: +dfx stop + + +Restart the Internet Computer in a clean state by running the following command: +dfx start --clean +The --clean option removes checkpoints and stale state information from your project’s cache so that you can restart the Internet Computer replica and web server processes in a clean state. + + +Keep in mind, however, that if you reset the state information by running dfx start --clean, your existing canisters are also removed. +After running dfx start --clean, recreate your canisters by running the following commands: +dfx canister create --all +dfx build +dfx canister install --all +
+
+Removing the canisters directory +If you run into problems building or deploying canisters after successfully connecting to the Internet Computer and registering canister identifiers, you should remove the canisters directory before attempting to rebuild or redeploy the canisters. +You can remove the canisters directory for a project by running the following command in the project’s root directory: +rm -rf ./.dfx/* canisters/* +
+
+Reinstalling dfx +Many of the bugs you might encounter can be addressed by uninstalling and reinstalling the dfx command-line interface. +Here are a few ways to reinstall dfx. +If you only have one version of dfx installed in your development environment, you can usually run the following command to uninstall and reinstall the latest version of dfx: +~/.cache/dfinity/uninstall.sh && sh -ci "$(curl -sSL https://sdk.dfinity.org/install.sh)" +If you have modified the location of the dfx binary, you might want run the following command to uninstall the version of dfx that is in your PATH, then reinstall the latest version of dfx: +rm -rf ~/.cache/dfinity && rm $(which dfx) && sh -ci "$(curl -sSL https://sdk.dfinity.org/install.sh)" +
+
+Xcode prerequisite +Some versions of the {sdk-short-name} prompted you to install Xcode when creating a new project on a macOS computer. +The prompt has been removed and the dfx new command does not require you to install any macOS developer tools. +However, you should have Developer Command Line Tools installed if you want to create a Git repository for your project. +You can check whether you have the developer tools installed by running xcode-select -p. +You can install the developer tools by running xcode-select --install. +
+
+Failed build when using VMs +If you are running dfx using a virtual machine image on Ubuntu or CentOS, you might see an error message that looks like this when you attempt to run the dfx build command: +Building hello... +An error occurred: +Io( + Os { + code: 2, + kind: NotFound, + message: "No such file or directory", + }, +) +
+
+Address in use error or orphan processes +If you are developing projects locally, you often have a local version of core Internet Computer processes—collectively referred to as the replica—running either is a separate terminal or in the background. +If the running Internet Computer processes do not get properly terminated, you might see operating system errors indicating that an address is already in use or or be unable to stop processes normally using the dfx stop command. +There are several scenarios in which you might encounter this issue. For example, if you run dfx start in a local project directory then change to a different local project directory without first stopping Internet Computer processes, you might see this issue. +If you encounter an issue where you suspect or you receive a message that an address is already in use or that a process is already running in the background, perform the following steps: + + +Run the following command to see which process is listening to the 8000 port if you are using the default local network binding: +lsof -i tcp:8000 + + +Run the following command to terminate any orphan processes: +killall dfx replica + + +Close the current terminal and open a new terminal window. + + +In the new terminal, run the following command to run the local Internet Computer in a clean state: +dfx start --clean --background + + +
+
+Memory leak +Fixing memory leaks is an ongoing process. If you encounter any error messages related to memory leaks, you should do the following: + + +Run dfx stop to stop currently running processes. + + +Uninstall dfx to prevent further degradation. + + +Re-install dfx + + +Run dfx start to restart replica processes. + + +Alternatively, you can remove the .cache/dfinity directory and re-install the latest dfx binary. +For example: +rm -rf ~/.cache/dfinity && sh -ci "$(curl -sSL https://sdk.dfinity.org/install.sh)" +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/tutorials-intro.xml b/modules/developers-guide/pages/tutorials-intro.xml new file mode 100644 index 000000000..0895a016b --- /dev/null +++ b/modules/developers-guide/pages/tutorials-intro.xml @@ -0,0 +1,60 @@ + + + +
+ +Tutorials +2021-08-05 + +The Quick start provided a simplified introduction to the basic work flow for creating and deploying a new project without exploring the contents of the project directory or sample code. +Next, we’ll explore writing a few simple programs to give you hands-on experience creating programs that run on the {IC}. + +Most of these tutorials illustrate how to write programs using the {proglang} programming language. +For additional examples of programs written in other languages, see the {company-id} examples repository. + +The following tutorials introduce the basics for writing programs that run on the {IC}: + + +Explore the default project takes a closer look at the work flow for creating projects by exploring the default files and folders that are added to your workspace when you create a new project. + + +Query using an actor highlights how to replace the typical print function usually defined in a "Hello, World!" program by defining an actor (object) with a hello function. + + +Pass text arguments introduces different ways you can pass arguments to a function using the command-line in a terminal shell. + + +Increment a natural number guides you through the process of writing a program that creates an actor with functions to increment and return the value of a counter. + + +Use integers in calculator functions shows you how to write a simple calculator program for more practice working with {proglang} and to learn more about how you can customize your project environment. + + +Import library modules illustrates how to import and use a few basic {proglang} base library functions for working with key-value pairs in a list. + + +Use multiple actors describes how to include multiple unrelated actors in a single project to illustrate how you can compile multiple canisters for the same project. + + +Customize the front-end illustrates using a simple React framework to create a new front-end for the default sample program and guides you through some basic modifications to customize the interface displayed. +If you already know how to use CSS, HTML, JavaScript, and React or other frameworks to build your user interface, you can skip this tutorial. + + +Add a stylesheet illustrates how to add a stylesheet when you use React to create a new front-end for your project. +If you already know how to add stylesheets to React, you can skip this tutorial. + + +Make inter-canister calls illustrates how to make simple calls to functions defined in one canister from another canister in the same project. + + +Create scalable apps describes using multiple canisters to create applications that scale. + + +Add access control with identities describes how to create and switch between multiple user identities. + + +Accept cycles from a wallet illustrates how to accept cycles sent from the default wallet canister. + + +Additional tutorials covering more advanced programs and more detailed examples of how to use the basic building blocks are available in the examples repository and {proglang} Programming Language Guide. +
\ No newline at end of file diff --git a/modules/developers-guide/pages/tutorials/access-control.xml b/modules/developers-guide/pages/tutorials/access-control.xml new file mode 100644 index 000000000..e5d4b839c --- /dev/null +++ b/modules/developers-guide/pages/tutorials/access-control.xml @@ -0,0 +1,400 @@ + + + +
+ +Add access control with identities +2021-08-05 + +Applications often require role-based permissions to control the operations different users can perform. +To illustrate how to create and switch between user identities, this tutorial creates a simple program that displays a different greeting for users who are assigned to different roles. +In this example, there are three named roles—owner, admin, and authorized. + + +Users who are assigned an admin role see a greeting that displays You have a role with administrative privileges. + + +Users who are assigned an authorized role see a greeting that displays Would you like to play a game?. + + +Users who are not assigned one of these roles see a greeting that displays Nice to meet you!. + + +In addition, only the user identity that initialized the canister is assigned the owner role and only the owner and admin roles can assign roles to other users. +At a high-level, each user has a public/private key pair. The public key combines with the canister identifier the user accesses forms a security principal that can then be used as a message caller to authenticate function calls made to the canister running on the Internet Computer. +The following diagram provides a simplified view of how user identities authenticate message callers. + + + + + +principal identities + + +
+Before you begin +Before starting the tutorial, verify the following: + + +You have downloaded and installed the {sdk-short-name} package as described in Download and install. + + +You have run at least one command that resulted in your default user identity being created. +Your default user identity is stored globally for all projects in the $HOME/.config/dfx/identity/ directory. + + +You have installed the Visual Studio Code plugin for Motoko as described in Install the language editor plug-in if you are using Visual Studio Code as your IDE. + + +You have stopped any Internet Computer network processes running on the local computer. + + +
+
+Create a new project +To create a new project directory for testing access control and switching user identities: + + +Open a terminal shell on your local computer, if you don’t already have one open. + + +Change to the folder you are using for your Internet Computer projects, if you are using one. + + +Create a new project by running the following command: +dfx new access_hello + + +Change to your project directory by running the following command: +cd access_hello + + +
+
+Modify the default program +For this tutorial, you are going to replace the template source code file with a program that has functions for assigning and retrieving roles. +To modify the default program: + + +Open the src/access_hello/main.mo file in a text editor and delete the existing content. + + +Copy and paste the following sample code into the file: +Unresolved directive in access-control.adoc - include::example$access-hello/main.mo[] +Let’s take a look at a few key elements of this program: + + +You might notice that the greet function is a variation on the greet function you have seen in previous tutorials. +In this program, however, the greet function uses a message caller to determine the permissions that should be applied and, based on the permissions associated with the caller, which greeting to display. + + +The program defines two custom types—one for Roles and one for Permissions. + + +The assign_roles function enables the message caller to assign a role to the principal associated with an identity. + + +The callerPrincipal function enables you to return the principal associated with an identity. + + +The my_role function enables you to return the role that is associated with an identity. + + + + +Save your changes and close the main.mo file to continue. + + +
+
+Start the local network +Before you can build the access_hello project, you need to connect to the Internet Computer network either running locally in your development environment or running remotely on a subnet that you can access. +To start the network locally: + + +Open a new terminal window or tab on your local computer. + + +Navigate to the root directory for your project, if necessary. + + +Start the Internet Computer network on your local computer by running the following command: +dfx start --background +After the local Internet Computer network completes its startup operations, you can continue to the next step. + + +
+
+Register, build, and deploy the application +After you connect to the Internet Computer network running locally in your development environment, you can register, build, and deploy your application in a single step by running the dfx deploy command. +You can also perform each of these steps independently using separate dfx canister create, dfx build, and dfx canister install commands. +To deploy the application locally: + + +Check that you are still in the root directory for your project, if needed. + + +Register, build, and deploy the access_hello back-end program by running the following command: +dfx deploy access_hello +Creating a wallet canister on the local network. +The wallet canister on the "local" network for user "default" is "rwlgt-iiaaa-aaaaa-aaaaa-cai" +Deploying: access_hello +Creating canisters... +Creating canister "access_hello"... +"access_hello" canister created with canister id: "rrkah-fqaaa-aaaaa-aaaaq-cai" +Building canisters... +Installing canisters... +Installing code for canister access_hello, with canister_id rrkah-fqaaa-aaaaa-aaaaq-cai +Deployed canisters. + + +
+
+Check the current identity context +Before we create any additional identities, let’s review the principal identifiers associated with your default identity and the cycles wallet for your default identity. +On the Internet Computer, a principal is the internal representative for a user, canister, node, or subnet. The textual representation for a principal is the external identifier you see displayed with working with the principal data type. +To review your current identity and principle: + + +Verify the currently-active identity by running the following command: +dfx identity whoami +The command displays output similar to the following: +default + + +Check the principal for the default user identity by running the following command: +dfx identity get-principal +The command displays output similar to the following: +zen7w-sjxmx-jcslx-ey4hf-rfxdq-l4soz-7ie3o-hti3o-nyoma-nrkwa-cqe + + +Check the role associated with the default user identity by running the following command: +dfx canister --wallet=$(dfx identity get-wallet) call access_hello my_role +The command displays output similar to the following: +(opt variant { owner }) + + +
+
+Create a new user identity +To begin testing the access controls in our program, let’s create some new user identities and assign those users to different roles. +To create a new user identity: + + +Check that you are still in your project directory, if needed. + + +Create a new administrative user identity by running the following command: +dfx identity new ic_admin +The command displays output similar to the following: +Creating identity: "ic_admin". +Created identity: "ic_admin". + + +Call the my_role function to see that your new user identity has not been assigned to any role. +dfx --identity ic_admin canister call access_hello my_role +The command displays output similar to the following: +Creating a wallet canister on the local network. +The wallet canister on the "local" network for user "ic_admin" is "ryjl3-tyaaa-aaaaa-aaaba-cai" +(null) + + +Switch your currently-active identity context to use the new ic_admin user identity and display the principal associated with the ic_admin user by running the following command: +dfx identity use ic_admin && dfx identity get-principal +The command displays output similar to the following: +Using identity: "ic_admin". +c5wa6-3irl7-tuxuo-4vtyw-xsnhw-rv2a6-vcmdz-bzkca-vejmd-327zo-wae + + +Check the principal used to call the access_hello canister by running the following command: +dfx canister call access_hello callerPrincipal +The command displays output similar to the following: +(principal "ryjl3-tyaaa-aaaaa-aaaba-cai") +By default, the cycles wallet identifier is the principal used to call the methods in the access_hello canister. +To illustrate access control, however, we want to use the principal associated with the user context, not the cycles wallet. +Before we get to that step, though, let’s assign a role to the ic_admin user. To do that, we need to switch to the default user identity that has the owner role. + + +
+
+Assign a role to an identity +To assign the admin role to the ic_admin identity: + + +Switch your currently-active identity context to use the default user identity by running the following command: +dfx identity use default + + +Assign the ic_admin principal the admin role by running a command similar to the following using Candid syntax: +dfx canister --wallet=$(dfx identity get-wallet) call access_hello assign_role '((principal "c5wa6-3irl7-tuxuo-4vtyw-xsnhw-rv2a6-vcmdz-bzkca-vejmd-327zo-wae"),opt variant{admin})' + + + +Be sure to replace the principal hash with the one returned by the dfx identity get-principal command for the ic_admin identity. + ++ +Optionally, you can rerun the command to call the my_role function to verify the role assignment. ++ +dfx --identity ic_admin canister call access_hello my_role ++ +The command displays output similar to the following: ++ +(opt variant { admin }) + + +Call the greet function using the ic_admin user identity that you just assigned the admin role by running the following command: +dfx --identity ic_admin canister call access_hello greet "Internet Computer Admin" +The command displays output similar to the following: +( + "Hello, Internet Computer Admin. You have a role with administrative privileges.", +) + + +
+
+Add an authorized user identity +At this point, you have a default user identity with the owner role and an ic_admin user identity with the admin role. +Let’s add another user identity and assign it to the authorized role. +For this example, however, we’ll use an environment variable to store the user’s principal. +To add a new authorized user identity: + + +Check that you are still in your project directory, if needed. + + +Create a new authorized user identity by running the following command: +dfx identity new alice_auth +The command displays output similar to the following: +Creating identity: "alice_auth". +Created identity: "alice_auth". + + +Switch your currently-active identity context to use the new alice_auth user identity by running the following command: +dfx identity use alice_auth + + +Store the principal for the alice_auth user in an environment variable by running the following command: +ALICE_ID=$(dfx identity get-principal) +You can verify the principal stored by running the following command: +echo $ALICE_ID +The command displays output similar to the following: +b5quc-npdph-l6qp4-kur4u-oxljq-7uddl-vfdo6-x2uo5-6y4a6-4pt6v-7qe + + +Use the ic_admin identity to assign the authorized role to alice_auth by running the following command: +dfx --identity ic_admin canister call access_hello assign_role "(principal \"$ALICE_ID\", opt variant{authorized})" + + +Call the my_role function to verify the role assignment. +dfx --identity alice_auth canister call access_hello my_role +The command displays output similar to the following: +(opt variant { authorized }) + + +Call the greet function using the alice_auth user identity that you just assigned the authorized role by running the following command: +dfx canister call access_hello greet "Alice" +The command displays output similar to the following: +( + "Welcome, Alice. You have an authorized account. Would you like to play a game?", +) + + +
+
+Add an unauthorized user identity +You have now seen a simple example of creating users with specific roles and permissions. +The next step is to create a user identity that is not assigned to a role or given any special permissions. +To add an unauthorized user identity: + + +Check that you are still in your project directory, if needed. + + +Check your currently-active identity, if needed, by running the following command: +dfx identity whoami + + +Create a new user identity by running the following command: +dfx identity new bob_standard +The command displays output similar to the following: +Creating identity: "bob_standard". +Created identity: "bob_standard". + + +Store the principal for the bob_standard user in an environment variable by running the following command: +BOB_ID=$(dfx --identity bob_standard identity get-principal) + + +Attempt to use the bob_standard identity to assign a role. +dfx --identity bob_standard canister call access_hello assign_role "(principal \"$BOB_ID\", opt variant{authorized})" +This command returns an unauthorized error. + + +Attempt to use the default user identity to assign bob_standard the owner role by running the following command: +dfx --identity default canister --wallet=$(dfx --identity default identity get-wallet) call access_hello assign_role "(principal \"$BOB_ID\", opt variant{owner})" +This command fails because users cannot be assigned the owner role. + + +Call the greet function using the bob_standard user identity by running the following command: +dfx --identity bob_standard canister --no-wallet call access_hello greet "Bob" +The command displays output similar to the following: +("Greetings, Bob. Nice to meet you!") + + +
+
+Set the user identity for multiple commands +So far, you have seen how to create and switch between user identities for individual commands. +You can also specify a user identity you want to use, then run multiple commands in the context of that user identity. +To run multiple commands under one user identity: + + +Check that you are still in your project directory, if needed. + + +List the user identities currently available by running the following command: +dfx identity list +The command displays output similar to the following with an asterisk indicating the currently-active user identity. +alice_auth +bob_standard +default * +ic_admin +In this example, the default user identity is used unless you explicitly select a different identity. + + +Select a new user identity from the list and make it the active user context by running a command similar to the following: +dfx identity use ic_admin ++ The command displays output similar to the following: +Using identity: "ic_admin". +If you rerun the dfx identity list command, the ic_admin user identity displays an asterisk to indicate it is the currently active user context. +You can now run commands using the selected user identity without specifying --identity on the command-line. + + +
+
+Stop the local network +After you finish experimenting with the program and using identities, you can stop the local Internet Computer network so that it doesn’t continue running in the background. +To stop the local network: + + +In the terminal that displays network operations, press Control-C to interrupt the local network process. + + +Stop the Internet Computer network by running the following command: +dfx stop + + +
+
+Want to learn more? +If you are looking for more information about identity and authentication, check out the following related resources: + + +dfx identity (command reference) + + +Set an identity to own a canister (how-to) + + +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/tutorials/at-a-glance.xml b/modules/developers-guide/pages/tutorials/at-a-glance.xml new file mode 100644 index 000000000..a6aa4f712 --- /dev/null +++ b/modules/developers-guide/pages/tutorials/at-a-glance.xml @@ -0,0 +1,35 @@ + + + +
+ +At a glance +2021-08-05 + +The Quick start provides a fast path to deploying a simple default application without stopping to admire the scenery along the way. +Individual tutorials walk through specific scenarios, pointing out details about what you’re doing in each step. +If the quick start and tutorials aren’t quite your style, this at-a-glance cheat sheet summarizes the steps to follow for quick reference. +After you install the {sdk-short-name}, here’s all you need to know: + + +Create a new project and change to the project directory. +dfx new <project_name> && cd <project_name>> + + +Edit the back-end that defines your service or application. + + +Edit the HTML, JavaScript, and CSS that provides the front-end for your service or application. + + +Start the Internet Computer for local development or check your connection to the Internet Computer for network deployment. + + +Register, build, and deploy locally or on the network. +dfx deploy --network <network> + + +View your service or application in a browser. + + +
\ No newline at end of file diff --git a/modules/developers-guide/pages/tutorials/calculator.xml b/modules/developers-guide/pages/tutorials/calculator.xml new file mode 100644 index 000000000..b49459fe8 --- /dev/null +++ b/modules/developers-guide/pages/tutorials/calculator.xml @@ -0,0 +1,233 @@ + + + +
+ +Use integers in calculator functions +2021-08-05 + +In this tutorial, you are going to write a simple calculator program that creates a single actor with several public entry-point functions to perform basic arithmetic operations. +For this tutorial, the actor is named Calc. +The program uses the cell variable to contain an integer number that represents the current result of a calculator operation. +This program supports the following function calls: + + +The add function call accepts input and performs addition. + + +The sub function call accepts input and performs subtraction. + + +The mul function call accepts input and performs multiplication. + + +The div function call accepts input and performs division. + + +The clearall function clears the cell value stored as the result of previous operations, resetting the cell value to zero. + + +The div function also includes code to prevent the program from attempting to divide by zero. +
+Before you begin +Before starting the tutorial, verify the following: + + +You have downloaded and installed the {sdk-short-name} package as described in Download and install. + + +You have stopped any Internet Computer network processes running on the local +computer. + + +This tutorial takes approximately 20 minutes to complete. +
+
+Create a new project +To create a new project for this tutorial: + + +Open a terminal shell on your local computer, if you don’t already +have one open. + + +Change to the folder you are using for your Internet Computer projects, if you are using one. + + +Create a new project by running the following command: +dfx new calc + + +Change to your project directory by running the following command: +cd calc + + +
+
+Modify the default configuration +For this tutorial, let’s modify the default dfx.json configuration file to use a more specific name for its main program. +To modify the default dfx.json configuration file: + + +Open the dfx.json configuration file in a text editor. + + +Change the main key setting from the default main.mo program name to calc_main.mo. +For example: +"main": "src/calc/calc_main.mo", +For this tutorial, changing the name of the source file from main.mo to calc_main.mo simply illustrates how the setting in the dfx.json configuration file determines the source file to be compiled. +In a more complex application, you might have multiple source files instead of a single main program file. +More complex applications might also have specific dependencies between multiple source files that you need to manage using settings in the dfx.json configuration file. +In a scenario like that—with multiple canisters and programs defined in your dfx.json file—having multiple files all named main.mo might make navigating your workspace more difficult. +The name you choose for each program isn’t significant, but it is important that the name you set in the dfx.json file matches the name of your program in the file system. + + +Save your changes and close the file to continue. + + +
+
+Modify the default program +For this tutorial, you need to replace the default program with a program that performs basic arithmetic operations. +To replace the default program: + + +Check that you are still in your project directory, if needed. + + +Copy the template main.mo file to create a new file named calc_main.mo by running the following command: +cp src/calc/main.mo src/calc/calc_main.mo + + +Open the src/calc/calc_main.mo file in a text editor and delete the existing content. + + +Copy and paste the following sample code into the calc_main.mo file: +Unresolved directive in calculator.adoc - include::example$calc_main.mo[] +You might notice that this sample code uses integer (Int) data types, enabling you to use positive or negative numbers. +If you wanted to restrict the functions in this calculator code to only use positive numbers, you could change the data type to only allow natural (Nat) data. + + +Save your changes and close the file to continue. + + +
+
+Start the local network +Before you can build the calc project, you need to connect to the Internet Computer network either running locally in your development environment or running remotely on a subnet that you can access. +Starting the network locally requires a dfx.json file, so you should be sure you are in your project’s root directory. +For this tutorial, you should have two separate terminal shells, so that you can start and see network operations in one terminal and manage your project in another. +To start the network locally: + + +Open a new terminal window or tab on your local computer. + + +Navigate to the root directory for your project, if necessary. + + +You should now have two terminals open. + + +You should have the project directory as your current working directory. + + + + +Start the Internet Computer network on your local computer by running the following command: +dfx start +After you start the local network, the terminal displays messages about network operations. + + +Leave the terminal that displays network operations open and switch your focus to your original terminal where you created your new project. + + +
+
+Register, build, and deploy the application +After you connect to the Internet Computer network running locally in your development environment, you can register, build, and deploy your application locally. +To deploy the application locally: + + +Check that you are still in the root directory for your project, if needed. + + +Register, build, and deploy your application by running the following command: +dfx deploy +The dfx deploy command output displays information about the operations it performs. + + +
+
+Verify calculator functions on the canister +You now have a program deployed as a canister on your local Internet Computer network. +You can test the program by using dfx canister call commands. +To test the program you have deployed: + + +Use the dfx canister call command to call the calc canister add function and pass it the input argument 10 by running the following command: +dfx canister call calc add '(10)' +When you pass an argument enclosed by the single quotation marks and parentheses,the interface description language (IDL) parses the argument type, so you don’t need to specify the argument type manually. +Verify that the command returns the value expected for the add function. +For example, the program displays output similar to the following: +(10) + + +Call the mul function and pass it the input argument 3 by running the following command: +dfx canister call calc mul '(3)' +Verify that the command returns the value expected for the mul function. +For example, the program displays output similar to the following: +(30) + + +Call the sub function and pass it the input argument 5 of type number by running the following command: +dfx canister call calc sub '(5)' +Verify that the command returns the value expected for the sub function. +For example, the program displays output similar to the following: +(25) + + +Call the div function and pass it the input argument 5 by running the following command: +dfx canister call calc div '(5)' +Verify that the command returns the value expected for the div function. +For example, the program displays output similar to the following: +(opt 5) +You might notice that the div function returns an optional result. +The program makes the result optional to enable the div function to return null in the case of a division-by-zero error. +Because the cell variable in this program is an integer, you can also call its functions and specify negative input values. +For example, you might run the following command: +dfx canister call calc mul '(-4)' +which returns: +(-20) + + +Call the clearall function and verify it resets the cell value to zero: +dfx canister call calc clearall +For example, the program displays output similar to the following: +(0) + + +Unresolved directive in calculator.adoc - include::example$candid-ui.adoc[] ++ + + + + +Calculator functions + +
+
+Stop the local network +After you finish experimenting with your program, you can stop the local Internet Computer network so that it doesn’t continue running in the background. +To stop the local network: + + +In the terminal that displays network operations, press Control-C to interrupt the local network process. + + +Stop the Internet Computer network by running the following command: +dfx stop + + +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/tutorials/counter-tutorial.xml b/modules/developers-guide/pages/tutorials/counter-tutorial.xml new file mode 100644 index 000000000..a98602e55 --- /dev/null +++ b/modules/developers-guide/pages/tutorials/counter-tutorial.xml @@ -0,0 +1,224 @@ + + + +
+ +Increment a natural number +2021-08-05 + +In this tutorial, you are going to write a program that creates a single actor and provides a few basic functions to increment a counter and illustrate persistence of a value. +For this tutorial, the actor is named Counter. +The program uses the currentValue variable to contain a natural number that represents the current value of the counter. +This program supports the following function calls: + + +The increment function call updates the current value, incrementing by 1 (no return value). + + +The get function call queries and returns the current value. + + +The set function call updates the current value to an arbitrary numeric value you specify as an argument. + + +This tutorial provides a simple example of how you can increment a counter by calling functions on a deployed canister. +By calling the function to increment a value multiple times, you can verify that the variable state—that is, the value of the variable between calls—persists. +
+Before you begin +Before starting the tutorial, verify the following: + + +You have downloaded and installed the {sdk-short-name} package as described in Download and install. + + +You have stopped any Internet Computer network processes running on the local +computer. + + +This tutorial takes approximately 20 minutes to complete. +
+
+Create a new project +To create a new project directory for this tutorial: + + +Open a terminal shell on your local computer, if you don’t already have one open. + + +Change to the folder you are using for your Internet Computer projects, if you are using one. + + +Create a new project by running the following command: +dfx new my_counter +The command creates a new my_counter project and Git repository for your project. + + +Change to your project directory by running the following command: +cd my_counter + + +
+
+Modify the default configuration +You have already seen that creating a new project adds a default dfx.json configuration file to your project directory. +In this tutorial, you will modify the default settings to use a different name for the main program in your project. +To modify the default dfx.json configuration file: + + +Open the dfx.json configuration file in a text editor and change the default main setting from main.mo to increment_counter.mo. +For example: +"main": "src/my_counter/increment_counter.mo", +For this tutorial, changing the name of the source file from main.mo to increment_counter.mo simply illustrates how the setting in the dfx.json configuration file determines the source file to be compiled. +In a more complex application, you might have multiple source files with dependencies that you need to manage using settings in the dfx.json configuration file. +In a scenario like that—with multiple canisters and programs defined in your dfx.json file—having multiple files all named main.mo might be confusing. +You can leave the rest of the default settings as they are. + + +Save your change and close the dfx.json file to continue. + + +Change the name of the main program file in the source code directory to match the name specified in the dfx.json configuration file by running the following command +mv src/my_counter/main.mo src/my_counter/increment_counter.mo + + +
+
+Modify the default program +So far, you have only changed the name of the main program for your project. +The next step is to modify the code in the src/my_counter/increment_counter.mo file to define an actor named Counter and implement the increment, get, and set functions. +To modify the default template source code: + + +Check that you are still in your project directory, if needed. + + +Open the src/my_counter/increment_counter.mo file in a text editor and delete the existing content. + + +Copy and paste the following sample code into the increment_counter.mo file: +Unresolved directive in counter-tutorial.adoc - include::example$counter.mo[] +Let’s take a closer look at this sample program: + + +You can see that the currentValue variable declaration in this example includes the stable keyword to indicate the state—the value that can be set, incremented, and retrieved—persists. +This keyword ensures that the value for the variable is unchanged when the program is upgraded. + + +The declaration for the currentValue variable also specifies that its type is a natural (Nat) number. + + +The program includes two public update methods—the increment and set functions—and one a query method, in this case, the get function. + + +For more information about stable and flexible variables, see Stable variables and upgrade methods in the Motoko Programming Language Guide. +For more information about the differences between a query and an update, see query calls in Canisters include both program and state. + + +Save your changes and close the file to continue. + + +
+
+Start the local network +Before you can build the my_counter project, you need to connect to the Internet Computer network either running locally in your development environment or running remotely on a subnet that you can access. +Starting the network locally requires a dfx.json file, so you should be sure you are in your project’s root directory. +For this tutorial, you should have two separate terminal shells, so that you can start and see network operations in one terminal and manage your project in another. +To start the network locally: + + +Open a new terminal window or tab on your local computer. + + +Navigate to the root directory for your project, if necessary. + + +You should now have two terminals open. + + +You should have the project directory as your current working directory. + + + + +Start the Internet Computer network on your local computer by running the following command: +dfx start +After you start the local network, the terminal displays messages about network operations. + + +Leave the terminal that displays network operations open and switch your focus to your original terminal where you created your new project. + + +
+
+Register, build, and deploy the application +After you connect to the Internet Computer network running locally in your development environment, you can register, build, and deploy your application locally. +To deploy the application locally: + + +Check that you are still in the root directory for your project, if needed. + + +Register, build, and deploy your application by running the following command: +dfx deploy +The dfx deploy command output displays information about the operations it performs. + + +
+
+Invoke methods on the deployed canister +After successfully deploying the canister, you can simulate an end-user invoking the methods provided by the canister. +For this tutorial, you invoke a get method to query the value of a counter, an increment method that increments the counter each time it is called, and a set method to pass an argument to update the counter to an arbitrary value you specify. +To test invoking methods on the deployed canister: + + +Run the following command to invoke the get function, which reads the current value of the currentValue variable on the deployed canister: +dfx canister call my_counter get +The command returns the current value of the currentValue variable as zero: +(0) + + +Run the following command to invoke the increment function to increment the value of the currentValue variable on the deployed canister by one: +dfx canister call my_counter increment +This command increments the value of the variable—changing its state—but does not return the result. + + +Rerun the following command to get the current value of the currentValue variable on the deployed canister: +dfx canister call my_counter get +The command returns the updated value of the currentValue variable as one: +(1) + + +Run additional commands to experiment with invoking other methods and using different values. +For example, try commands similar to the following to set and return the counter value: +dfx canister call my_counter set '(987)' +dfx canister call my_counter get +Returns the current value of 987. +dfx canister call my_counter increment +dfx canister call my_counter get +Returns the incremented value of 988. + + +Unresolved directive in counter-tutorial.adoc - include::example$candid-ui.adoc[] ++ + + + + +Counter functions + +
+
+Stop the local network +After you finish experimenting with your program, you can stop the local Internet Computer network so that it doesn’t continue running in the background. +To stop the local network: + + +In the terminal that displays network operations, press Control-C to interrupt the local network process. + + +Stop the Internet Computer network by running the following command: +dfx stop + + +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/tutorials/custom-frontend.xml b/modules/developers-guide/pages/tutorials/custom-frontend.xml new file mode 100644 index 000000000..3b4d741c9 --- /dev/null +++ b/modules/developers-guide/pages/tutorials/custom-frontend.xml @@ -0,0 +1,364 @@ + + + +
+ +Customize the front-end +2021-08-05 + +Now that you have a basic understanding of how to create, build, and deploy a simple program and are familiar with the default project files and sample front-end, you might want to start experimenting with different ways to customize the front-end user experience for your project. +This tutorial illustrates using a simple React framework to create a new front-end for the default sample program and guides you through some basic modifications to customize the interface displayed. +Later tutorials expand on the techniques introduced here, but if you already know how to use CSS, HTML, JavaScript, and React or other frameworks to build your user interface, you can skip this tutorial. + +This tutorial illustrates using the React framework to manage the Document Object Model (DOM) for your canister. +Because React has its own custom DOM syntax, you need to modify the webpack configuration to compile the front-end code, which is written in JSX. For more information about learning to use React and JSX, see Getting started on the React website. + +
+Before you begin +Before starting the tutorial, verify the following: + + +You have node.js installed for front-end development and can install packages using npm install in your project. +For information about installing node for your local operating system and package manager, see the Node website. + + +You have downloaded and installed the {sdk-short-name} package as described in Download and install. + + +You have installed the Visual Studio Code plugin for Motoko as described in Install the language editor plug-in if you are using Visual Studio Code as your IDE. + + +You have stopped any Internet Computer network processes running on the local +computer. + + + +Because of significant changes to the handling of HTTP requests and front-end assets, this tutorial requires you to use the {sdk-short-name} version 0.7.0 or later. For an overview of what’s changed, see this article. + +This tutorial takes approximately 30 minutes to complete. +
+
+Create a new project +To create a new project directory for your custom front-end application: + + +Open a terminal shell on your local computer, if you don’t already have one open. + + +Change to the folder you are using for your Internet Computer projects, if you are using one. + + +Check that you have node.js installed locally by running the following commands: +which node +which npm +If you don’t have node.js installed, you should download and install it before continuing to the next step. +For information about installing node for your local operating system and package manager, see the Node website. + + +Create a new project by running the following command: +dfx new custom_greeting +The dfx new custom_greeting command creates a new custom_greeting project. + + +Change to your project directory by running the following command: +cd custom_greeting + + +
+
+Install the React framework +If you’ve never used React before, you might want to explore the Intro to React tutorial or the React website before editing the front-end code. +To install required framework modules: + + +Install the React module by running the following command: +npm install --save react react-dom + + +Install the required TypeScript language compiler loader by running the following command: +npm install --save-dev typescript ts-loader + +As an alternative to installing these modules, you can edit the default package.json file to add dependencies for your project. + +Unresolved directive in custom-frontend.adoc - include::example$custom-frontend-package.json[] + + +
+
+Review the default configuration +Before we make any changes to use React for this tutorial, let’s review the default front-end settings in the dfx.json configuration file for your project. +To review the default dfx.json configuration file: + + +Open the dfx.json configuration file in a text editor. + + +Notice that the canisters key includes settings for a custom_greeting_assets canister. +{ + "canisters": { + ... + + "custom_greeting_assets": { + "dependencies": [ + "custom_greeting" + ], + "frontend": { + "entrypoint": "src/custom_greeting_assets/src/index.html" + }, + "source": [ + "src/custom_greeting_assets/assets", + "dist/custom_greeting_assets/" + ], + "type": "assets" + } + } +} +Let’s take a look at the settings in this section. + + +Front-end assets for your project are compiled into their own canister, in this case, a canister named custom_greeting_assets. + + +The assets canister has a default dependency on the main canister for the project. + + +The frontend.entrypoint setting specifies the path to a file—in this case, the index.html file—to use as your application entry point. +If you had a different starting point—for example, a custom first-page.html file—you would modify this setting. + + +The source settings specify the path to your src and dist directories. The src setting specifies the directory to use for static assets that will be included in your assets canister when you build your project. +If you have custom cascading stylesheet (CSS) or JavaScript files, you would include them in the folder specified by this path. +After building the project, the project assets are served from the directory specified by the dist setting. + + +The type setting specifies that the custom_greeting_assets is an asset canister rather than a program canister. + + +For this tutorial, we are going to add React JavaScript in an index.jsx file, but that won’t require any changes to the default settings in the dfx.json file. + + +Close the dfx.json file to continue. + + +
+
+Review the default front-end files +For this tutorial, you are going to use the default main.mo program and only manipulate the application by modifying the front-end. +Before you make any changes, though, let’s take a look at what’s in the default front-end files for a project. +To review the default front-end files: + + +Open the src/custom_greeting_assets/src/index.html file in a text editor. +This template file is the default front-end entry point for the application as specified by the frontend.entrypoint setting in the dfx.json file. +This file contains standard HTML with references to a CSS file and an image that are located in the src/custom_greeting_assets/assets directory. +The default index.html file also includes standard HTML syntax for displaying an input field for the name argument and a clickable button. +This is the same default front-end you saw in Viewing the default front-end. + + +Open the src/custom_greeting_assets/src/index.js file in a text editor. +import { custom_greeting } from "../../declarations/custom_greeting"; + +document.getElementById("clickMeBtn").addEventListener("click", async () => { + const name = document.getElementById("name").value.toString(); + // Interact with custom_greeting actor, calling the greet method + const greeting = await custom_greeting.greet(name); + + document.getElementById("greeting").innerText = greeting; +}); + + +The import statement points to an actor that will allow us to make calls to our custom_greeting canister from "../declarations" + + +The declarations haven’t been created yet, but we will come back to that. + + + + +Close the index.js file to continue. + + +
+
+Modify the front-end files +You are now ready to create a new front-end for the default program. +To prepare the front-end files: + + +Open the webpack configuration file (webpack.config.js) in a text editor. + + +Modify the front-end entry to replace the default index.html with index.jsx. +entry: { + // The frontend.entrypoint points to the HTML file for this build, so we need + // to replace the extension to `.js`. + index: path.join(__dirname, asset_entry).replace(/\.html$/, ".jsx"), +}, + + +Add the following module key above the plugins section: +module: { + rules: [ + { test: /\.(js|ts)x?$/, loader: "ts-loader" } + ] +}, +This setting enables the program to use the ts-loader compiler for a React JavaScript index.jsx file. +Note that there’s a commented section in the default webpack.config.js file that you can modify to add the module key. + + +Create a new file named tsconfig.json in the root directory for your project. + + +Open the tsconfig.json file in a text editor, then copy and paste the following into the file: +Unresolved directive in custom-frontend.adoc - include::example$sample-tsconfig.json[] + + +Save your changes and close the tsconfig.json file to continue. + + +Open the default src/custom_greeting_assets/src/index.js file in a text editor and delete lines 2 to 9. + + +Copy and paste the following sample code into the index.js file: +Unresolved directive in custom-frontend.adoc - include::example$react-index.jsx[] + + +Rename the modified index.js file as index.jsx by running the following command: +mv src/custom_greeting_assets/src/index.js src/custom_greeting_assets/src/index.jsx + + +Open the default src/custom_greeting_assets/src/index.html file in a text editor, then replace the body contents with <div id="app"></div>. +For example: +<!doctype html> +<html lang="en"> + <head> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width"> + <title>custom_greeting</title> + <base href="/"> + <link type="text/css" rel="stylesheet" href="main.css" /> + </head> + <body> + <div id="app"></div> + </body> +</html> + + +
+
+Start the local network +Before you can build the custom_greeting project, you need to connect to the Internet Computer network either running locally in your development environment or running remotely on a subnet that you can access. +To start the network locally: + + +Open a new terminal window or tab on your local computer. + + +Navigate to the root directory for your project, if necessary. + + +Start the Internet Computer network on your local computer by running the following command: +dfx start --background +After the local Internet Computer network completes its startup operations, you can continue to the next step. + + +
+
+Register, build, and deploy the application +After you connect to the Internet Computer network running locally in your development environment, you can register, build, and deploy your application locally. +To deploy the application locally: + + +Check that you are still in the root directory for your project, if needed. + + +Register, build, and deploy your application by running the following command: +dfx deploy +The dfx deploy command output displays information about the operations it performs. + + +
+
+View the new front-end +You can now access the new front-end for the default program by entering the canister identifier for the assets canister in a browser. +To view the custom front-end: + + +Open a new tab or window of your terminal and run +npm start + + +Open a browser and navigate to http://localhost:8080. + + +Verify that you are prompted to type a greeting. +For example: + + + + +Sample front-end + + + +Replace Name in the input field with the text you want to display, then click Get Greeting to see the result. +For example: + + + + +Greeting result + + + +
+
+Revise the front-end and test your changes +After viewing the front-end, you might want to make some changes. +To modify the front-end: + + +Open the index.jsx file in a text editor and modify its style settings. +For example, you might want to change the font family and use a placeholder for the input field by making changes similar to the following: +Unresolved directive in custom-frontend.adoc - include::example$react-revised-index.jsx[] + + +Save the file and view the updated page in your browser. +For example: + + + + +Modified styles on your entry page + + + +Type a new message and see your new greeting. +For example: + + + + +Modified greeting result + + + +
+
+Stop the local network +After you finish experimenting with the front-end for your program, you can stop the local Internet Computer network so that it doesn’t continue running in the background. +To stop the local network: + + +In the terminal that displays the webpack development server, press Control-C to interrupt the dev-server. + + +In the terminal that displays network operations, press Control-C to interrupt the local network process. + + +Stop the Internet Computer network by running the following command: +dfx stop + + +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/tutorials/define-an-actor.xml b/modules/developers-guide/pages/tutorials/define-an-actor.xml new file mode 100644 index 000000000..2e034eeb9 --- /dev/null +++ b/modules/developers-guide/pages/tutorials/define-an-actor.xml @@ -0,0 +1,230 @@ + + + +
+ +Query using an actor +2021-08-05 + +In the Quick start, you had your first look at a simple program for the Internet Computer involving an actor object and asynchronous messaging. +As the next step in learning to write programs that take advantage of actor-based messaging, this tutorial illustrates how to modify a traditional Hello, World! program to define an actor, then deploy and test your program on a local network. +
+Before you begin +Before starting the tutorial, verify the following: + + +You have downloaded and installed the {sdk-short-name} package as described in Download and install. + + +You have stopped any Internet Computer network processes running on the local computer. + + +This tutorial takes approximately 20 minutes to complete. +
+
+Create a new project +To create a new project for this tutorial: + + +Open a terminal shell on your local computer, if you don’t already +have one open. + + +Change to the folder you are using for your Internet Computer projects, if you are using one. + + +Create a new project by running the following command: +dfx new actor_hello + + +Change to your project directory by running the following command: +cd actor_hello + + +
+
+Modify the default configuration +In the Exploring the default project tutorial, you saw that creating a new project adds a default dfx.json configuration file to your project directory. +In this tutorial, you need to modify a few of the default settings to reflect your project. +To modify the dfx.json configuration file: + + +Open the dfx.json configuration file in a text editor. + + +Check the default settings for the actor_hello project. + + +Notice that the names and paths to source and output files all use the actor_hello project name. +For example, the default canister name is actor_hello and the default path to the main program file is src/actor_hello/main.mo. +You can rename any of these files or directories. +If you make any changes, however, be sure that the names you use for your files and directories on the file system match the names you specify in the dfx.json configuration file. +If you plan to use the default directory and file names, no changes are necessary. + + +Remove all of the actor_hello_assets configuration settings from the file. +The sample program for this tutorial doesn’t use any front-end assets, so you can remove those settings from the configuration file. +For example, the configuration file looks like this after you remove the actor_hello_assets section: +Unresolved directive in define-an-actor.adoc - include::example$define-actor-dfx.json[] + + +Save your changes and close the file to continue. + + +
+
+Modify the default program +In the Exploring the default project tutorial, you saw that creating a new project creates a default src directory with a template main.mo file. +In this tutorial, you modify the template code to create a simple "Hello, World!" program that uses an actor. +To modify the default template source code: + + +Change to the source code directory for your project by running the following command: +cd src/actor_hello + + +Open the template main.mo file in a text editor and delete the existing content. +The next step is to write a program that prints a statement like the traditional "Hello, World!" sample program. +To compile the program for the Internet Computer, however, your program must include an actor object with a public function. + + +Copy and paste the following sample code into the main.mo file: +Unresolved directive in define-an-actor.adoc - include::example$actor_hello.mo[] +Let’s take a closer look at this simple program: + + +The program imports a Debug module to provide the print functionality. + + +The program uses the public query func to define a query method because, in this case, the actor_hello program doesn’t make any changes to the state of the canister or perform any operations that would update the data you are accessing. + + +For more information about using a query call, see query calls in Canisters include both program and state. + + +Save your changes and close the main.mo file. + + +
+
+Build the program with a local identifier +You are probably only going to use this simple program for some local testing. +Therefore, there’s no need to reserve a unique canister identifier on the Internet Computer network to hold the compiled output for the program. +In this scenario, you can compile the program without connecting to an Internet Computer network at all. +Instead, the dfx build command creates a local, hard-coded canister identifier for you to use. +You can use this local identifier while you are testing your program or any time you want to compile your program without starting the Internet Computer replica process locally or connecting to a replica on a remote subnet. +To build the program executable: + + +Navigate back to the root of your project directory. + + +Build the program with a locally-defined identifier by running the following command: +dfx build --check +The --check option enables you to build a project locally to verify that it compiles and to inspect the files produced. +Because the dfx build --check command only generates a temporary identifier, you should see output similar to the following: +Building canisters to check they build ok. Canister IDs might be hard coded. +Building canisters... +If the program compiles successfully, you can inspect the output in the default .dfx/local/canisters directory and .dfx/local/canisters/actor_hello/ subdirectory. +For example, you might use the tree command to review the files created: +tree .dfx/local/canisters +The command displays output similar to the following + + +.dfx/local/canisters +├── actor_hello +│   ├── actor_hello.d.ts +│   ├── actor_hello.did +│   ├── actor_hello.did.js +│   ├── actor_hello.js +│   └── actor_hello.wasm +└── idl + +2 directories, 5 files +
+
+Deploy the project +You cannot deploy the output from the dfx build --check command to any Internet Computer network. +If you wanted to deploy this project, you would need to do the following: + + +Connect to the Internet Computer network. + + +Register a network-specific canister identifier. + + +Deploy the canister. + + +Let’s consider these steps in a bit more detail. +Before you can deploy this project, you must connect to the Internet Computer network either running locally in your development environment or running remotely on a subnet that you can access. +After you connect to a local or remote network, you must also generate a unique, network-specific canister identifier to replace your locally-defined identifier. +To see the steps involved for yourself, let’s deploy the project locally. +To deploy this project locally: + + +Open a terminal and navigate to your project directory, if needed. + + +Start the Internet Computer network on your local computer by running the following command: +dfx start --background +For this tutorial, you can use the --background option to start the Internet Computer network as background processes. +With this option, you can continue to the next step without opening another terminal shell on your local computer. + + +Generate a new canister identifier for your project on the local Internet Computer network by running the following command: +dfx canister create actor_hello +You should see output similar to the following: +Creating a wallet canister on the local network. +The wallet canister on the "local" network for user "pubs-id" is "rwlgt-iiaaa-aaaaa-aaaaa-cai" +Creating canister "actor_hello"... +"actor_hello" canister created with canister id: "rrkah-fqaaa-aaaaa-aaaaq-cai" +The dfx canister create command also stores the network-specific canister identifier in a canister_ids.json file in the .dfx/local directory. +For example: +{ + "actor_hello": { + "local": "rrkah-fqaaa-aaaaa-aaaaq-cai" + } +} + + +Deploy your actor_hello project on the local network by running the following command: +dfx canister install actor_hello +The command displays output similar to the following: +Installing code for canister actor_hello, with canister_id rrkah-fqaaa-aaaaa-aaaaq-cai + + +
+
+Query the canister +You now have a program deployed as a canister on your local Internet Computer network and can test your program by using the dfx canister call command. +To test the program you have deployed on the local network: + + +Use dfx canister call to call the hello function by running the following command: +dfx canister call actor_hello hello + + +Verify that the command returns the text specified for the hello function along with a checkpoint message in the terminal running the local network process. +For example, the program displays "Hello, World from DFINITY" in output similar to the following: +[Canister rrkah-fqaaa-aaaaa-aaaaq-cai] Hello, World from DFINITY +Note that if you are running the Internet Computer network in a separate terminal instead of in the background, the "Hello, World from DFINITY" message is displayed in the terminal that displays network activity. + + +
+
+Stop the local network +After you finish experimenting with your program, you can stop the local Internet Computer network so that it doesn’t continue running in the background. +To stop the local network: + + +In the terminal that displays network operations, press Control-C to interrupt the local network process. + + +Stop the Internet Computer network by running the following command: +dfx stop + + +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/tutorials/explore-templates.xml b/modules/developers-guide/pages/tutorials/explore-templates.xml new file mode 100644 index 000000000..e266e4bf4 --- /dev/null +++ b/modules/developers-guide/pages/tutorials/explore-templates.xml @@ -0,0 +1,434 @@ + + + +
+ +Explore the default project +2021-08-05 + +If you started your tour of the {sdk-long-name} with the Quick start, you have already seen the basic work flow for creating applications that run on the Internet Computer. +Now, let’s take a closer look at that work flow by exploring the default files and folders that are added to your workspace when you create a new project. +As a preview, the following diagram illustrates the development work flow when running the Internet Computer locally on you computer. + + + + +Development work flow + +
+Before you begin +Before you start this tutorial, verify the following: + + +You have an internet connection and access to a shell terminal on your local macOS or Linux computer. + + +You have node.js installed if you want to include the default template files for front-end development in your project. + + +You have downloaded and installed the {sdk-short-name} package as described in Download and install. + + +You have installed the Visual Studio Code plugin for Motoko as described in Install the language editor plug-in if you are using Visual Studio Code as your IDE. + + +You have stopped any Internet Computer network processes running on the local computer. + + +This tutorial takes approximately 20 minutes to complete. +
+
+Create a new project +As discussed in the Quick start, applications for the Internet Computer start as projects that you create. You can create projects using the dfx executable command-line interface (CLI). +To take a closer look at the files and folders that are included in a project by default, let’s create a new project to work with. +To create a new project: + + +Open a terminal shell on your local computer, if you don’t already have one open. + + +Navigate to the folder you are using for your Internet Computer projects, if you are using a separate working folder. + + +Create a new project by running the following command: +dfx new explore_hello +The dfx new explore_hello command creates a new explore_hello +project, including a default project directory structure under the new +project name and a new Git repository for your project. +If you have node.js installed locally, creating a new project also adds some template front-end code and dependencies. +To ensure that project names are valid when used in JavaScript, Motoko, and other contexts, you should only use alphanumeric characters and underscores. +You cannot include dashes or any special characters. + + +View the default directory structure by running the following command: +ls -l explore_hello +By default, the project directory structure includes at least one source subdirectory, a template README.md file, and a default dfx.json configuration file. +Depending on whether you have node.js installed, your project directory might include some or all of the following files: +explore_hello/ +├── README.md # default project documentation +├── dfx.json # project configuration file +├── node_modules # libraries for front-end development +├── package-lock.json +├── package.json +├── src # source files directory +│   ├── explore_hello +│   │   └── main.mo +│   └── explore_hello_assets +│   ├── assets +│   │   ├── logo.png +│   │   ├── main.css +│   │   └── sample-asset.txt +│   └── src +│   ├── index.html +│   └── index.js +└── webpack.config.js +At a minimum, the default project directory includes the following folders and files: + + +A default README file for documenting your project in the repository. + + +A default dfx.json configuration file to set configurable options for your project. + + +A default src directory for all of the source files required by your application. + + +The default src directory includes a template main.mo file that you can modify or replace to include your core programming logic. +Because this tutorial focuses on the basics of getting started, you are only going to use the main.mo file. +If you have node.js installed, your project directory includes additional files and directories that you can use to define the front-end interface for your application. +Front-end development and the template files in the assets folder are discussed a little later. + + +
+
+Review the default configuration +By default, creating a new project adds some template files to your project directory. +You can edit these template files to customize the configuration settings for your project and to include your own code to speed up the development cycle. +To review the default configuration file for your project: + + +Open a terminal shell on your local computer, if you don’t already have one open. + + +Change to your project directory by running the following command: +cd explore_hello + + +Open the dfx.json configuration file in a text editor to review the default settings. +For example: +Unresolved directive in explore-templates.adoc - include::example$sample-explore-dfx.json[] +Let’s take a look at a few of the default settings. + + +The canisters section specifies the name of the WebAssembly module for your explore_hello project is explore_hello. + + +The canisters.explore_hello key specifies that the main program to be compiled is located in the path specified by the main setting, in this case, src/explore_hello/main.mo and the type setting indicates that this is a motoko program. + + +The canisters.explore_hello_assets key specifies configuration details about front-end assets for this project. Let’s skip those for now. + + +The dfx setting is used to identify the version of the software used to create the project. + + +The networks section specifies information about the networks to which you connect. The default settings bind the local Internet Computer network to the local host address 127.0.0.1 and port 8000. +If you have access to other Internet Computer network providers, the networks section can include network aliases and URLs for connecting to those providers. + + +You can leave the default settings as they are. + + +Close the dfx.json file to continue. + + +
+
+Review the default program code +New projects always include a template main.mo source code file. +You can edit this file to include your own code to speed up the development cycle. +Let’s take a look at the sample program in the default main.mo template file as a starting point for creating simple program using the Motoko programming language. +To review the default sample program for your project: + + +Check that you are still in your project directory by running the following command: +pwd + + +Open the src/explore_hello/main.mo file in a text editor and review the code in the template: +actor { + public func greet(name : Text) : async Text { + return "Hello, " # name # "!"; + }; +}; +Let’s take a look at a few key elements of this program: + + +You might notice that this sample code defines an actor instead of a main function, which some programming languages require. +For Motoko, the main function is implicit in the file itself. + + +Although the traditional "Hello, World!" program illustrates how you can print a string using a print or println function, that traditional program would not represent a typical use case for Motoko programs that run on the Internet Computer. + + +Instead of a print function, this sample program defines an actor with a public greet function that takes a name argument with a type of Text. + + +The program then uses the async keyword to indicate that the program returns an asynchronous message consisting of a concatenated text string constructed using "Hello, ", the # operator, the name argument, and "!". + + +We’ll explore code that uses actor objects and asynchronous message handling more a little later. +For now, you can continue to the next section. + + +Close the main.mo file to continue. + + +
+
+Start the local network +Before you can build the default project, you need to connect to the Internet Computer network either running locally in your development environment or running remotely on a subnet that you can access. +Starting the network locally requires a dfx.json file, so you should be sure you are in your project’s root directory. +For this tutorial, you should have two separate terminal shells, so that you can start and see network operations in one terminal and manage your project in another. +To start the network locally: + + +Open a new terminal window or a new terminal tab on your local computer. + + +Navigate to the root directory for your project, if necessary. + + +You should now have two terminals open. + + +You should have the project directory as your current working directory. + + + + +Start the Internet Computer network on your local computer by running the following command: +dfx start +Depending on your platform and local security settings, you might see a warning displayed. +If you are prompted to allow or deny incoming network connections, click Allow. +After you start the local network, you have one terminal that displays messages about network operations and another for performing project-related tasks. + + +Leave the terminal that displays network operations open and switch your focus to the terminal where you created your new project. + + +
+
+Register canister identifiers +After you connect to the Internet Computer network running locally in your development environment, you can register with the network to generate unique, network-specific canister identifiers for your project. +In the Quick start tutorial, this step was performed as part of the dfx deploy command work flow. +This tutorial demonstrates how to perform each of the operations independently. +To register canister identifiers for the local network: + + +Check that you are still in your project directory, if needed. + + +Register unique canister identifiers for the canisters in the project by running the following command: +dfx canister create --all +The command displays the network-specific canister identifiers for the canisters defined in the dfx.json configuration file. +Creating a wallet canister on the local network. +The wallet canister on the "local" network for user "pubs-id" is "rwlgt-iiaaa-aaaaa-aaaaa-cai" +Creating canister "explore_hello"... +"explore_hello" canister created with canister id: "rrkah-fqaaa-aaaaa-aaaaq-cai" +Creating canister "explore_hello_assets"... +"explore_hello_assets" canister created with canister id: "ryjl3-tyaaa-aaaaa-aaaba-cai" +Because you are connected to the Internet Computer network running locally, these canister identifiers are only valid locally and are stored for the project in the .dfx/local/canister_ids.json file. +For example: +{ + "explore_hello": { + "local": "rrkah-fqaaa-aaaaa-aaaaq-cai" + }, + "explore_hello_assets": { + "local": "ryjl3-tyaaa-aaaaa-aaaba-cai" + } +} + + +
+
+Build the program +Now that you have explored the default configuration settings and program code and have started the Internet Computer network, let’s compile the default program into an executable WebAssembly module. +To build the program executable: + + +In the terminal shell on your local computer, navigate to your explore_hello project directory. +You must run the dfx build command from within the project directory structure. + + +Build the executable canister by running the following command: +dfx build +You should see output similar to the following: +Building canisters... +Building frontend... +Because you are connected to the Internet Computer network running locally, the dfx build command adds the canisters directory under the .dfx/local/ directory for the project. + + +Verify that the .dfx/local/canisters/explore_hello directory created by the dfx build command contains the WebAssembly and related application files by running the following command. +ls -l .dfx/local/canisters/explore_hello/ +For example, the command returns output similar to the following: +-rw-r--r-- 1 pubs staff 178 Apr 6 14:25 explore_hello.d.ts +-rw-r--r-- 1 pubs staff 41 Apr 6 14:25 explore_hello.did +-rw-r--r-- 1 pubs staff 155 Apr 6 14:25 explore_hello.did.js +-rw-r--r-- 1 pubs staff 142 Apr 6 14:25 explore_hello.js +-rw-r--r-- 1 pubs staff 157613 Apr 6 14:25 explore_hello.wasm +The canisters/explore_hello directory contains the following key files: + + +The explore_hello.did file contains an interface description for your main program. + + +The explore_hello.did.js file contains a JavaScript representation of the canister interface for the functions in your program. + + +The explore_hello.js file contains a JavaScript representation of the canister interface for your program. + + +The explore_hello.wasm file contains the compiled WebAssembly for the assets used in your project. + + +The canisters/explore_hello_assets directory contains similar files to describe the front-end assets associated with your project. +In addition to the files in the canisters/explore_hello and the canisters/explore_hello_assets directories, the dfx build command creates an idl directory. + + +Verify that a new folder has been created, src/declarations. +This folder will include copies of the folders from .dfx/local, except for the wasm. They do not contain any secrets, and we recommend committing these files along with the rest of your source code. + + +
+
+Deploy the project locally +You’ve seen that the dfx build command creates several artifacts in a canisters directory for your project. +The WebAssembly modules and the canister_manifest.json file are required for your program to be deployed on the Internet Computer network. +To deploy locally: + + +In a terminal shell on your local computer, navigate to your explore_hello project directory. + + +Deploy your explore_hello project on the local network by running the following command: +dfx canister install --all +The command displays output similar to the following: +Installing code for canister explore_hello, with canister_id rrkah-fqaaa-aaaaa-aaaaq-cai +Installing code for canister explore_hello_assets, with canister_id ryjl3-tyaaa-aaaaa-aaaba-cai +Authorizing our identity (pubs-id) to the asset canister... +Uploading assets to asset canister... + /index.html 1/1 (480 bytes) + /index.js 1/1 (296836 bytes) + /main.css 1/1 (484 bytes) + /sample-asset.txt 1/1 (24 bytes) + /logo.png 1/1 (25397 bytes) + /index.js.map 1/1 (964679 bytes) + /index.js.LICENSE.txt 1/1 (499 bytes) + + +Run the dfx canister call command and specify the program and function to call by running the following command: +dfx canister call explore_hello greet '("everyone": text)' +This command specifies: + + +explore_hello as the name of the canister or application service you want to call. + + +greet as the specific method or function you want to call. + + +everyone as the argument to pass to the greet function. + + + + +Verify the command displays the return value of the greet function. +For example: +("Hello, everyone!") + + +
+
+View the default front-end +If you have node.js installed in your development environment, your project includes a simple front-end example that uses a template index.js JavaScript file for accessing the explore_hello program in a browser. +To explore the default front-end template: + + +Open a terminal shell on your local computer, if you don’t already have one open, and navigate to your explore_hello project directory. + + +Open the src/explore_hello_assets/src/index.js file in a text editor and review the code in the template script: +import { explore_hello } from "../../declarations/explore_hello"; + +document.getElementById("clickMeBtn").addEventListener("click", async () => { + const name = document.getElementById("name").value.toString(); + // Interact with explore_hello actor, calling the greet method + const greeting = await explore_hello.greet(name); + + document.getElementById("greeting").innerText = greeting; +}); +The template index.js imports an explore_hello agent from our newly created declarations directory. The agent is automatically configured to interact with the interface we created in Main.mo, and makes calls to our Canister using an AnonymousIdentity when the user clicks the greeting button. +This file works in conjunction with the template index.html file to display an HTML page with an image asset, input field, and button for the greet function. + + +Close the index.js file to continue. + + +View the front-end assets created for the project by running following command: +ls -l .dfx/local/canisters/explore_hello_assets/ +The command displays output similar to the following: +drwxr-xr-x 9 pubs staff 288 Apr 6 14:25 assets +-r--r--r-- 1 pubs staff 2931 Dec 31 1969 assetstorage.did +-r--r--r-- 1 pubs staff 265823 Dec 31 1969 assetstorage.wasm +-rw-r--r-- 1 pubs staff 3651 Apr 6 14:25 explore_hello_assets.d.ts +-rw-rw-rw- 1 pubs staff 2931 Dec 31 1969 explore_hello_assets.did +-rw-r--r-- 1 pubs staff 4236 Apr 6 14:25 explore_hello_assets.did.js +-rw-r--r-- 1 pubs staff 149 Apr 6 14:25 explore_hello_assets.js +-rw-rw-rw- 1 pubs staff 265823 Dec 31 1969 explore_hello_assets.wasm +These files were generated automatically by the dfx build command using node modules and the template index.js file. + + +Start a development server with npm start. + + +Open a browser and navigate to the local network address and port number—+127.0.0.1:8080 + + +Verify that you see the HTML page for the sample application. +For example: + + + + +Sample HTML entry page + + + +Type a greeting, then click Click Me to return the greeting. +For example: + + + + +Return the name argument + + + +
+
+Stop the local network +After you finish experimenting with your program, you can stop the local Internet Computer network so that it doesn’t continue running in the background. +To stop the local network: + + +In the terminal that displays network operations, press Control-C to interrupt the local network process. + + +Stop the Internet Computer network by running the following command: +dfx stop + + +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/tutorials/hello-location.xml b/modules/developers-guide/pages/tutorials/hello-location.xml new file mode 100644 index 000000000..b0caa7d30 --- /dev/null +++ b/modules/developers-guide/pages/tutorials/hello-location.xml @@ -0,0 +1,241 @@ + + + +
+ +Pass text arguments +2021-08-05 + +This tutorial provides a simple variation on the default program that lets you pass a single text argument to a single actor, compile the code to create a canister, then retrieve the argument. +This tutorial illustrates how to pass arguments on the command-line in a terminal using the Candid interface description language (IDL) and how to modify the program to allow it to accept more than one value for the text argument. +
+Before you begin +Before you start this tutorial, verify the following: + + +You have downloaded and installed the {sdk-short-name} package as described in Download and install. + + +You have stopped any Internet Computer network processes running on the local +computer. + + +This tutorial takes approximately 20 minutes to complete. +
+
+Create a new project +To create a new project for this tutorial: + + +Open a terminal shell on your local computer, if you don’t already have one open. + + +Change to the folder you are using for your Internet Computer projects, if you are using one. + + +Create a new project by running the following command: +dfx new location_hello + + +Change to your project directory by running the following command: +cd location_hello + + +
+
+Modify the default configuration +In the Explore the default project tutorial, you saw that creating a new project adds a default dfx.json configuration file to your project directory. +You should always review the default settings in the file to verify the information accurately reflects the project settings you want to use. +For this tutorial, you’ll modify the default configuration to remove settings that aren’t used. +To modify settings in the dfx.json configuration file: + + +Open the dfx.json configuration file in a text editor. + + +Check the default settings for the location_hello project. + + +Remove all of the unnecessary configuration settings. +Because this tutorial does not involve creating any front-end assets, you can remove all of the location_hello_assets configuration settings from the file. + + +Save your changes and close the file to continue. + + +
+
+Modify the default program +In the Explore the default project tutorial, you saw that creating a new project creates a default src directory with a template main.mo file. +To modify the default template source code: + + +Open the src/location_hello/main.mo source code file in a text editor. + + +Modify the default source code to replace the greet function with a location function and the name argument with a city argument. +For example: +Unresolved directive in hello-location.adoc - include::example$location_hello.mo[] + + +Save your changes and close the file to continue. + + +
+
+Start the local network +Before you can build your project, you need to connect to the Internet Computer network either running locally in your development environment or running remotely on a subnet that you can access. +Starting the network locally requires a dfx.json file, so you should be sure you are in your project’s root directory. +For this tutorial, you should have two separate terminal shells, so that you can start and see network operations in one terminal and manage your project in another. +To start the local network: + + +Open a new terminal window or tab on your local computer. + + +Navigate to the root directory for your project, if necessary. + + +You should now have two terminals open. + + +You should have the project directory as your current working directory. + + + + +Start the Internet Computer network on your local computer by running the following command: +dfx start +If you are prompted to allow or deny incoming network connections, click Allow. + + +Leave the terminal that displays network operations open and switch your focus to your original terminal where you created your project. + + +
+
+Register, build, and deploy the application +After you connect to the Internet Computer network running locally in your development environment, you can register, build, and deploy your application locally. +To deploy the application locally: + + +Check that you are still in the root directory for your project, if needed. + + +Register, build, and deploy your application by running the following command: +dfx deploy +The dfx deploy command output displays information about the operations it performs. + + +
+
+Pass a text argument +You now have a program deployed as a canister on your local Internet Computer network and can test your program by using dfx canister call commands. +To test the program you have deployed locally: + + +Call the location method in the program and pass your city argument of type text by running the following command: +dfx canister call location_hello location "San Francisco" +Because the argument in this case includes a space between San and Francisco, you need to enclose the argument in quotes. +The command displays output similar to the following: +("Hello, San Francisco!") +If the argument did not contain a space that required enclosing the text inside of quotation marks, you could allow the Candid interface description language to infer the data type like this: +dfx canister call location_hello location Paris +Candid infers the data type as Text and returns the output from your program as text like this: +("Hello, Paris!") + + +Call the location method in the program and pass your city argument explicitly using the Candid interface description language syntax for Text arguments: +dfx canister call location_hello location '("San Francisco and Paris")' +The command displays output similar to the following: +("Hello, San Francisco and Paris!") +Because your program only accepts a single text argument, specifying multiple strings returns only the first argument. +For example, if you try this command: +dfx canister call location_hello location '("San Francisco","Paris","Rome")' +Only the first argument—("Hello, San Francisco!")—is returned. + + +
+
+Revise the source code in your program +To extend what you have learned in this tutorial, you might want to try modifying the source code to return different results. +For example, you might want to modify the location function to return multiple city names. +To experiment with modifying the source code for this tutorial: + + +Open the dfx.json configuration file in a text editor and change the default location_hello settings to favorite_cities. +For this step, you should modify both the canister name and the path to the main program for the canister to use favorite_cities. + + +Save your changes and close the dfx.json file to continue. + + +Copy the location_hello source file directory to match the name specified in the dfx.json configuration file by running the following command: +cp -r src/location_hello src/favorite_cities + + +Open the src/favorite_cities/main.mo file in a text editor. + + +Copy and paste the following code sample to replace the location function with two new functions. +For example: +Unresolved directive in hello-location.adoc - include::example$favorite_cities.mo[] +You might notice that Text in this code example is enclosed by square ([ ]) brackets. By itself, Text represents a collection of UTF-8 characters. +The square brackets around a type indicate that it is an array of that type. +In this context, therefore, [Text] indicates an array of a collection of UTF-8 characters, enabling the program to accept and return multiple text strings. +The code sample also uses the basic format of an apply operation for the array, which can be abstracted as: +public func apply<A, B>(fs : [A -> B], xs : [A]) : [B] { + var ys : [B] = []; + for (f in fs.vals()) { + ys := append<B>(ys, map<A, B>(f, xs)); + }; + ys; +}; +For information about the functions that perform operations on arrays, see the description of the Array module in the Motoko base library or the Motoko Programming Language Reference. +For another example focused on the use of arrays, see Quicksort in the examples repository. + + +Register, build, and deploy the application by running the following command: +dfx deploy + + +Call the location method in the program and pass your city argument using the Candid interface description syntax by running the following command: +dfx canister call favorite_cities location '(vec {"San Francisco";"Paris";"Rome"})' +The command uses the Candid interface description syntax (vec { val1; val2; val3; }) to return a vector of values. +For more information about the Candid interface description language, see the Candid language guide. +This command displays output similar to the following: +("Hello, from ["San Francisco", "Paris", "Rome"]!") + + +Call the location_pretty method in the program and pass your city argument using the interface description syntax by running the following command: +dfx canister call favorite_cities location_pretty '(vec {"San Francisco";"Paris";"Rome"})' +The command displays output similar to the following: +("Hello from San Francisco, Paris, Rome, bon voyage!") + + +Unresolved directive in hello-location.adoc - include::example$candid-ui.adoc[] ++ +In this example, each function accepts an array of text strings. Therefore, you first select the length of the array, then set values for each item before clicking Call. ++ + + + + +Specifying an array + +
+
+Stop the local network +After you finish experimenting with your program, you can stop the local Internet Computer network so that it doesn’t continue running in the background. +To stop the local network: + + +In the terminal that displays network operations, press Control-C to interrupt the local network process. + + +Stop the Internet Computer network by running the following command: +dfx stop + + +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/tutorials/intercanister-calls.xml b/modules/developers-guide/pages/tutorials/intercanister-calls.xml new file mode 100644 index 000000000..fdbefcc0f --- /dev/null +++ b/modules/developers-guide/pages/tutorials/intercanister-calls.xml @@ -0,0 +1,414 @@ + + + +
+ +Make inter-canister calls +2021-08-05 + +One of the most important features of the Internet Computer for developers is the ability to build, deploy, and call shared functions in one canister from a program in another canister. +This capability to make calls between canisters—also sometimes referred to as inter-canister calls—enables you to reuse and share functionality in multiple applications. +For example, you might want to create an application for professional networking, organizing community events, or hosting fundraising activities. +Each of these applications might have a social component that enables users to identify social relationships based on some criteria or shared interest, such as friends and family or current and former colleagues. +To address this social component, you might want to create a single canister for storing user relationships then write your professional networking, community organizing, or fundraising application to import and call functions that are defined in the canister for social connections. +You could then build additional applications to use the social connections canister or extend the features provided by the social connections canister to make it useful to an even broader community of other developers. +The Motoko-based LinkedUp sample application provides a simple implementation of an open professional network that demonstrates how to use inter-canister calls within a project. +The LinkedUp sample application is implemented using the following canisters: + + +The linkedup canister creates and stores basic profile information for a user, including work experience and educational background. + + +The connectd canister creates and stores a user’s connections. + + +The linkedup_assets canister stores the front-end assets—including the JavaScript, HTML, and CSS files—that define the user interface + + +
+Before you begin +Before building the sample application, verify the following: + + +You have downloaded and installed the {sdk-short-name} package as described in Download and install. + + +You have stopped any Internet Computer network processes running on the local +computer. + + +
+
+Download the demo +To experiment with inter-canister calls using the LinkedUp sample application: + + +Open a terminal shell and change to the folder you are using for your Internet Computer sample projects. + + +Clone the linkedup repository. +git clone https://github.com/dfinity/linkedup.git + + +Change to the local working directory for the linkedup repository. +cd linkedup + + +Install node modules by running the following command: +npm install +If necessary, fix any vulnerabilities found by running the following command: +npm audit fix + + +Open the dfx.json file in a text editor and verify the dfx setting has same the version number as the dfx executable you have installed. + + +
+
+Start the local network +Before you can build the linkedup project, you need to connect to the Internet Computer network either running locally in your development environment or running remotely on a subnet that you can access. +To start the network locally: + + +Open a new terminal window or tab on your local computer. + + +Navigate to the root directory for your project, if necessary. + + +Start the Internet Computer network on your local computer by running the following command: +dfx start --background +After the local Internet Computer network completes its startup operations, you can continue to the next step. + + +
+
+Register canister identifiers +After you connect to the Internet Computer network running locally in your development environment, you can register with the network to generate unique canister identifiers for your project. +To register canister identifiers for the local network: + + +Check that you are still in your project directory, if needed. + + +Register unique canister identifiers for the project by running the following command: +dfx canister create --all +The command displays the network-specific canister identifiers for the canisters defined in the dfx.json configuration file. +"connectd" canister created with canister id: "75hes-oqbaa-aaaaa-aaaaa-aaaaa-aaaaa-aaaaa-q" +"linkedup" canister created with canister id: "cxeji-wacaa-aaaaa-aaaaa-aaaaa-aaaaa-aaaaa-q" +"linkedup_assets" canister created with canister id: "7kncf-oidaa-aaaaa-aaaaa-aaaaa-aaaaa-aaaaa-q" +Keep in mind that because you are running the Internet Computer locally, these identifiers are only valid on the local network. +To deploy canisters on a remote network, you must connect to that network using the --network command-line option and a specific network name or address to register identifiers on that network. + + +
+
+Build and deploy the demo project +To build and deploy the LinkUp sample application, take the following steps: + + +Check that you are still in your project directory by running the pwd command, if necessary. + + +Build the LinkedUp canisters by running the following command: +dfx build + + +Deploy the project on the local network by running the following command: +dfx canister install --all +You should see canister identifiers for the connectd, linkedup and linkedup_assets canisters with a message similar to the following: +Installing code for canister connectd, with canister_id 75hes-oqbaa-aaaaa-aaaaa-aaaaa-aaaaa-aaaaa-q +Installing code for canister linkedup, with canister_id cxeji-wacaa-aaaaa-aaaaa-aaaaa-aaaaa-aaaaa-q +Installing code for canister linkedup_assets, with canister_id 7kncf-oidaa-aaaaa-aaaaa-aaaaa-aaaaa-aaaaa-q + + +Copy the linkedup_assets canister identifier returned by the dfx canister install command. +In this sample application, only the linkedup_assets canister includes the front-end assets used to access the application’s features. +To open the application in a browser, therefore, you need to specify the linkedup_assets canister identifier. + + +Open the linkedup_assets canister in your web browser. +For example, if binding to the default localhost address and port number, the URL looks similar to this: +http://127.0.0.1:8000/?canisterId=7kncf-oidaa-aaaaa-aaaaa-aaaaa-aaaaa-aaaaa-q + + +
+
+Create a profile and connections +To run through a demonstration of the LinkedUp sample application, take the following steps: + + +Open a browser tab or window. + + +Type the web server host name, port, and the canisterId keyword, then paste the linkedup_assets canister identifier as the URL to display. +127.0.0.1:8000/?canisterId=<ic-identifier-for-linkedup-assets> +The browser displays an introductory page. +A public-private key pair will be automatically generated to establish your identity for accessing the canister, so there’s no need to provide a user name and password or register an account to store your identity before using the service. + + +Click Login. +The browser displays an empty profile page. + + + + +linkedup empty maya + + + +Click Edit, type profile information, copy and paste the image address for an avatar photo, then click Submit. + + + + +linkedup edit maya + +After you click Submit, you have a profile with some work history that can be viewed. +For example: + + + + +linkedup profile maya + + + +
+Add another profile +At this point, there are no other profiles to search for or to add as connections. +To try out the Search and Connect features, you can: + + +Run a script that populates the sample application with some additional profiles. + + +Create a profile manually by opening a private window. + + +For this tutorial, you will create another profile manually. +To add a user profile with different identity: + + +At the top right of the browser window, click the appropriate icon to display the browser’s menu options. +For example, if you are using Google Chrome, click the vertical ellipse to display the More menu. + + +Click New Incognito Window if you are using Google Chrome or New Private Window if you are using Firefox to enable you to navigate to the canister without the user identity generated in your initial browser connection to the canister. + + +Copy and paste the URL from your first browser session into the private browsing window, then click Login. + + + + +linkedup incognito + +Notice that there’s no profile in the private browsing window but your original profile is still visible in your initial browser tab. + + +Click Edit, type profile information, copy and paste the image address for an avatar photo, then click Submit. + + + + +linkedup edit dylan + +After clicking Submit, you have a second profile with some work history that can be viewed. +For example: + + + + +linkedup profile dylan + + + +Type the first name or last name from the first profile you created—for example, if you created a profile for Maya Garcia, type Maya—then click Search. + + + + +linkedup search from dylan for maya + +The profile matching your search criteria is displayed. + + + + +linkedup search result + + + +Select the contact from the search results, wait for the Connect button to be displayed, then click Connect. + + + + +linkedup connect from dylan to maya + +When the connection request completes, the second profile displays the connection to the first profile. +For example: + + + + +linkedup connected to maya + + + +Return to the browser tab with your original profile. +If you want to create a connection between the original profile and the profile you created in the private browsing window, you can do so by repeating the search, select, and connect steps. + + +
+
+
+Explore the configuration file +Now that you have explored the basic features of the sample application, you have some context for exploring how the configuration settings and source files are used. +To explore the configuration file: + + +Change to the linkedup directory, then open the project’s dfx.json file. + + +Note that there are two main canisters defined—connectd and linkedup—each with a main.mo source file. + + +Note that the linkedup_assets canister specifies a frontend entry point of main.js and assets in the form of CSS and HTML files. + + +Note that the application uses the default server IP address and port number. + + +
+
+Explore the connectd source code +The source code for the social connections canister, connectd, is organized into the following files: + + +The digraph.mo file provides the functions to create a directed graph of vertices and edges to describe a user’s connections. + + +The main.mo contains the actor and key functions for defining the connections associated with a user profile that can be called by the LinkedUp sample application. + + +The types.mo file defines the custom type that maps a vertex to a user identity for use in the digraph and main program files. + + +
+
+Explore the linkedup source code +The source code for the professional profile with work history and educational background is organized into the following files: + + +The main.mo file contains the actor and key functions for the LinkedUp sample application. + + +The types.mo file defines the custom types that describe the user identity and profile fields that are imported and used in the main program file for the linkedup canister. + + +The utils.mo file provides helper functions. + + +
+Query and update operations +In working with the LinkedUp sample application, you might notice that some operations—such as viewing a profile or performing a search—returned results almost immediately. +Other operations—such as creating a profile or adding a connection—took a little longer. +These differences in performance illustrate the difference between using query and update calls in the linkedup canister. +For example, in the src/linkedup/main.mo file, the create and update functions are update calls that change the state of the canister, but the program uses query calls for the get and search functions to view or search for a profile: + // Profiles + + public shared(msg) func create(profile: NewProfile): async () { + directory.createOne(msg.caller, profile); + }; + + public shared(msg) func update(profile: Profile): async () { + if(Utils.hasAccess(msg.caller, profile)) { + directory.updateOne(profile.id, profile); + }; + }; + + public query func get(userId: UserId): async Profile { + Utils.getProfile(directory, userId) + }; + + public query func search(term: Text): async [Profile] { + directory.findBy(term) + }; +
+
+Interaction between the canisters +In this sample application, the linkedup canister leverages functions defined in the connectd canister. +This separation simplifies the code in each canister and illustrates how you can extend a project by calling common functions defined in one canister from one or more other canisters. +To make the public functions defined in one canister available in the another canister: + + +Add an import statement in the calling canister. +In this example, the public functions are defined in the connectd canister and are called by the linkedup canister. +Therefore, the src/linkedup/main.mo includes the following code: +// Make the Connectd app's public methods available locally +import Connectd "canister:connectd"; + + +Use the canister.function syntax to call public methods in the imported canister. +In this example, the linkedup canister calls the connect and getConnections function in the imported connectd canister. + + +You can see the code that enables interaction between the linkedup canister and the connectd canister in the main.mo source files. +For example, the src/connectd/main.mo defines the following functions: ++ +actor Connectd { + flexible var graph: Digraph.Digraph = Digraph.Digraph(); + + public func healthcheck(): async Bool { true }; + + public func connect(userA: Vertex, userB: Vertex): async () { + graph.addEdge(userA, userB); + }; + + public func getConnections(user: Vertex): async [Vertex] { + graph.getAdjacent(user) + }; + +}; +Because of the Import statement, the connectd functions are available to the linkedup canister and the src/linkedup/main.mo includes the following code: + // Connections + + public shared(msg) func connect(userId: UserId): async () { + // Call Connectd's public methods without an API + await Connectd.connect(msg.caller, userId); + }; + + public func getConnections(userId: UserId): async [Profile] { + let userIds = await Connectd.getConnections(userId); + directory.findMany(userIds) + }; + + public shared(msg) func isConnected(userId: UserId): async Bool { + let userIds = await Connectd.getConnections(msg.caller); + Utils.includes(userId, userIds) + }; + + // User Auth + + public shared query(msg) func getOwnId(): async UserId { msg.caller } + +}; +
+
+
+Stop the local network +After you finish experimenting with the linkedup program, you can stop the local Internet Computer network so that it doesn’t continue running in the background. +To stop the local network: + + +In the terminal that displays network operations, press Control-C to interrupt the local network process. + + +Stop the Internet Computer network by running the following command: +dfx stop + + +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/tutorials/multiple-actors.xml b/modules/developers-guide/pages/tutorials/multiple-actors.xml new file mode 100644 index 000000000..f945f011e --- /dev/null +++ b/modules/developers-guide/pages/tutorials/multiple-actors.xml @@ -0,0 +1,235 @@ + + + +
+ +Use multiple actors +2021-08-05 + +In this tutorial, you are going to create a project with multiple actors. +Currently, you can only define one actor in a Motoko file and a single actor is always compiled to a single canister. +You can, however, create projects that have multiple actors and can build multiple canisters from the same dfx.json configuration file. +For this tutorial, you are going to create separate program files for three actors in the same project. +This project defines the following unrelated actors: + + +The assistant actor provides functions to add and show tasks in a to-do list. +For simplicity, the code sample for this tutorial only includes the functions to add to-do items and to show the current list of to-do items that have been added. A more complete version of this program—with additional functions for marking items as complete and removing items from the list—is available in the examples repository as Simple to-do checklist. + + +The rock_paper_scissors actor provides a function for determining a winner in a hard-coded rock-paper-scissors contest. +This code sample illustrates the basic use of switch and case in a Motoko program with hard-coded players and choices. + + +The daemon actor provides mock functions for starting and stopping a daemon. +This code sample simply assigns a variable and prints messages for demonstration purposes. + + +
+Before you begin +Before starting the tutorial, verify the following: + + +You have downloaded and installed the {sdk-short-name} package as described in Download and install. + + +You have stopped any Internet Computer network processes running on the local +computer. + + +This tutorial takes approximately 20 minutes to complete. +
+
+Create a new project +To create a new project for this tutorial: + + +Open a terminal shell on your local computer, if you don’t already have one open. + + +Change to the folder you are using for your Internet Computer projects, if you are using one. + + +Create a new project by running the following command: +dfx new multiple_actors + + +Change to your project directory by running the following command: +cd multiple_actors + + +
+
+Modify the default configuration +You have already seen that creating a new project adds a default dfx.json configuration file to your project directory. +For this tutorial, you need to add sections to this file to specify the location of each program that defines an actor you want to build. +To modify the default dfx.json configuration file: + + +Open the dfx.json configuration file in a text editor, then change the default multiple_actors canister name and source directory to assistant. +For example, under the canisters key: + "assistant": { + "main": "src/assistant/main.mo", + "type": "motoko" + }, +Because you are going to add settings to this canisters section of the configuration file, you must also add a comma after the curly brace that encloses the location of the assistant main source code file and the canister type. + + +Remove the multiple_actors_assets section from the file. + + +Add a new canister name, source code location, and canister type for the rock_paper_scissors program and a new canister name, source code location, and canister type for the daemon program files below the assistant canister definition. +After making the changes, the canisters section of the dfx.json file should look similar to this: +Unresolved directive in multiple-actors.adoc - include::example$multiple-actors/dfx.json[] +You can leave the other sections as-is. + + +Save your changes and close the dfx.json file to continue. + + +Change the name of the default source file directory to match the name specified in the dfx.json configuration file by running the following command: +cp -r src/multiple_actors/ src/assistant/ + + +Copy the assistant source file directory to create the main program file for the rock_paper_scissors actor by running the following command: +cp -r src/assistant/ src/rock_paper_scissors/ + + +Copy the assistant source file directory to create the main program file for the daemon actor by running the following command: +cp -r src/assistant/ src/daemon/ + + +
+
+Modify the default programs +You now have three separate directories in the src directory, each with a template main.mo file. +For this tutorial, you will replace the content in each template main.mo file with a different actor. +To modify the default source code: + + +Open the src/assistant/main.mo file in a text editor and delete the existing content. + + +Copy and paste the following sample code into the file: +Unresolved directive in multiple-actors.adoc - include::example$multiple-actors/assistant/main.mo[] + + +Save your changes and close the main.mo file to continue. + + +Open the src/rock_paper_scissors/main.mo file in a text editor and delete the existing content. + + +Copy and paste the following sample code into the file: +Unresolved directive in multiple-actors.adoc - include::example$multiple-actors/rock_paper_scissors/main.mo[] + + +Save your changes and close the main.mo file to continue. + + +Open the src/daemon/main.mo file in a text editor and delete the existing content. + + +Copy and paste the following sample code into the file: +Unresolved directive in multiple-actors.adoc - include::example$multiple-actors/daemon/main.mo[] + + +Save your changes and close the main.mo file to continue. + + +
+
+Start the local network +Before you can build the multiple_actors project, you need to connect to the Internet Computer network either running locally in your development environment or running remotely on a subnet that you can access. +To start the network locally: + + +Open a new terminal window or tab on your local computer. + + +Navigate to the root directory for your project, if necessary. + + +Start the Internet Computer network on your local computer by running the following command: +dfx start + + +Leave the terminal that displays network operations open and switch your focus to your original terminal where you created your new project. + + +
+
+Register, build, and deploy your application +After you connect to the Internet Computer network running locally in your development environment, you can register, build, and deploy your multi-canister application locally. +To deploy the application locally: + + +Check that you are still in the root directory for your project, if needed. + + +Register, build, and deploy the application by running the following command: +dfx deploy +If you have access to the Internet Computer running remotely, you can deploy to the that network instead of deploying locally by specifying the --network option and the network alias configured in the dfx.json file. +For example, if you are connecting to the URL specified by the network alias ic you would run a command similar the following: +dfx deploy --network ic +The dfx deploy command output displays information about the operations it performs. +For example, the command displays the network-specific canister identifiers for the three canisters defined in the dfx.json configuration file. +Deploying all canisters. +Creating canisters... +Creating canister "assistant"... +"assistant" canister created with canister id: "75hes-oqbaa-aaaaa-aaaaa-aaaaa-aaaaa-aaaaa-q" +Creating canister "daemon"... +"daemon" canister created with canister id: "cxeji-wacaa-aaaaa-aaaaa-aaaaa-aaaaa-aaaaa-q" +Creating canister "rock_paper_scissors"... +"rock_paper_scissors" canister created with canister id: "7kncf-oidaa-aaaaa-aaaaa-aaaaa-aaaaa-aaaaa-q" + + +
+
+Verify deployment by calling functions +You now have three programs deployed as a canisters on your local replica network and can test each program by using dfx canister call commands. +To test the programs you have deployed: + + +Use the dfx canister call command to call the canister assistant using the addTodo function and pass it the task you want to add by running the following command: +dfx canister call assistant addTodo '("Schedule monthly demos")' + + +Verify that the command returns the to-do list item using the showTodos function by running the following command: +dfx canister call assistant showTodos +The command returns output similar to the following: +(" +___TO-DOs___ +(1) Schedule monthly demos") + + +Use the dfx canister call command to call the canister rock_paper_scissors using the contest function by running the following command: +dfx canister call rock_paper_scissors contest +The command returns the result of the hard-coded contest similar to the following: +("Bob won") + + +Use the dfx canister call command to call the canister daemon using the launch function by running the following command: +dfx canister call daemon launch + + +Verify the mock launch function returns "The daemon process is running" message": +(""The daemon process is running"") + + +
+
+Stop the local network +After you finish experimenting with your program, you can stop the local Internet Computer network so that it doesn’t continue running in the background. +To stop the local network: + + +In the terminal that displays network operations, press Control-C to interrupt the local network process. + + +Stop the Internet Computer network by running the following command: +dfx stop + + +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/tutorials/multiple-factorial-actors.xml b/modules/developers-guide/pages/tutorials/multiple-factorial-actors.xml new file mode 100644 index 000000000..6113e5a69 --- /dev/null +++ b/modules/developers-guide/pages/tutorials/multiple-factorial-actors.xml @@ -0,0 +1,218 @@ + + + +
+ +Using multiple actors +2021-08-05 + + +February 2020 (Alpha) + + +F + +In this tutorial, you are going to create a project with multiple actors. +Currently, you can only define one actor in a Motoko file and a single actor is always compiled to a single canister. +In addition, you cannot yet call functions defined in an actor in one canister from an actor defined in another canister or define an actor class to support multiple actor instances in your Motoko programs. +You can, however, create projects that have multiple actors and can build multiple canisters from the same dfx.json configuration file. +For this tutorial, you are going to create separate program files for three actors in the same project. +This project defines the following unrelated actors: + + +The assistant actor provides functions to add and show tasks in a to-do list. +For simplicity, the code sample for this tutorial only includes the functions to add to-do items and to show the current list of to-do items that have been added. A more complete version of this program-with additional functions for marking items as complete and removing items from the list—is included in Sample code, applications, and microservices. + + +The factorial actor provides a function for determining the factorial for a specified number. + + +The daemon actor provides mock functions for starting and stopping a daemon. +This code sample simply assigns a variable and prints messages for demonstration purposes. + + +
+Before you begin +Before starting the tutorial, verify the following: + + +You have downloaded and installed the SDK as described in +Getting started. + + +You have stopped any network replica processes running on the local +computer. + + +This tutorial takes approximately 20 minutes to complete. +
+
+Create a new project +To create a new project for this tutorial: + + +Open a terminal shell on your local computer, if you don’t already have one open. + + +Change to the folder you are using for your Internet Computer projects, if you are using one. + + +Create a new project by running the following command: +dfx new multiple_actors + + +Change to your project directory by running the following command: +cd multiple_actors + + +
+
+Modify the default configuration +You have already seen that creating a new project adds a default dfx.json configuration file to your project directory. +For this tutorial, you need to add sections to this file to specify the location of each program that defines an actor you want to build. +To modify the default dfx.json configuration file: + + +Open the dfx.json configuration file in a text editor, then change the default multiple_actors canister name and source directory to assistant. +For example: +{ + "canisters": { + "assistant": { + "frontend": { + "entrypoint": "src/multiple_actors/public/index.js" + }, + "main": "src/assistant/main.mo" + }, +Because you are going to add settings to this canisters section of the configuration file, you must also add a comma after the curly brace that encloses the location of the assistant main source code file. + + +Add a new canister name and source file location for the factorial program and a new canister name and source file location for the daemon program files below the assistant source file location. +For example: + "factorial": { + "main": "src/factorial/main.mo" + }, + "daemon": { + "main": "src/daemon/main.mo" + } + }, +You can leave the other sections as-is. + + +Change the name of the default source file directory to match the name specified in the dfx.json configuration file by running the following command: +cp -r src/multiple_actors/ src/assistant/ + + +Copy the assistant source file directory to create the main program file for the factorial actor by running the following command: +cp -r src/assistant/ src/factorial/ + + +Copy the assistant source file directory to create the main program file for the daemon actor by running the following command: +cp -r src/assistant/ src/daemon/ + + +
+
+Modify the default template programs +You now have three separate directories in the src directory, each with a template main.mo file. +For this tutorial, you will replace the content in each template main.mo file with a different actor. +To modify the default template source code: + + +Open the src/assistant/main.mo file in a text editor and delete the existing content. + + +Copy and paste the following sample code into the file: +include::example$multiple-actors/assistant/main.mo + + +Open the src/factorial/main.mo file in a text editor and delete the existing content. + + +Copy and paste the following sample code into the file: +include::example$multiple-actors/factorial/main.mo + + +Open the src/daemon/main.mo file in a text editor and delete the existing content. + + +Copy and paste the following sample code into the file: +include::example$multiple-actors/daemon/main.mo + + +
+
+Build all of the canisters in the project +You now have a program that you can compile into an executable WebAssembly module that you can deploy on your local replica network. +To build the executable for each actor in the project: + + +Change to the ~/ic-projects/multiple_actors root directory for your project, if needed. + + +Build the WebAssembly executable for each program by running the following command: +dfx build --all +If the command is successful, it builds all of the canisters you have specified in the dfx.json file. +Building canister assistant +Building canister factorial +Building canister daemon + + +
+
+Deploy the canisters in the project +You now have three separate compiled programs—one for each actor—ready for deployment. +To deploy the canisters: + + +Start the Internet Computer network on your local computer by running the following command: +dfx start + + +Open a new terminal shell, then change the ~/ic-projects/multiple_actors root directory for your project. +For example: +cd ~/ic-projects/multiple_actors + + +Deploy your canisters on the local network by running the following command: +dfx canister install --all + + +
+
+Verify deployment by calling functions +You now have three programs deployed as a canisters on your local replica network and can test each program by using dfx canister call commands. +To test the programs you have deployed on the local replica network: + + +Use the dfx canister call command to call the canister assistant using the addTodo function and pass it the task you want to add by running the following command: +dfx canister call assistant addTodo '("Schedule monthly demos")' + + +Verify that the command returns the to-do list item using the showTodos function by running the following command: +dfx canister call assistant showTodos +The command returns output similar to the following: +(" +___TO-DOs___ +(1) Schedule monthly demos + + +Use the dfx canister call command to call the canister factorial using the fac function by running the following command: +dfx canister call factorial fac '(8)' +The command returns the result of the function: +(40320) + + +Use the dfx canister call command to call the canister daemon using the launch function by running the following command: +dfx canister call daemon launch + + +Verify the mock launch function returns "The daemon process is running" message": +(""The daemon process is running"") + + +Stop the Internet Computer processes running on your local computer by running the following command: +dfx stop + + +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/tutorials/my-contacts.xml b/modules/developers-guide/pages/tutorials/my-contacts.xml new file mode 100644 index 000000000..b30d58b06 --- /dev/null +++ b/modules/developers-guide/pages/tutorials/my-contacts.xml @@ -0,0 +1,313 @@ + + + +
+ +Add a stylesheet +2021-08-05 + +Cascading stylesheets represent one of the most common ways to customize the user experience for an application. +This tutorial illustrates how to add a stylesheet when you use React to create a new front-end for your project. +If you already know how to add cascading stylesheets (CSS) to a React-based project, you can skip this tutorial. + +This tutorial illustrates using the React framework to manage the Document Object Model (DOM) for your canister. +Because React has its own custom DOM syntax, you need to modify the webpack configuration to compile the front-end code, which is written in JSX. For more information about learning to use React and JSX, see Getting started on the React website. + +
+Before you begin +Before starting the tutorial, verify the following: + + +You have node.js installed for front-end development and can install packages using npm install in your project. +For information about installing node for your local operating system and package manager, see the Node website. + + +You have downloaded and installed the {sdk-short-name} package as described in Download and install. + + +You have installed the Visual Studio Code plugin for Motoko as described in Install the language editor plug-in if you are using Visual Studio Code as your IDE. + + +You have stopped any Internet Computer network processes running on the local +computer. + + + +Because of significant changes to the handling of HTTP requests and front-end assets, this tutorial requires you to use the {sdk-short-name} version 0.7.0 or later. For an overview of what’s changed, see this article. + +
+
+Create a new project +To create a new project directory for your custom front-end application: + + +Open a terminal shell on your local computer, if you don’t already have one open. + + +Change to the folder you are using for your Internet Computer projects, if you are using one. + + +Verify that you have node.js installed locally, if necessary. + + +Create a new project by running the following command: +dfx new contacts + + +Change to your project directory by running the following command: +cd contacts + + +
+
+Install the React framework +if you’ve never used React before, you might want to explore the Intro to React tutorial or the React website before editing the front-end code. +To install required framework modules: + + +Install the React module by running the following command: +npm install --save react react-dom + + +Install the required TypeScript language compiler loader by running the following command: +npm install --save-dev typescript ts-loader + + +Install the required style loaders by running the following command: +npm install --save-dev style-loader css-loader +If the npm install command reports a vulnerability, you might also want to run the npm audit fix command to attempt to fix the vulnerability reported before continuing. + +As an alternative to installing these modules, you can edit the default package.json file to add dependencies for your project. + +Unresolved directive in my-contacts.adoc - include::example$add-stylesheet-package.json[] +The version of the JavaScript agent in this example package.json file is 0.9.2. In most cases, however, you would want to use the latest version of the agent available. When you create a new project, the dfx new command automatically retrieves the latest version of the JavaScript agent for you. You can also manually retrieve the latest version after creating a project by running the npm install --save @dfinity/agent command. + + +
+
+Modify the default program +For this tutorial, you are going to modify the main program to with code that allows you to store and look up contact information. +To modify the default program: + + +Open the src/contacts/main.mo file in a text editor and delete the existing content. + + +Copy and paste the following sample code into the file: +Unresolved directive in my-contacts.adoc - include::example$mycontacts/contacts.mo[] + + +Save your changes and close the main.mo file to continue. + + +
+
+Modify the front-end files +You are now ready to create a new front-end for your program. + + +Open the webpack configuration file (webpack.config.js) in a text editor. + + +Modify the front-end entry to replace the default index.html with index.jsx. +entry: { + // The frontend.entrypoint points to the HTML file for this build, so we need + // to replace the extension to `.js`. + index: path.join(__dirname, asset_entry).replace(/\.html$/, ".jsx"), +}, + + +Locate the commented example for the module key above the plugins section, then uncomment the following lines: +module: { + rules: [ + { test: /\.(js|ts)x?$/, loader: "ts-loader" }, + { test: /\.css$/, use: ['style-loader','css-loader'] } + ] +}, +These settings enable your program to use the ts-loader compiler and to import CSS files. + + +Save your changes and close the webpack.config.js file to continue. + + +Create a new file named tsconfig.json in the root directory for your project. + + +Open the tsconfig.json file in a text editor, then copy and paste the following into the file: +Unresolved directive in my-contacts.adoc - include::example$sample-tsconfig.json[] + + +Save your changes and close the tsconfig.json file to continue. + + +
+
+Add a stylesheet to your project +You are now ready to create a new cascading stylesheet and add it to your project. +To add a stylesheet: + + +Change to the src/contacts_assets/assets directory. +cd src/contacts_assets/assets/ + + +Open the main.css file in a text editor and delete the existing content. + + +Define some style properties for the front-end. +For example, copy and paste the following sample styles into the file: +Unresolved directive in my-contacts.adoc - include::example$mycontacts/mycontacts.css[] + + +Save your changes and close the main.css file to continue. + + +Change to the src/contacts_assets/src directory. +cd ../src + + +Open the default index.js file in a text editor and delete the existing content. + + +Copy and paste the following sample code into the index.js file: +Unresolved directive in my-contacts.adoc - include::example$mycontacts/mod-index.jsx[] + + +Rename the modified index.js file as index.jsx by running the following command: +mv index.js index.jsx + + +Open the default src/contacts_assets/src/index.html file in a text editor, then replace main.css as the stylesheet file name with mycontacts.css and update the body contents with <div id="contacts"></div>. +For example: +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="UTF-8" /> + <meta name="viewport" content="width=device-width" /> + <title>contacts</title> + <base href="/" /> + + <link type="text/css" rel="stylesheet" href="main.css" /> + </head> + <body> + <main> + <div id="contacts"></div> + </main> + </body> +</html> + + +Navigate back to the root of your project directory. +For example: +cd ../../.. + + +
+
+Start the local network +Before you can build the contacts project, you need to connect to the Internet Computer network either running locally in your development environment or running remotely on a subnet that you can access. +To start the network locally: + + +Open a new terminal window or tab on your local computer. + + +Start the Internet Computer network on your local computer by running the following command: +dfx start --background +After the local Internet Computer network completes its startup operations, you can continue to the next step. + + +
+
+Register, build, and deploy the application +After you connect to the Internet Computer network running locally in your development environment, you can register, build, and deploy your application locally. +To deploy the application: + + +Check that you are still in the root directory for your project, if needed. + + +Register, build, and deploy your application by running the following command: +dfx deploy +The dfx deploy command output displays information about the operations it performs. +Keep in mind that because you are running the Internet Computer locally, the identifiers displayed when you run the dfx deploy command are only valid on the local network. +To deploy canisters on an external Internet Computer network, you must connect to that network using the --network command-line option and a specific network name or address to register identifiers on that network. +For example, to deploy on the Internet Computer using the reserve network alias ic, you would run a command similar the following: +dfx deploy --network=ic + + +Start the Webpack development server: +npm start + + +
+
+View the front-end +You can now access the front-end for the contacts program by entering the canister identifier for the assets canister in a browser. +To view the front-end: + + +Open a browser and navigate to the http://localhost:8080. + + +Verify that you are prompted with a My Contacts form. +For example: + + + + +Sample front-end + + + +Create one or more test records by entering text in the Name, Address, and Email input fields and a number in the Phone input field, then clicking Add Contact. + + +Clear the form fields and type a contact name in the Lookup name field, then click Lookup to see the stored contact information. +Keep in mind that the Lookup name you type must be an exact match for the name of a contact you added. + + +
+
+Modify the stylesheet and test your changes +After viewing the Contacts application, you might want to make some changes. +To change stylesheet properties: + + +Open the src/contacts_assets/public/mycontacts.css file in a text editor and modify its style settings. +For example, you might want to change the background color or style the input form. +You should see the changes update immediately in your open browser window. + + +
+
+Modify the front-end or back-end code +If you want to explore further, you might want to experiment with modifying the front-end or back-end code for this tutorial. +For example, you might want try modifying the tutorial to do the following: + + +Change the front-end code to clear the input fields after adding a new contact, for example, as part of an onClick event. + + +Change the Motoko program functions to do partial instead of exact string matching on the Name field. (You will need to run dfx deploy to test your changes on the local replica) + + +Change the Motoko program to allow lookups based on a different field. + + +
+
+Stop the local network +After you finish experimenting with your program, you can stop the local Internet Computer network so that it doesn’t continue running in the background. +To stop the local network: + + +In the terminal that displays your webpack dev server, press Control-C to interrupt the development server. + + +Stop the Internet Computer network by running the following command: +dfx stop + + +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/tutorials/phonebook.xml b/modules/developers-guide/pages/tutorials/phonebook.xml new file mode 100644 index 000000000..2bf042b41 --- /dev/null +++ b/modules/developers-guide/pages/tutorials/phonebook.xml @@ -0,0 +1,195 @@ + + + +
+ +Import library modules +2021-08-05 + +In this tutorial, you are going to write a simple program that enables you to store and look up telephone numbers. +This tutorial illustrates how to import and use a few basic Motoko library functions. +For this tutorial, the Motoko base library functions are defined in the List and AssocList modules and enable you to work with lists as linked key-value pairs. +In this example, the key is a name and the value is the phone text string associated with that name. +This program supports the following function calls: + + +The insert function accepts the name and phone key-value pair as input stored in the book variable. + + +The lookup function is a query that uses the specified name key as input to find the associated phone number. + + +
+Before you begin +Before starting the tutorial, verify the following: + + +You have downloaded and installed the {sdk-short-name} package as described in Download and install. + + +You have stopped any Internet Computer network processes running on the local +computer. + + +This tutorial takes approximately 10 minutes to complete. +
+
+Create a new project +To create a new project for this tutorial: + + +Open a terminal shell on your local computer, if you don’t already +have one open. + + +Change to the folder you are using for your Internet Computer projects, if you are using one. + + +Create a new project by running the following command: +dfx new phonebook + + +Change to your project directory by running the following command: +cd phonebook + + +
+
+Modify the default program +For this tutorial, let’s create a new main.mo file for the simple phone number lookup program. +To modify the default template: + + +Open the src/phonebook/main.mo file in a text editor and delete the existing content. + + +Copy and paste the following sample code into the main.mo file: +Unresolved directive in phonebook.adoc - include::example$phonebook.mo[] +In looking at this sample program, you might notice the following key elements: + + +The code defines Name and Phone as custom Text types. +Creating user-defined types improves the readability of the code. + + +The insert function is an update call and the lookup function is a query call. + + +The Phone type is identified as an optional value by using the ?Phone syntax. + + + + +
+
+Start the local network +Before you can build the phonebook project, you need to connect to the Internet Computer network either running locally in your development environment or running remotely on a subnet that you can access. +Starting the network locally requires a dfx.json file, so you should be sure you are in your project’s root directory. +For this tutorial, you should have two separate terminal shells, so that you can start and see network operations in one terminal and manage your project in another. +To start the network locally: + + +Open a new terminal window or tab on your local computer. + + +Navigate to the root directory for your project, if necessary. + + +You should now have two terminals open. + + +You should have the project directory as your current working directory. + + + + +Start the Internet Computer network on your local computer by running the following command: +dfx start --clean +For this tutorial, we’re using the --clean option to start the Internet Computer network in a clean state. +This option removes any orphan background processes or canister identifiers that might disrupt normal operations. +For example, if you forgot to issue a dfx stop when moving between projects, you might have a process running in the background or in another terminal. +The --clean option ensures the you can start the Internet Computer network and continue to the next step without manually finding and terminating any running processes. + + +Leave the terminal that displays network operations open and switch your focus to your original terminal where you created your new project. + + +
+
+Register, build, and deploy the application +After you connect to the Internet Computer network running locally in your development environment, you can register, build, and deploy your application locally. +To deploy the application locally: + + +Check that you are still in the root directory for your project, if needed. + + +Register, build, and deploy your application by running the following command: +dfx deploy phonebook +The dfx.json file provides default settings for creating an application front-end entry point and assets canister. +In previous tutorials, we deleted the entries for the asset canister because we weren’t adding a front-end for the sample application. That change kept our project workspace tidy by eliminating files that would go unused. There’s no requirement to do this, however, and there’s no harm in leaving the asset canister description in the dfx.json file. For example, you might want to use it as a placeholder if you intend to add front-end assets later. +For this tutorial, you can deploy just the phonebook back-end canister using the dfx deploy phonebook command because the project is a terminal-based application that doesn’t include any front-end assets. +Although this tutorial illustrates how to skip compiling a front-end canister, you can add a simple user interface to this application later by exploring the phone-book project in the examples repository. + + +
+
+Add names and numbers using the insert function +You now have a program deployed as a canister on your local replica network and can test your program by using dfx canister call commands. +To test the program you have deployed on the local replica network: + + +Use the dfx canister call command to call the canister phonebook using the insert function and pass it a name and phone number by running the following command: +dfx canister call phonebook insert '("Chris Lynn", "01 415 792 1333")' + + +Add a second name and number pair by running the following command: +dfx canister call phonebook insert '("Maya Garcia", "01 408 395 7276")' + + +Verify that the command returns the number associated with "Chris Lynn" using the lookup function by running the following command: +dfx canister call phonebook lookup '("Chris Lynn")' +The command returns output similar to the following: +(opt "01 415 792 1333") + + +Try to call the lookup function with the number associated with "Maya Garcia" by running the following command: +dfx canister call phonebook lookup '("01 408 395 7276")' +Note that, in this case, the command returns (null) because the phone number is not a key associated with the "Maya Garcia" name entry. + + +Try to call the lookup function again to return the phone numbers for both "Maya Garcia" and "Chris Lynn" by running the following command: +dfx canister call phonebook lookup '("Maya Garcia","Chris Lynn")' +Because the program is written to return one value for one key, the command only returns information associated with the first key, in this example the phone number for Maya Garcia. + + +Unresolved directive in phonebook.adoc - include::example$candid-ui.adoc[] ++ + + + + +Phonebook functions + +
+
+Revise the source code in your program +To extend what you have learned in this tutorial, you might want to try modifying the source code to return different results. +For example, you might want to change the source code so that instead of a program that inserts and looks up a current key-value (name-phone) pair to create a program that stores contact information similar to a database "record" in which a primary key is associated with multiple fields. +In this example, your program might enable users or another program to add information—such as a home phone number, a cell phone number, an email address, and a street address—and selectively return all or specific field values. +
+
+Stop the local network +After you finish experimenting with your program, you can stop the local Internet Computer network so that it doesn’t continue running in the background. +To stop the local network: + + +In the terminal that displays network operations, press Control-C to interrupt the local network process. + + +Stop the Internet Computer network by running the following command: +dfx stop + + +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/tutorials/scalability-cancan.xml b/modules/developers-guide/pages/tutorials/scalability-cancan.xml new file mode 100644 index 000000000..6b3f4e046 --- /dev/null +++ b/modules/developers-guide/pages/tutorials/scalability-cancan.xml @@ -0,0 +1,110 @@ + + + +
+ +Create scalable apps +2021-08-05 + +The CanCan sample application is a simplified video-sharing service that demonstrates several features that you can use as models for your own applications. +For example, here are a few things you can learn by exploring the CanCan sample application: + + +How to build a scalable application by splitting content into fragments for upload and storage then using queries to retrieve and reassemble the fragments for efficient streaming. + + +How to configure interoperability for an application that uses canisters written in different back-end languages. + + +How to implement a basic authentication model for storing videos uploaded by different users. + + +How to build a front-end that implements more sophisticated user interface features for desktop or mobile apps. + + +
+Splitting uploaded content into multiple canisters +Because canisters are compiled WebAssembly modules, they have certain known limitations. +For example, currently WebAssembly modules have a maximum of 4GB for memory and an upper limit on the number of object calls allowed. +For a video-sharing sample applications like CanCan, these limitations mean that multiple canisters are required and that data must be broken into smaller chunks for storage and retrieval. +
+Implementing a distributed hash table +The initial attempt to build a scalable video-sharing service for the Internet Computer used a distributed hash table (DHT) as a back-end service with simple get and put functions that distributed data—chunks of the video to be uploaded or streamed—into a predefined set of canisters. +In the early phases of the project, this approach was sufficient for a proof-of-concept and verifying that the video data could be properly transcoded for storage and retrieval. +However, the scalability of the application was limited because the distributed hash table relied on a specific number of canisters that it could populate with data for storage and retrieve data from for viewing. +In addition, the original implementation of the distributed hash table back-end service included code to accommodate common network connectivity issues that could cause nodes to be unavailable or lose data. +
+
+Simplifying scalability +Because the Internet Computer protocol relies on replicated state across nodes in a subnet, it provides certain guarantees about fault tolerance and failover natively that are not generally available to applications running on other platforms or protocols. +With the realization that the Internet Computer could ensure that canisters were available to receive and respond to requests,the original distributed hash table back-end service was replaced with a simpler but more scalable back-end service called BigMap. +BigMap provides a simple, plug-in library for building scalable applications using key-value storage on the Internet Computer. +By using the BigMap library as a back-end service, the CanCan sample application can dynamically chunk, serialize, and distribute data to multiple canisters. +The library offers building blocks for application-specific, in-memory data abstractions that scale using any number of canisters. +Each canister still has limited capacity, but the application instantiates the canisters it needs and keeps track of the fragments that make up the full video content for each user’s videos in an index file called the manifest. +The code required for the BigMap service is much simpler than a traditional distributed hash table because the Internet Computer as a platform provides scalability, replication, failover, and fault tolerance. +
+
+
+Demonstrating interoperability +The BigMap service included in the CanCan sample application repository is written in the Rust programming language. +However, the CanCan sample application also demonstrates interoperability between canisters written in different languages. +In this case, the BigMap functionality is implemented using the Rust programming language and other services—such as encoding and decoding of video content and the management of user principals for authentication—are implemented using Motoko. +By deploying different parts of the sample application as canisters, the interaction between them provides a seamless user experience. +Although the BigMap service you see in the CanCan repository is written in Rust, the service was actually implemented in both Rust and Motoko programming languages to demonstrate the following: + + +You can run both Motoko code and Rust code deployed as canisters on the Internet Computer. + + +You can switch between back-end languages without affecting the operation of the CanCan sample application. + + +Both language implementation work seamlessly because the Candid language provides a common language for describing the BigMap API, independent of JavaScript, Rust, or Motoko. + + +
+
+Authentication model +Much like the LinkedUp sample application, the CanCan sample application uses the public-private key pair, browser-based local storage, and the Principal data type to authenticate users. +
+
+Implementing front-end features +The CanCan sample application uses the React library in combination with TypeScript to implement front-end user interface. +
+
+Data model overview +The application stores information about users and information about videos. +To support most browsers, the videos are serialized into byte arrays with video data stored in 500kb segments of bytes that are referred to as Uint8Array objects. +When a video is requested, the manifest loads the list of chunks required to play the video and concatenates the chunks before displaying the video in a standard <video> element. +
+User profiles +User profiles are stored as profiles/{username} and are defined using the following data model: +export interface Profile { + username: string; // maya + following: string[]; // [`alice`, `bob]` + followers: string[]; // ['palice'] + uploadedVideos: string[]; // ['profiles/maya/videos/a5b54646-2ea3-4e0e-82d1-da3ab8148df2'] + likedVideos: string[]; // ['profiles/bob/videos/b74e4eb0-dea8-4a4a-a1ae-d4593dc86930'] + avatar?: string; // ?ImageData (TODO) +} +
+
+Videos +Uploaded videos are identified by a unique identifier stored at profiles/{username}/videos/{videoId} and in public/videos (an array of all existing videos on the platform). +Metadata for videos is stored at profiles/{username}/videos/{videoId}/metadata +Individual video fragments are stored at profiles/{username}/videos/{videoId}/chunks/chunk.{0-10}. +Videos are stored as profiles/{username} and are defined using the following data model: +export interface Video { + src: string; // 'profiles/maya/videos/f5a44646-2ea3-4e0f-83d2-da3ab8148df2' + userId: string; // 'maya' + createdAt: string; // Date.now() + caption: string; // 'cool movie, punk' + tags: string[]; // ['outside', 'grilling', 'beveragino'] + likes: string[]; // ['sam', 'kelly'] + viewCount: number; // 102 + name: string; // 'grilling' +} +
+
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/tutorials/simple-cycles.xml b/modules/developers-guide/pages/tutorials/simple-cycles.xml new file mode 100644 index 000000000..fa04f80f9 --- /dev/null +++ b/modules/developers-guide/pages/tutorials/simple-cycles.xml @@ -0,0 +1,232 @@ + + + +
+ +Accept cycles from a wallet +2021-08-05 + +When you are doing local development, you can use the default wallet in your project to send cycles and check your cycle balance. +But what about the programs that need to receive and burn those cycles to execute their functions and provide services to users? +This tutorial provides a simple example to illustrate how you might add the functions to receive cycles and check your cycle balance to the default template program. +This example consists of the following: + + +The wallet_balance function enables you to check the current cycle balance for the canister. + + +The wallet_receive function enables the program to accept cycles that are sent to the canister. + + +The greet function accepts a text argument and displays a greeting in a terminal. + + +The owner function returns the principal used by the message caller. + + +
+Before you begin +Before starting the tutorial, verify the following: + + +You have downloaded and installed the {sdk-short-name} package as described in Download and install. + + +You have installed the Visual Studio Code plugin for Motoko as described in Install the language editor plug-in if you are using Visual Studio Code as your IDE. + + +You have stopped any Internet Computer network processes running on the local +computer. + + +
+
+Create a new project +To create a new project directory for testing access control and switching user identities: + + +Open a terminal shell on your local computer, if you don’t already have one open. + + +Change to the folder you are using for your Internet Computer projects, if you are using one. + + +Create a new project by running the following command: +dfx new cycles_hello + + +Change to your project directory by running the following command: +cd cycles_hello + + +
+
+Modify the default program +For this tutorial, you are going to modify the template source code to include new functions for accepting cycles and checking the cycle balance. +To modify the default program: + + +Open the src/cycles_hello/main.mo file in a text editor and delete the existing content. + + +Copy and paste the following sample code into the file: +Unresolved directive in simple-cycles.adoc - include::example$cycles-main.mo[] +Let’s take a look at a few key elements of this program: + + +The program imports a Motoko base library—ExperimentalCycles—that provides basic functions for working with cycles. + + +The program uses an actor class instead of a single actor so that it can have multiple actor instances to accept different cycle amounts up to a capacity for all instances. + + +The capacity is passed as an argument to the actor class. + + +The msg.caller identifies the principal associated with the call. + + + + +Save your changes and close the main.mo file to continue. + + +
+
+Start the local network +Before you can build the access_hello project, you need to connect to the Internet Computer network either running locally in your development environment or running remotely on a subnet that you can access. +To start the network locally: + + +Open a new terminal window or tab on your local computer. + + +Navigate to the root directory for your project, if necessary. + + +Start the Internet Computer network on your local computer by running the following command: +dfx start --clean --background +After the local Internet Computer network completes its startup operations, you can continue to the next step. + + +
+
+Register, build, and deploy the application +After you connect to the Internet Computer network running locally in your development environment, you can register, build, and deploy your application locally. +To deploy the application locally: + + +Check that you are still in the root directory for your project, if needed. + + +Register, build, and deploy your application by running the following command: +dfx deploy --argument '(360000000000)' +This example sets the capacity for the canister to 360,000,000,000 cycles. +The dfx deploy command output then displays information about the operations it performs, including the identity associated with the wallet canister created for this local project and the wallet canister identifier. +For example: +Deploying all canisters. +Creating canisters... +Creating canister "cycles_hello"... +Creating the canister using the wallet canister... +Creating a wallet canister on the local network. +The wallet canister on the "local" network for user "default" is "rwlgt-iiaaa-aaaaa-aaaaa-cai" +"cycles_hello" canister created with canister id: "rrkah-fqaaa-aaaaa-aaaaq-cai" +Creating canister "cycles_hello_assets"... +Creating the canister using the wallet canister... +"cycles_hello_assets" canister created with canister id: "ryjl3-tyaaa-aaaaa-aaaba-cai" +Building canisters... +Building frontend... +Installing canisters... +Installing code for canister cycles_hello, with canister_id rrkah-fqaaa-aaaaa-aaaaq-cai +Installing code for canister cycles_hello_assets, with canister_id ryjl3-tyaaa-aaaaa-aaaba-cai +Authorizing our identity (default) to the asset canister... +Uploading assets to asset canister... +Deployed canisters. + + +
+
+Test the application +After you have deployed the application on your local Internet Computer network, you can experiment with the wallet functions and test your program by using dfx canister call commands. +To test the application: + + +Check the principal for the default user identity by running the following command: +dfx canister call cycles_hello owner +The command displays output similar to the following for the current identity: +(principal "g3jww-sbmtm-gxsag-4mecu-72yc4-kef5v-euixq-og2kd-sav2v-p2sb3-pae") +If you haven’t made changes to the identity you were using to run the dfx deploy command, you should get the same principal by running the dfx identity get-principal command. +This is important because you must be the owner of the wallet canister to perform certain tasks such as sending cycles or granting other custodian identities permission to send cycles. + + +Check the initial wallet cycle balance by running the following command: +dfx canister call cycles_hello wallet_balance +You haven’t sent any cycles to the canister, so the command displays the following balance: +(0) + + +Send some cycles from your default wallet canister to the cycles_hello canister using the canister principal by running a command similar to the following: +dfx canister call rwlgt-iiaaa-aaaaa-aaaaa-cai wallet_send '(record { canister = principal "rrkah-fqaaa-aaaaa-aaaaq-cai"; amount = (256000000000:nat64); } )' + + +Call the wallet_balance function to see that the cycles_hello canister has the number of cycles you transferred, if you specified an amount under the allowed capacity, or the capacity you specified when you ran the dfx deploy command. +dfx canister call cycles_hello wallet_balance +The command displays output similar to the following: +(256_000_000_000) + + +Call the wallet_balance function to see the number of cycles in your default wallet by running a command similar to the following: +dfx canister call rwlgt-iiaaa-aaaaa-aaaaa-cai wallet_balance +The command returns the balance for the wallet canister identifier you specified as a record using Candid format. +For example, the command might display a record with an amount field (represented by the hash 3_573_748_184) and a balance of 97,738,624,621,042 cycles like this: +(record { 3_573_748_184 = 97_738_624_621_042 }) +For this simple tutorial, cycles are only consumed from the balance in the default wallet canister, not from the cycles_hello canister. + + +Call the greet function by running a command similar to the following: +dfx canister call cycles_hello greet '("from DFINITY")' + + +Rerun the call to the wallet_balance function to see the number of cycles deducted from your default wallet: +dfx canister call rwlgt-iiaaa-aaaaa-aaaaa-cai wallet_balance +For example, you might a result similar to this: +(record { 3_573_748_184 = 97_638_622_179_500 }) + + +
+
+Stop the local network +After you finish experimenting with the program, you can stop the local Internet Computer network so that it doesn’t continue running in the background. +To stop the local network: + + +In the terminal that displays network operations, press Control-C to interrupt the local network process. + + +Stop the Internet Computer network by running the following command: +dfx stop + + +
+
+Want to learn more? +If you are looking for more information about working with cycles, check out the following related resources: + + +Tokens and cycles (overview) + + +dfx identity (command reference) + + +Set an identity to own a canister (how-to) + + +Managing cycles (language reference) + + +ExperimentalCycles (base module) + + +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/webpack-config.xml b/modules/developers-guide/pages/webpack-config.xml new file mode 100644 index 000000000..690cec7cd --- /dev/null +++ b/modules/developers-guide/pages/webpack-config.xml @@ -0,0 +1,246 @@ + + + +
+ +Add front-end assets +2021-08-05 + +The tutorials introduced a few basic approaches to building a front-end user interface for your projects. +For example, the tutorials demonstrated: + + +Using Candid as a bare-bones interface to expose and test the functions in a canister. + + +Using raw HTML and JavaScript to display a simple HTML entry page. + + +Using React and compiled JavaScript to embed HTML attributes and elements directly in a page. + + +Using React and TypeScript to import CSS properties from an external file. + + +This section takes a closer look at the default front-end template, front-end configuration options, and using other frameworks to build the user interface for your projects. +
+How the default templates are used +As you might have noticed in the tutorials, projects include template index.js and webpack.config.js files. +By default, the index.js file imports an agent that is located in src/declarations folder. That directory will be generated by dfx when you run dfx deploy, either locally or when deploying to the IC. +That generated code will look like this: +import { Actor, HttpAgent } from "@dfinity/agent"; + +// Imports candid interface +import { idlFactory } from './hello.did.js'; +// CANISTER_ID is replaced by webpack based on node enviroment +export const canisterId = process.env.HELLO_CANISTER_ID; + +/** + * + * @param {string | Principal} canisterId Canister ID of Agent + * @param {{agentOptions?: import("@dfinity/agent").HttpAgentOptions; actorOptions?: import("@dfinity/agent").ActorConfig}} [options] + * @return {import("@dfinity/agent").ActorSubclass<import("./hello.did.js")._SERVICE>} + */ +export const createActor = (canisterId, options) => { + const agent = new HttpAgent({ ...options?.agentOptions }); + + // Fetch root key for certificate validation during development + if(process.env.NODE_ENV !== "production") agent.fetchRootKey(); + + // Creates an actor with using the candid interface and the HttpAgent + return Actor.createActor(idlFactory, { + agent, + canisterId, + ...options?.actorOptions, + }); +}; + +/** + * A ready-to-use agent for the hello canister + * @type {import("@dfinity/agent").ActorSubclass<import("./hello.did.js")._SERVICE>} + */ +export const hello = createActor(canisterId); +Then, if you return to index.js, you can see see that it takes the generated actor, and uses it to make a call to the hello canister’s greet method: +import { hello } from "../../declarations/hello"; + +document.getElementById("clickMeBtn").addEventListener("click", async () => { + const name = document.getElementById("name").value.toString(); + // Interact with hello actor, calling the greet method + const greeting = await hello.greet(name); + + document.getElementById("greeting").innerText = greeting; +}); +In many projects, you will be able to ignore the code under declarations for the most part, and make your changes in hello_assets/src. However, if your project has additional requirements, continue reading below. +
+Modifying the webpack configuration +Because webpack is a popular and highly-configurable module bundler for JavaScript-based applications, new projects create a default webpack.config.js file that makes it easy to add the specific modules—such as react and markdown—that you want to use. +If you review the code in the template webpack.config.js file, you see that it infers canister ID’s from your .dfx/local/canister_ids.json for local development, and from './canister_ids.json' for any other environments you configure. It decides which network to use based on a DFX_NETWORK proccess variable, or based on whether NODE_ENV is set to "production". +You can see these steps in the following code block: +let localCanisters, prodCanisters, canisters; + +try { + localCanisters = require(path.resolve(".dfx", "local", "canister_ids.json")); +} catch (error) { + console.log("No local canister_ids.json found. Continuing production"); +} + +function initCanisterIds() { + try { + prodCanisters = require(path.resolve("canister_ids.json")); + } catch (error) { + console.log("No production canister_ids.json found. Continuing with local"); + } + + const network = + process.env.DFX_NETWORK || + (process.env.NODE_ENV === "production" ? "ic" : "local"); + + canisters = network === "local" ? localCanisters : prodCanisters; + + for (const canister in canisters) { + process.env[canister.toUpperCase() + "_CANISTER_ID"] = + canisters[canister][network]; + } +} +initCanisterIds(); +
+
+Entry and output configuration +In many cases, you can use the default webpack.config.js file as-is, without any modification, or you can add plug-ins, modules, and other custom configuration to suit your needs. +The specific changes you make to the webpack.config.js configuration largely depend on the other tools and frameworks you want to use. +For example, if you have experimented with the Customize the front-end or Add a stylesheet front-end tutorials, you might have modified the following section to work with React JavaScript: + module: { + rules: [ + { test: /\.(ts|tsx|jsx)$/, loader: "ts-loader" }, + { test: /\.css$/, use: ['style-loader','css-loader'] } + ] + } + }; +} +If your application does not use dfx to run your build script, you can provide the variables yourself. For example: +DFX_NETWORK=staging NODE_ENV=production HELLO_CANISTER_ID=rrkah... npm run build +
+
+Ensuring node is available in a project +Because projects rely on webpack to provide the framework for the default front-end, you must have node.js installed in your development environment and accessible in the project directory. + + +If you want to develop your project without using the default webpack configuration and canister aliases, you can remove the assets canister from the dfx.json file or build your project using a specific canister name. For example, you can choose to build only the hello program without front-end assets by running the following command: +dfx build hello + + +If you are using the default webpack configuration and running dfx build fails, you should try running npm install in the project directory then re-running dfx build. + + +If running npm install in the project directory doesn’t fix the issue, you should check the configuration of the webpack.config.js file for syntax errors. + + +
+
+
+Using other modules with the React framework +Several tutorials and sample projects in the examples repository illustrate how to add React modules using the npm install command. +You can use these modules to construct the user interface components you want to use in your project. +For example, you might run the following command to install the react-router module: +npm install --save react react-router-dom +You could then use the module to construct a navigation component similar to the following: +import React from 'react'; +import { NavLink } from 'react-router-dom'; + +const Navigation = () => { + return ( + <nav className="main-nav"> + <ul> + <li><NavLink to="/myphotos">Remember</NavLink></li> + <li><NavLink to="/myvids">Watch</NavLink></li> + <li><NavLink to="/audio">Listen</NavLink></li> + <li><NavLink to="/articles">Read</NavLink></li> + <li><NavLink to="/contribute">Write</NavLink></li> + </ul> + </nav> + ); +} + +export default Navigation; +
+
+Iterate faster using webpack-dev-server +Starting with dfx 0.7.7, we now provide you with webpack dev-server in our dfx new starter. +The webpack development server—webpack-dev-server—provides in-memory access to the webpack assets, enabling you to make changes and see them reflected in the browser right away using live reloading. +To take advantage of the webpack-dev-server: + + +Create a new project and change to your project directory. + + +Start the {IC} locally, if necessary, and deploy as you normally would, for example, by running the dfx deploy command. + + +Start the webpack development server by running the following command: +npm start + + +Open a web browser and navigate to the asset canister for your application using port 8080. +For example: +http://localhost:8080 + + +Open a new terminal window or tab and navigate to your project directory. + + +Open the index.js file for your project in a text editor and make changes to the content. +For example, you might add an element to the page using JavaScript: +document.body.onload = addElement; +document.body.onload = addElement; + +function addElement () { + // create a new div element + const newDiv = document.createElement("div"); + + // and give it some content + const newContent = document.createTextNode("Test live page reloading!"); + + // add the text node to the newly created div + newDiv.appendChild(newContent); + + // add the newly created element and its content into the DOM + const currentDiv = document.getElementById("div1"); + document.body.insertBefore(newDiv, currentDiv); +} + + +Save your changes to the index.js file but leave the editor open to continue making changes. + + +Refresh the browser or wait for it to refresh on its own to see your change. +When you are done working on the front-end for your project, you can stop the webpack development server by pressing Control-C. + + +
+
+Using other frameworks +You may want to use a bundler other than webpack. Per-bundler instructions are not ready yet, but if you are familiar with your bundler, the following steps should get you going: + + +Remove the copy:types, prestart, and prebuild scripts from package.json + + +Run dfx deploy to generate the local bindings for your canisters + + +Copy the generated bindings to a directory where you would like to keep them + + +Modify declarations/<canister_name>/index.js and replace process.env.<CANISTER_NAME>_CANISTER_ID with the equivalent pattern for environment variables for your bundler + + +Alternately hardcode the canister ID if that is your preferred workflow + + + + +Commit the declarations and import them in your codebase + + +
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/work-with-languages.xml b/modules/developers-guide/pages/work-with-languages.xml new file mode 100644 index 000000000..be360ded1 --- /dev/null +++ b/modules/developers-guide/pages/work-with-languages.xml @@ -0,0 +1,383 @@ + + + +
+ +Develop using different languages +2021-08-05 + +Most of the examples in this guide use {proglang}—the programming language specifically designed to work with the {IC}. +Potentially, however, you can write programs in any language that compiles to WebAssembly to deploy applications that run on the {IC}. +This section provides some high-level guidance for writing programs in different languages and how to deploy them on the {IC}. +
+Using Rust +You can create Rust projects to run on the {IC} by using Cargo and compiling your program to use WebAssembly as the target output. +This section provides a summary of the key steps involved in deploying a Rust program as a smart contract canister on the {IC}. +You should note, however, that the steps described here only illustrate one approach. +Other implementation approaches are also possible. +Note that the Rust canister development kit (Rust CDK) for provides some shortcuts to make it easier to write functions as query and update calls and includes several examples to get you started building Rust-based projects, but you can also develop applications for the {IC} without using the Rust CDK. +
+Create a project +Because most Rust programmers use Cargo to handle build and package management tasks—such as downloading and compiling the libraries your program depends on—your first step is to create a new Rust project using the Cargo command-line interface. +Alternatively, you could create a new project using {sdk-long-name} instead of Cargo, but creating a project using Cargo represents the typical workflow for creating Rust projects. +To create a new Rust project: + + +Open a terminal shell on your local computer, if you don’t already +have one open. + + +Verify that you have Cargo installed by running the following command: +cargo --version + + +Change to the folder you are using for your {IC} or Rust sample projects. + + +Create a new project by running a command similar to the following: +cargo new my_rust_program +This command creates a new my_rust_program directory with a default Cargo.toml file and a src directory with a default main.rs file. + + +Change to your project directory by running the following command: +cd my_rust_program +If you list the contents of this directory, you’ll see that it only contains the Cargo.toml file and src directory. +To compile this project to run on the {IC}, you’ll need some additional files. + + +
+
+Modify the Cargo configuration file +The Cargo.toml file provides a manifest for each Rust package. +The manifest contains sections that specify configuration details for the package. +To prepare the Rust project to run on the {IC}, we’ll copy the default Cargo.toml file then modify some of the configuration details for the project. +To modify the Cargo.toml file: + + +Check that you are in the root directory for your project by running the pwd command, if necessary. + + +Copy the default Cargo.toml file to the src directory by running the following command: +cp Cargo.toml src/Cargo.toml +Projects that run on the {IC} typically use one project-level Cargo.toml file to set up a workspace for the canister members of the project and a second Cargo.toml file in the source code directory to configure settings for each canister. + + +Open the Cargo.toml file that is the root directory of your project in a text editor. +By default, the file contains the [package] and the [dependencies] sections. + + +Replace the [package] section with a [workspace] section similar to the following: +[workspace] +members = [ + "src/my_rust_program", +] +For information about the [workspace] section and [workspace] keys, see Workspaces. +For information about the other sections and keys you can configure in the Cargo.toml file, see The Manifest Format. + + +Remove the [dependencies] section. + + +Save your changes and close the file to continue. + + +Open the src/Cargo.toml file in a text editor. + + +Add a [lib] section with the path to the main source code similar to the following: +[lib] +path = "main.rs" + + +Update the [dependencies] section with any package dependencies. + + +Save your changes and close the file to continue. + + +
+
+Add a canister configuration file +When you create a new project using the {sdk-short-name}, the dfx new command automatically adds a default dfx.json configuration file to the project directory. +Because we created the Rust project using Cargo, you need to manually create this file in your project directory. +To add the dfx.json configuration file: + + +Check that you are still in your project directory by running the pwd command, if necessary. + + +Create a new dfx.json configuration file in the root directory for your project. + + +Open the `dfx.json`file in a text editor. + + +Add the version and canisters keys with settings similar to the following to the dfx.json file: +{ + "version": 1, + "canisters": { + "my_rust_program": { + "type": "custom", + "candid": "src/my_rust_program.did", + "wasm": "target/wasm32-unknown-unknown/debug/my_rust_program.wasm", + "build": "cargo build --target wasm32-unknown-unknown --package my_rust_program" + } + } +} +Let’s take a closer look at these settings. + + +The version setting is used to identify the version of the software used to create the project. + + +The canisters section specifies the name of the project’s canisters. +In this case, there’s only one canister and it is named my_rust_program. + + +The type key is set to custom because this canister is not one of the currently recognized (motoko or assets) canister types. + + +The candid key specifies the name and location of the Candid interface description file to use for this project. + + +The wasm key specifies the path to the WebAssembly file generated by the cargo build command. + + +The build key specifies the cargo command used to compile the output. + + +These are the minimum settings required. +As you build more complex programs, you might need to include additional configuration details in the Cargo.toml file, the dfx.json file, or both files. + + +Save your changes and close the file to continue. + + +
+
+Create a Candid interface description file +In addition to the dfx.json configuration file, you need to have a Candid interface description file—for example, my_rust_program.did—to map your program’s input parameters and return value formats to their language-agnostic representation in Candid. +To add the Candid interface description file: + + +Check that you are still in your project directory by running the pwd command, if necessary. + + +Create a new Candid interface description file—for example, my_rust_program.did—in the src directory for your project. + + +Open the Candid interface description file in a text editor and add a description for each function the program defines. +For example, if the my_rust_program is a simple program that increments a counter using the increment, read, and write functions, the my_rust_program.did file might look like this: +service : { + "increment": () -> (); + "read": () -> (nat) query; + "write": (nat) -> (); +} + + +Save your changes and close the file to continue. + + +
+
+Modify the default program +When you create a new project, your project src directory includes a template main.rs file with the "Hello, World!" program. +To modify the template source code: + + +Open the template src/main.rs file in a text editor and delete the existing content. + + +Write the program you want to deploy on the {IC}. +As you write your program, keep in mind that there are two types of calls—update calls and query calls—and that update functions use asynchronous messaging. + + +Save your changes and close the main.rs file. + + +
+
+Connect to a network and deploy +Before you can deploy and test your program, you need to do the following: + + +Connect to the {IC} network either running locally in your development environment or running remotely on a subnet that you can access. + + +Register a network-specific identifier for the application + + +Compile the program with a target output of WebAssembly. + + +Because you configured the custom dfx.json file with a cargo build command that compiles to WebAssembly, you can use the dfx command-line interface and standard work flow to perform all of the remaining steps. +To build and deploy the program locally: + + +Check that you are still in your project directory by running the pwd command, if necessary. + + +Open a new terminal window or tab on your local computer and navigate to your project directory. +For example, you can do either of the following if running Terminal on macOS: + + +Click Shell, then select New Tab to open a new terminal in your current working directory. + + +Click Shell and select New Window, then run cd ~/ic-projects/location_hello in the new terminal if your location_hello project is in the ic-projects working folder. + + +You should now have two terminals open with your project directory as your current working directory**. + + +Start the {IC} network on your local computer by running the following command: +dfx start +Depending on your platform and local security settings, you might see a warning displayed. +If you are prompted to allow or deny incoming network connections, click Allow. + + +Leave the terminal that displays network operations open and switch your focus to your original terminal where you created your project. + + +Register a unique canister identifier for the application by running the following command: +dfx canister create --all + + +Build the program by running the following command: +dfx build + + +Deploy the program on the local network by running the following command: +dfx canister install --all + + +Test functions in the program from the command-line or in a browser. + + +
+
+
+Using C +Because the {IC} supports applications compiled to standard WebAssembly modules, you can use standard compilers and toolchains to build applications in languages such as C, C++, Objective-C, and Objective-C++ programming languages and the Clang compiler. +To illustrate how to migrate programs written in C to run on the {IC}, let’s look at the simple reverse.c program in the examples repository. +The reverse.c program contains one function—named go—that reverses a string in place. +
+Set up the development environment +To compile the reverse.c program into WebAssembly, you need to have the clang compiler and standard libraries installed. +You can check whether you have clang installed on your local computer by running the following command: +clang --version +If clang is installed, the command displays information similar to the following: +clang version 10.0.0 +Target: x86_64-apple-darwin19.5.0 +Thread model: posix +InstalledDir: /usr/local/opt/llvm/bin +If the command doesn’t return version information, install clang before continuing. +The steps to install clang vary depending on the operating system you are using. +On Debian Linux, for example, run the following command: +sudo apt-get install clang lld gcc-multilib +On macOS, you can install clang by installing the Developer Command-Line Tools or by installing LLVM using Homebrew. +For example, if clang is not installed, run the following command: +brew install llvm +
+
+Compile the program into WebAssembly +You can compile a C program to run as a WebAssembly module by first compiling using clang, then linking using wasm-ld. +Depending on the operating system and version of clang you are using, you might use a different version of the WebAssembly linker, such as wasm-ld on macOS or wasm-ld-8 on Debian. +To compile to WebAssembly on macOS: + + +Compile the program by running the following clang command: +clang --target=wasm32 -c -O3 reverse.c + + +Run the linker to create the WebAssembly module by running the following wasm-ld command: +wasm-ld --no-entry --export-dynamic --allow-undefined reverse.o -o reverse.wasm + + +
+
+Create a minimal configuration file +Next, you need to prepare a simple configuration file that identifies the reverse program binary as a package that can be installed on the {IC} and a build directory so that you can use the dfx command-line interface to install and run the package as a canister. +To prepare a configuration file and build directory: + + +Create a dfx.json file with a canisters key by running the following command: +echo '{"canisters":{"reverse":{"main":"reverse"}}}' > dfx.json + + +Create a build directory for the program by running the following command: +mkdir build + + +Create a reverse directory for the program by running the following command: +mkdir build/reverse + + +Copy the WebAssembly modules to the new build/reverse directory by running the following command: +cp reverse.wasm build/reverse/ + + +
+
+Create a minimal interface description file +In a standard development workflow, running the dfx build command creates several files in the canisters output directory, including one or more Candid interface description (.did) files that handle type matching for the data types associated with a program’s functions. +For details about the syntax to use for different data types, see the Candid Guide and Candid specification. +To create a Candid interface description file for this program: + + +Open a terminal in the build directory you created for the reverse.c program source + + +Create a new text file named reverse.did. + + +Add a description of the go function. +For example: +service : { + "go": (text) -> (text); +} + + +Save your changes and close the file to continue. + + +
+
+Deploy and test the program +Before you can deploy and test your program, you need to do the following: + + +Connect to the {IC} network either running locally in your development environment or running remotely on a subnet that you can access. + + +Register a network-specific identifier for the application. + + +To deploy and test the application locally: + + +Open a new terminal window or tab on your local computer. +For example, if running Terminal on macOS,click Shell, then select New Tab to open a new terminal in your current working directory. + + +Start the {IC} network on your local computer in your second terminal by running the following command: +dfx start + + +Register a unique canister identifier for the reverse application by running the following command: +dfx canister create --all + + +Deploy the default program on the local network by running the following command: +dfx canister install --all + + +Call the go function in the program by running the following command: +dfx canister call reverse go reward +("drawer") + + +You can find additional examples of C programs in the examples repository. +
+
+
\ No newline at end of file diff --git a/modules/developers-guide/pages/working-with-canisters.xml b/modules/developers-guide/pages/working-with-canisters.xml new file mode 100644 index 000000000..da73517dd --- /dev/null +++ b/modules/developers-guide/pages/working-with-canisters.xml @@ -0,0 +1,285 @@ + + + +
+ +Manage canisters +2021-08-05 + + +March 2020 (Alpha) + + +M + +If you have experimented with using the {sdk-long-name} by following the tutorials in the Tutorials section or by cloning examples from the examples repository, you are already familiar with how to build and deploy programs as canisters. +This section provides additional information about the canister lifecycle and how to manage canisters. +
+Register a canister identifier +Depending on your preferred development workflow, you can register a unique canister identifier before or after you have a program ready to compile. +For example, if you want to reserve a unique identifier for your program on a subnet before you have written any code, you can do so by running the dfx canister create command. +This command essentially creates an empty canister placeholder into which you can later install your code. +To register a unique identifier for a canister: + + +Open a new terminal window or tab on your local computer. + + +Create a new project for the canister you plan to create by running a command similar to the following: +dfx new YOUR-PROJECT-NAME +Note that the name you use for the project is also used as the canister name by default. + + +Change to your new project directory. + + +Open the dfx.json configuration file and set the host and port for the Internet Computer network provider you want to use. +If you are using the local host as the Internet Computer network provider, you can skip this step. +You can also optionally change the names of your canisters or add canister settings to the configuration file if you want to create identifiers for any additional canisters you think you will need before compiling code. + + +Start the Internet Computer network, if necessary, by running the following command: +dfx start --background +In most cases, this step is only necessary if you are running the Internet Computer network locally. +If you were registering canisters to run on a remote network, you would include the --network command-line option to perform tasks on that network. + + +Register unique identifiers for the canisters defined in the dfx.json by running the following command: +dfx canister create --all +The command creates the .dfx/local directory and adds the canister_ids.json file to that directory for the project. + + +
+
+Build a canister with a local identifier +After you have written source code for your project, you need to compile it into a WebAssembly module before deploying it to the network as a canister. +If you are only compiling your project for local debugging, you can generate a locally-defined identifier for your project. +To generate a locally-defined identifier: + + +Create a project with the configuration settings and program logic to suit your needs. + + +Start the Internet Computer network, if necessary. +In most cases, this step is only necessary if you are running the Internet Computer network locally. +If you were compiling canisters to run on a remote network, you would include the --network command-line option to perform tasks on that network. + + +Generate hard-coded local identifiers for the canisters defined in the dfx.json by running the following command: +dfx build --check +Note that you must register unique canister identifiers to replace your locally-defined identifier before you can deploy the project on the Internet Computer network. + + +
+
+Deploy canisters on the Internet Computer network +After you have compiled a program, you can install the compiled code on the Internet Computer network running locally in your development or on a remote network provider. +The canister identifier that was created in advance or during the build process determines where your code is installed during deployment. +To deploy on the Internet Computer network for the first time: + + +Open a new terminal and navigate to your project directory. + + +Start the Internet Computer network, if necessary. +In most cases, this step is only necessary if you are running the Internet Computer network locally. +If you were installing canisters on a remote network, you would include the --network command-line option to perform tasks on that network. + + +Verify you have canister identifiers for all of the canisters you want to deploy. + + +Deploy all of the canisters by running the following command: +dfx canister install --all + + +
+
+Look up a canister identifier +All canisters have unique, network-specific identifiers. +You often need to use these identifiers to interact with the canister. +For example, if you want to access the front-end canister for an application or interact with a service using the Candid web interface, you must specify the appropriate canister identifier. +Because the identifiers are network-specific, the files used to store the information are in different directories. +For example, identifiers for a canister deployed locally are located in the project’s .dfx/local/canister_ids.json file. +You can look up the canister identifier for any specific canister by running the dfx canister id command. +For example, to look up the the canister identifier for the lookup canister deployed on the local network, you could run the following command: +dfx canister id lookup +To look up the canister identifier for the same canister deployed on the network specified by the ic alias, you would run the following command: +dfx canister --network=ic id lookup +
+
+Add a wallet for existing canisters +When you are doing local development, creating a new project automatically creates a default wallet for you to use with the canisters in that project.If you want to add a wallet for projects with canisters that you have previously created, you can force dfx to generate one by taking a couple of manual steps. +To add a wallet for use with an existing canister: + + +Open a terminal and navigate to your project directory. + + +Stop the local Internet Computer network, if necessary, by running the following command: +dfx stop + + +Delete the .dfx directory. + + +Start with Internet Computer network by running the following command: +dfx start --clean + + +
+
+Reinstall a canister +During the development cycle, you might want to install, then replace your program as you debug and improve it. +In this scenario, you might want to keep the canister identifier you have registered but without preserving any of the canister code or state. +For example, your canister might only have test data that you don’t want to keep or you might have decided to change the program altogether but want to reinstall under a canister identifier you used to install a previous program. +To reinstall on the Internet Computer network: + + +Open a new terminal and navigate to your project directory. + + +Start the Internet Computer network, if necessary. +In most cases, this step is only necessary if you are running the Internet Computer network locally. +If you were reinstalling canisters on a remote network, you would include the --network command-line option to perform tasks on that network. + + +Verify you have canister identifiers for all of the canisters you want to re-deploy. + + +Re-deploy all of the canisters by running the following command: +dfx canister install --all --mode reinstall + + +Note that you can use the reinstall mode to replace any canister, regardless of whether the canister has code or state associated with it. +
+
+Set an identity to own a canister +In most cases, a default user identity is created for you automatically the first time you run the dfx canister create command. +This default identity consists of the public and private key pair generated for your local user account. +Typically, this default identity is also the default owner of all of the projects you create and all of the canisters you deploy. +You can, however, proactively create and use identities of your choice to circumvent the default user identity from being used. +As an example, the following scenario illustrates creating a registered_owner identity that is then used to register, build, deploy, and call the pubs project. +To set an identity for a project: + + +Create a new project by running the following command: +dfx new pubs + + +Change to the project directory by running the following command: +cd pubs + + +Start the Internet Computer network locally in the background by running the following command: +dfx start --background + + +Create a new registered_owner identity by running the following command: +dfx identity new registered_owner + + +Set the active user context to use the registered_owner identity by running the following command: +dfx identity use registered_owner + + +Register, build, and deploy canisters for the project by running the following commands: +dfx canister create --all +dfx build --all +dfx canister install --all +These commands run using the registered_owner identity, making that user the owner of the canisters deployed. + + +Call the greet function to verify a successful deployment by running the following command: +dfx canister call pubs greet '("Sam")' + + +
+
+Managing the running state of a canister +After you deploy a canister on the Internet Computer, it can begin receiving and processing requests from users and from other canisters. +Canisters that are available to send requests and receive replies are considered in be in a Running state. +Although canisters are normally placed in the Running state by default, there are cases where you might want to temporarily or permanently stop a canister. +For example, you might want to stop a canister before upgrading it. +Stopping a canister helps to ensure proper handling of any messages that are in progress and need to either run to completion or be rolled back. +You might also want to stop a canister to clear its message queue cleanly as a prerequisite to deleting the canister. +You can check the current status of all canisters or a specified canister by running the dfx canister status command. +For example, to see the status for all canisters running on the local Internet Computer network, you would run the following command: +dfx canister status --all +This command returns output similar to the following if canisters are currently running: +Canister status_check's status is Running. +Canister status_check_assets's status is Running. +You can stop canisters that are currently running by running the dfx canister stop command. +dfx canister stop --all +This command displays output similar to the following: +Stopping code for canister status_check, with canister_id 75hes-oqbaa-aaaaa-aaaaa-aaaaa-aaaaa-aaaaa-q +Stopping code for canister status_check_assets, with canister_id cxeji-wacaa-aaaaa-aaaaa-aaaaa-aaaaa-aaaaa-q +If you were to rerun the dfx canister status command, you might see a status of Stopped indicating that there were no pending messages that needed to processed or a status of Stopping indicating that there were messages in-flight that needed to be addressed. +To restart a canister-for example, after a successful canister upgrade—you can run the dfx canister start command. +For example, to restart all of the canisters running on the local Internet Computer network, you would run the following command: +dfx canister start --all +This command displays output similar to the following: +Starting code for canister status_check, with canister_id 75hes-oqbaa-aaaaa-aaaaa-aaaaa-aaaaa-aaaaa-q +Starting code for canister status_check_assets, with canister_id cxeji-wacaa-aaaaa-aaaaa-aaaaa-aaaaa-aaaaa-q +
+
+Upgrade a canister +Unlike a canister replacement that preserves the canister identifier but no state, a canister upgrade enables you to preserve the state of a deployed canister, and change the code. +For example, assume you have an application that manages professional profiles and social connections. +If you want to add a new feature to the application, you need to be able to update the canister code without losing any of the previously-stored data. +A canister upgrade enables you to update existing canister identifiers with program changes without losing the program state. + +To preserve state when you are upgrading a canister written in Motoko, be sure to use the stable keyword to identify the variables you want to preserve. For more information about preserving variable state in Motoko, see Stable variables and upgrade methods. +If you are upgrading a canister written in Rust, you should use pre_upgrade and post_upgrade functions as illustrated in the Rust CDK asset storage example to ensure data is properly preserved after a canister upgrade. + +To upgrade a canister on the Internet Computer network: + + +Open a new terminal and navigate to your project directory. + + +Start the Internet Computer network, if necessary. +In most cases, this step is only necessary if you are running the Internet Computer network locally. +If you were upgrading canisters on a remote network, you would include the --network command-line option to perform tasks on that network. + + +Verify you have canister identifiers for all of the canisters you want to upgrade. +Note that your program must identify the variables for which to maintain state by using the stable keyword in the variable declaration. +For more information about declaring stable variables, see the Motoko Programming Language Guide. + + +Upgrade all of the canisters by running the following command: +dfx canister install --all --mode upgrade + + +
+
+Delete a canister +If you want to permanently delete a specific canister or all canisters for a specific project on a given Internet Computer network, you can do so by running the dfx canister delete command. +Deleting a canister removes the canister identifier, code, and state from the Internet Computer network. +Before you can delete a canister, however, you must first stop the canister to clear any pending message requests or replies. +To delete all canisters for a project running on the local Internet Computer network: + + +Open a new terminal and navigate to your project directory. + + +Start the Internet Computer network, if necessary. +In most cases, this step is only necessary if you are running the Internet Computer network locally. +If you were deleting canisters on a remote network, you would include the --network command-line option to perform tasks on that network. + + +Check the status of the project canisters running on the local Internet Computer network by running the following command: +dfx canister status --all + + +Stop all of the project canisters by running the following command: +dfx canister stop --all + + +Delete all of the project canisters by running the following command: +dfx canister delete --all + + +
+
\ No newline at end of file diff --git a/modules/integration/integration-nav.xml b/modules/integration/integration-nav.xml new file mode 100644 index 000000000..f2bdb7869 --- /dev/null +++ b/modules/integration/integration-nav.xml @@ -0,0 +1,19 @@ + + + +
+ +Untitled +2021-05-09 + + + +Integration + + +Integrating with the Ledger + + + + +
\ No newline at end of file diff --git a/modules/integration/pages/ledger-quick-start.xml b/modules/integration/pages/ledger-quick-start.xml new file mode 100644 index 000000000..47dfa3bbe --- /dev/null +++ b/modules/integration/pages/ledger-quick-start.xml @@ -0,0 +1,398 @@ + + + +
+ +Integrate with the Internet Computer ledger +2021-08-05 + +This guide is an introduction to the Internet Computer Protocol (ICP) components for token distribution, transaction management, token-based staking, and payments for services. +The document includes an overview of the design, implementation, security guarantees, system requirements, and the application programming interface (API) that support token management for the Internet Computer Protocol. +Integrate with the Internet Computer ledger is intended as a high-level overview for organizations and developers who need to understand the terminology and overall transaction management flow for Internet Computer Protocol (ICP) utility tokens. +While you read this guide, be aware that additional details about specific components or interfaces might be available in subsequent documents to supplement the overview provided in this document. +In addition, this overview focuses on how to integrate with the Internet Computer using the Rosetta API. +Other options for integration are possible. +Information about other integration options and procedures might be available in future documentation. +
+Basic terminology +The Internet Computer is primarily a distributed and decentralized platform for running software. +When you write applications that run on the Internet Computer, you deploy your programs in the form of a conceptual computational unit called a canister. +A canister is similar to a "smart contract" in that it consists of the source code of a program as well as its running state, and is replicated on a blockchain network that guarantees security as well as liveness. +End-users or other canisters can send messages to canister functions to perform specific operations. +The messages can be either query calls that retrieve information without saving the state of application data or update calls that change and preserve the state. +The order in which updates are executed is agreed upon by using a consensus protocol between all Internet Computer nodes that run the canister. +
+
+Ledger canister overview +The Internet Computer Protocol (ICP) implements token management using a specialized canister, called the ledger canister. +There is a single ledger canister which runs alongside all other canisters on the Internet Computer. +The ledger canister is basically a smart contract that holds accounts and transactions. +These transactions either mint ICP tokens for accounts, transfer ICP tokens from one account to another, or burn ICP tokens, eliminating them from existence. +The ledger canister maintains a traceable history of all transactions starting from its genesis, or beginning, state. +
+Accounts +An account belongs to and is controlled by the account owner who must be an IC principal. No account can be owned by two or more IC principals (no "joint accounts"). +An account owner may control more than one account. In this case, each account corresponds to a pair (account_owner, sub_account). The sub-account is an optional bitstring which helps distinguish between the different sub-accounts of the same owner. +An account on the ledger is identified by its address, which is derived from the principal ID and sub-account identifier. +In this context, you can think of principal identifiers as a rough equivalent to the hash of a user’s public key for Bitcoin or Ethereum. You use the corresponding secret key to sign messages and therefore authenticate to the ledger canister and operate on the principal’s account. Canisters can also have accounts in the ledger canister, but currently the functionality of such accounts is limited. +The ledger canister is initialized using administrative operations that are internal to the Internet Computer. +As part of the initialization process, the canister is created with the set of accounts and associated ICP token balances. +
+
+Transaction types +There are three operations that can change the internal state of the ledger canister: + + +Minting ICP tokens for accounts. + + +Transferring ICP tokens between accounts. + + +Burning ICP tokens. + + +All operations are recorded as transactions in the ledger canister. +The ledger maintains the transactions as a hashed blockchain. +As state changes are recorded, each new transaction is placed in a block and assigned a unique index. +The entire chain is regularly authenticated by signing the latest chain link. The signature used to authenticate the chain can be verified by any third party who has access to the root public key of the Internet Computer. +Specific transactions can be retrieved by querying the ledger. +
+
+
+Integrate with the Internet Computer ledger canister using the Rosetta API +One can interact with the Internet Computer and ledger canister in several ways. +This document outlines how to integrate with the ledger canister using the Rosetta application programming interface. This is a well-documented and open standard designed to support multiple blockchain data formats and structured communication for exchange transactions. +The interface is implemented by the integration software—`dfinity/rosetta-api. This piece of software enables you to deploy a passive Rosetta node outside of the Internet Computer network and use the node to communicate with the ledger canister running on the Internet Computer. +The following diagram provides a simplified view of the communication between the Rosetta node and the Internet Computer using the dfinity/rosetta-api integration software. + + + + +basic rosetta api integration + +As this diagram suggests, the Rosetta node maintains a local copy of the Internet Computer ledger canister. +Periodically, the dfinity/rosetta-api software running on the Rosetta node updates its local view of the ledger by querying the ledger canister for the latest block of the ledger chain, then querying for any missing ledger blocks. +The Rosetta node uses the root key of the Internet Computer to ensure that the local copy of the ledger is genuine. +The integration software also allows you to use the Rosetta node to submit transactions to the Internet Computer ledger. +
+Integration workflow overview +The following summarizes the basic operational workflow for transferring ICP tokens if you’re using a Rosetta node to communicate with the Internet Computer ledger canister. In this scenario, you must be an Internet Computer principal who authenticates to the Internet Computer using a signing key stored in a wallet. +After a user submits a request to the Rosetta node to make a transaction, the request is passed to the integration software running on that node to interact with the Internet Computer and completes the following operations: + + +It reads from the local copy of the ledger to determine the state of the latest transaction index and block height identified by the latest_index label. + + +It generates a random nonce value — used to ensure transactions are unique. + + +It creates an ingress message for the ledger canister that invokes the send function and specifies the amount and the destination for the transaction: +send(nonce, latest_index, dst, amount) + + +It signs the ingress message using the key stored in the wallet to identify the principal ID for the owner. + + +It forwards the message to the ledger canister on the Internet Computer. + + +
+
+Set up a Rosetta node +You can set up a Rosetta API-compliant node to interact with the Internet Computer and exchange Internet Computer Protocol (ICP) tokens. +To keep the instructions simple, we use a Docker image to create the integration with the Rosetta API  — one can also build and run binary using the source code. +If you don’t already have Docker on your local computer, download and install the latest version. +To set up a Rosetta node (which connects to a testnet): + + +Install Docker and start the Docker daemon. +The Docker daemon (dockerd) should automatically start when you reboot your computer. If you start the Docker daemon manually, the instructions vary depending on the local operating system. + + +Pull the latest dfinity/rosetta-api image from the Docker Hub by running the following command: +docker pull dfinity/rosetta-api + + +Start the integration software by running the following command: +docker run \ + --interactive \ + --tty \ + --publish 8080:8080 \ + --rm \ + dfinity/rosetta-api +This command starts the software on the local host and displays output similar to the following: +Listening on 0.0.0.0:8080 +Starting Rosetta API server +By default, the software does not connect to the ledger canister running on the Internet Computer production network, but rather it connects to one of the testnets. +If you have been assigned a test network and corresponding ledger canister identifier, you can run the command against that network by specifying an additional canister argument. For example, the following command illustrates connecting to the ledger canister on a test network by setting the canister argument to 2xh5f-viaaa-aaaab-aae3q-cai. +docker run \ + --interactive \ + --tty \ + --publish 8080:8080 \ + --rm \ + dfinity/rosetta-api + --canister 2xh5f-viaaa-aaaab-aae3q-cai + +The first time you run the command it might take some time for the node to catch up to the current link of the chain. +When the node is caught up, you should see output similar to the following: + +You are all caught up to block height 109 +After completing this step, the node continues to run as a passive node that does not participate in block making. + + +Open a new terminal window or tab and run the ps command to verify the status of the service. +If you need to stop the service, press CONTROL-C. You might want to do this to change the canister identifier you are using, for example. +To test the integration after setting up the node, you will need to write a program to simulate a principal submitting a transaction or looking up an account balance. + + +
+
+Run the Rosetta node in production +When you are finished testing, you should run the Docker image in production mode without the --interactive, --tty, and --rm command-line options. +These command-line options are used to attach an interactive terminal session and remove the container, and are primarily intended for testing purposes. +To run the software in a production environment, you can start the Docker image using the --detach option to run the container in the background and, optionally, specify the --volume command for storing blocks. +To connect the Rosetta node instance to the mainnet, add flags: +--mainnet and --not-whitelisted. +For more information about Docker command-line options, see the Docker reference documentation. +
+
+Requirements and limitations +The integration software provided in the Docker image has one requirement that is not part of the standard Rosetta API specification. +For transactions involving ICP tokens, the unsigned transaction must be created less than 24 hours before the network receives the signed transaction. The reason is that the 'created_at' field of each transaction refers to an existing transaction (essentially last_index available locally at the time of transaction creation). Any submitted transaction that refers to a transaction that is too old is rejected to maintain operational efficiency. +Other than this requirement, the Rosetta API integration software is fully-compliant with all standard Rosetta endpoints and passes all of the rosetta-cli tests. +The software can accept any valid Rosetta request. +However, the integration software only prompts for transactions to be signed using Ed25519, rather than all the signature schemes listed here and only replies with a small subset of the potential responses that the specification supports. For example, the software doesn’t implement any of the UTXO features of Rosetta, so you won’t see any UTXO messages in any of the software responses. +
+
+Basic properties for ICP utility tokens +The ICP token is similar to utility tokens governing decentralized networks such as Bitcoin, but also differs in important ways. +The ICP token is similar to Bitcoin in the following ways: + + +Each ICP token is divisible 10^8 times. + + +All transactions are stored in the ledger starting with the genesis initial state. + + +Tokens are entirely fungible. + + +Account identifiers are 32 bytes and are roughly the equivalent of the hash of a public key, optionally together with some additional sub-account specifier. + + +The ICP token differs from Bitcoin in the following ways: + + +Rather than using proof of work, staked participant nodes use a variant of threshold BLS signatures to agree on a valid state of the chain. + + +Any transaction can store an 8-byte memo — this memo field is used by the Rosetta API to store the nonce that distinguishes between transactions. However, other uses for the field are possible. + + +
+
+
+Frequently asked questions +The following questions are taken from the most commonly reported questions and blockers from the developer community regarding Rosetta integration with the Internet Computer. +
+The Rosetta node +
+How to I run an instance of the Rosetta node? +An easy way to accomplish this is to use the dfinity/rosetta-api Docker image. Once the node initializes and syncs all blocks, you can perform queries and submit transactions by invoking the Rosetta API on the node. The node listens on the 8080 port. +
+
+How do I connect the Rosetta node to the mainnet? +Use flags --mainnet and --not-whitelisted +
+
+How do I know if the node has caught up with the test net? +Search the Starting Rosetta API server startup log. There will be a log entry that says You are all caught up to block XX. This message confirms that you are caught up with all blocks. +
+
+How to persist synced blocks data? +Mount the /data directory elsewhere. +
+
+Is the Rosetta node versioned? +Not yet. Before launch, when we push to the dfinity/rosetta-api:latest image, it’s usually a major update that we’ll announce in our communication channels beforehand. +We’ll soon implement nightly builds of the image, and CI will ensure it works before pushing. Other than latest, those images will also be tagged with the build date, so for more reproducibility, it’s possible to use the image of a specific date tag rather than latest. We’ll announce when nightly builds become available. +
+
+How do I connect to the main net instead of the test net? +Start dfinity/rosetta-api with --help, you can see some additional CLI arguments that can be passed. Among those there are --canister-id and --ic-url which can be used to configure the ledger destination. At the moment, they default to the test net. +Note: The main net is not live yet; it will be live some time before the publicly announced date, and we’ll push the updated image to point to the main net to ensure you can perform testing on the main net beforehand. +
+
+
+ICP-specific Rosetta API details +
+How are accounts generated and verified? + + +Generate an ED25519 keypair. + + +The secret key is used for signing transactions. + + +The public key is used for generating a self-authenticating Principal ID. For more information, see: https://sdk.dfinity.org/docs/interface-spec/index.html#_principals. + + +The Principal ID is hashed to generate the account address. + + +
+
+How to use the public key to generate its account address? + + +Call the /construction/derive endpoint with the hex-encoded 32-byte public key. + + +Call the pub_key_to_address function in the JavaScript SDK. + + +
+
+How to verify the checksum of an account address? + + +After hex decoding, the first 4 bytes is the big-endian CRC32 checksum of the rest of the address. + + +Call address_from_hex in the JavaScript SDK. It returns and error if checksum doesn’t match. + + +Here is a Java implementation of address validation logic. + + +
+
+What are <literal>signature_type</literal> and <literal>curve_type</literal> for ED25519? + + +signature_type is "ed25519" + + +curve_type is "edwards25519" + + +
+
+What kinds of transactions can appear in a block, and what do they mean? + + +Each block as queried from the /block endpoint contains exactly one transaction. Note that some operations, such as burn, are not suppoted in Rosetta API calls. + + +Transfer + + +Operation 0: type "TRANSACTION", subtracts the transfer amount from the source account. + + +Operation 1: type "TRANSACTION", adds the same transfer amount to the destination account. + + +Operation 2: type "FEE", subtracts the fee from the source account. + + + + +Don’t rely on the order above, you can rearrange them in the /construction/payloads call, and when parsing transactions in a block, you should check for transaction type and amount sign instead. + + +Mint + + +Operation 0: type "MINT", adds the minted amount to the destination account. + + + + +Burn + + +Operation 0: type "BURN", subtract the burned amount from the source account. + + + + +"status" is always "COMPLETED", failed transactions don’t show up in the polled blocks + + +
+
+What fee is needed? Can I customize the fee? + + +By calling /construction/metadata, you can get suggested_fee. + + +At the moment, suggested_fee is a constant, and the fee specified in a transfer must be equal to it. + + +Fees do not apply to Mint or Burn operations. + + +
+
+How do I know if the submitted transaction hit the chain? + + +The Rosetta server will wait for a short period of time after a /construction/submit call, if the transaction hit the chain, it’ll be returned. + + +In case of an error from the ledger, the error information will be available in the /construction/submit result. + + +It’s still possible that a /construction/submit call has returned successfully, but there’s still some time before it hits the chain. You can poll latest blocks and search for the transaction hash. We also implemented a subset of the /search/transactions endpoint which allows searching for a transaction given its hash. + + +5 minutes is a worst case timeout. + + +Don’t use mempool APIs, our implementation is an empty stub. + + +
+
+What kinds of errors might I get from Rosetta API calls? + + +Successful calls always have 200 response status code. + + +Failed calls always have 500 response status code, with a JSON payload containing more information. The possible Rosetta error codes and their text descriptions can be seen in the /network/options call result. + + +
+
+How do I send Mint or Burn transactions? + + +Mint is a privileged operation; we don’t support Burn through Rosetta API calls at the moment. + + +
+
+What happens if the same signed transaction is submitted multiple times? +The ledger rejects duplicate transactions. Only the first transaction will make it to the chain and for the duplicate submissions the /construction/submit call will fail. +
+
+How to sign a transaction without calling Rosetta API? +The JavaScript SDK contains an implementation of the offline signing logic. This is deeply coupled with internal implementation details, so we strongly advise you to call /construction/combine to sign a transaction if possible. +
+
+How to configure the ingress time period? +In the /construction/payloads call, you can add one or all of the ingress_start / ingress_end fields to specify the ingress time period. They are nanoseconds since the Unix epoch, and must be within the next 24 hours. This enables generating & signing a transaction, but delaying the actual submission to a later time. +
+
+How to deserialize a signed transaction? +The JavaScript SDK supports deserializing a signed_transaction hex string and recovering some information about the transfer. This may be useful in the case that you’d like to perform a sanity check. +
+
+
+
\ No newline at end of file diff --git a/modules/introduction/pages/welcome.xml b/modules/introduction/pages/welcome.xml new file mode 100644 index 000000000..91c986da2 --- /dev/null +++ b/modules/introduction/pages/welcome.xml @@ -0,0 +1,70 @@ + + + +
+ +Introducing the Internet Computer +2021-08-05 + +Hello there! +If you’ve landed here, you’re interested in learning more about the Internet Computer. You’re in the right place — take a look below for where to get started! +
+For: First-Timers +The Internet Computer is a blockchain that runs at web speed with unbounded capacity. +As a crash course in blockchain history, Bitcoin created digital gold. Then, in the next step of the evolution, Ethereum developed smart contracts and pioneered DeFi and NFT use cases. +The Internet Computer is the third major blockchain innovation — a blockchain that scales smart contract computation and data, runs them at web speed, processes and stores data efficiently, and provides powerful software frameworks to developers. By making this possible, the Internet Computer enables the complete reimagination of how systems and apps operate. +Interested in learning more? Check out the following resources: + + +Primer to the Internet Computer, a high-level overview of the Internet Computer in under 10 minutes + + +The Internet Computer Review, our blog covering updates for the Internet Computer + + +The Reboot, our tech publication exploring the issues with the current internet + + +Follow us on the official DFINITY Twitter for the latest updates. +
+
+For: Developers +The Internet Computer hosts special smart contracts, called canisters. A canister is a bundle of WebAssembly bytecode logic and memory pages. Apps on the Internet Computer are created from one or more canisters. +Canisters can serve web content directly to end-users, and users can interact with blockchain services without holding tokens. When building on the Internet Computer, you can deploy code directly to the Internet. +The Internet Computer can eventually host any number of canisters (i.e., code & state). Moreover, it can run them concurrently with unbounded on-chain capacity. This means you can create dapps that scale. +Canisters are unstoppable and tamperproof. Imagine building without having to worry about databases, caches, firewalls, CDNs, cloud providers, VPNs, DNS, and even usernames & passwords — all because the Internet Computer abstracts these needs away. +Excited to take the leap? Check out our Quick Start to get started with a simple hello world app. +Interested in getting plugged into our developer community? Check out the following: + + +Developer Discord, our official Discord for the developer community + + +Developer Forum, a welcoming space for technical discussions about building on the Internet Computer + + +You can follow us on the DFINITY Developer Twitter for the latest developer-specific updates. +
+
+For: Protocol Enthusiasts +The Internet Computer is created by the Internet Computer Protocol (“ICP”), which has formed the world’s first web-speed, web-serving public blockchain network. The Internet Computer can grow its capacity with demand and is self-governing. It combines special node machines run en masse by independent data centers all around the world. Like all blockchains, it is unstoppable, and the code it hosts is tamperproof. +Get started by checking out our “Concepts” section to the left, starting with What is the Internet Computer? +To learn more about the Internet Computer Protocol, check out the following resources: + + +Technical Library, for in-depth videos with our world-class R&D team explaining components of the Internet Computer Protocol. Worth noting in particular: + + +Chain Key Cryptography, one of the fundamental breakthroughs enabling the Internet Computer to scale to millions of nodes. The most notable innovation of Chain Key cryptography is that the Internet Computer has a single public key, which enables any device to verify the authenticity of artifacts generated by the Internet Computer, even smart watches and mobile phones. + + + + +Interface Specification, for a deeply technical document that provides an overview of the lower-level external interfaces of the Internet Computer + + +Internet Computer Dashboard, to monitor real-time metrics around the Internet Computer network + + +
+
\ No newline at end of file diff --git a/modules/languages/pages/languages-overview.xml b/modules/languages/pages/languages-overview.xml new file mode 100644 index 000000000..20fb09a94 --- /dev/null +++ b/modules/languages/pages/languages-overview.xml @@ -0,0 +1,58 @@ + + + +
+ +Languages and API reference +2021-05-09 + +The Languages and API reference information is intended for advanced programmers or system architects who want more details about the lower level structures, libraries, and modules that support the higher-level developer tools. +
+{proglang} + + +Motoko Language Guide + + +Motoko Base Library + + +Motoko Language Quick Reference + + +
+
+Candid + + +Candid Guide + + +Candid specification + + +Candid crate + + +
+
+Rust + + +Introduction to working with Rust + + +{IC} Type Library (ic-types) + + +{IC} Agent Library (ic-agent) + + +{IC} Canister Development Kit (ic-cdk) + + +Rust Canister Development Kit (CDK) examples + + +
+
\ No newline at end of file diff --git a/modules/languages/pages/motoko-at-a-glance.xml b/modules/languages/pages/motoko-at-a-glance.xml new file mode 100644 index 000000000..4ebe6e7ce --- /dev/null +++ b/modules/languages/pages/motoko-at-a-glance.xml @@ -0,0 +1,579 @@ + + + +
+ +Motoko at-a-glance +2021-08-05 + +This summary provides a simple but comprehensive overview of Motoko with examples of key features to help you identify operations and patterns that you might know in other languages and what they look like in Motoko. +
+Motoko motivation and goals +A simple, useful language for DFINITY and the {platform}. + + +Familiar syntax + + +Safe by default + + +Incorporates smart contracts using the canister model + + +Provides seamless integration of DFINITY and the {platform} features + + +Makes the most of present and future WebAssembly + + +
+
+Key design points +Motoko takes inspiration from several programming languages, including Java, JavaScript, C#, Swift, Pony, ML, Haskell. + + +Object-oriented, functional, and imperative + + +Objects as records of members + + +async/await for sequential programming of asynchronous messaging + + +Structural typing with simple generics and subtyping + + +Safe arithmetic (unbounded and checked) + + +Non-nullable types by default + + +JavaScript-like syntax but statically typed and sane + + +
+
+Semantics + + +call-by-value (like Java, C, JS, and ML; unlike Haskell and Nix) + + +declarations are locally mutually recursive + + +parametric, bounded polymorphism + + +subtyping as subsumption, not coercion + + +no dynamic casts + + +no inheritance + + +
+
+Implementations + + +implemented in OCaml (leverages wasm library) + + +simple reference interpreter + + +less simple compiler to WebAssembly + + +multipass with typed IR in each pass + + +uniform representation, unboxed arithmetic + + +two-space gc, gc between messages + + +polymorphism by erasure + + +
+
+Language features +The next sections highlight Motoko programming language features in simplified form. +For additional information about using these and other features, see the Language quick reference in the ink:../language-guide/motoko.xml[Motoko Programming Language Guide]. +
+Expressions + + +identifiers such as x, foo_bar, test', List, Map + + +parentheses for grouping + + +type annotations to help type inference, for example (42 : Int) + + +
+
+Blocks and declarations + + +semi-colons are required after each declaration + + +mutually recursive + + +mutable variables marked explicitly + + +type Delta = Nat; +func print() { + Debug.print(Int.toText(counter)); +}; +let d : Delta = 42; +var counter = 1; +counter := counter + tmp; +print(); +
+
+Control flow +if and if - else +if (b) … +if (b) … else … +switch and case +switch x { case (pat1) e1; …; case _ en } +while and loop +while (b) … + +loop … +loop … while (b)` +for +for (pat in e) … +
+
+
+Primitive types +The next sections highlight the primitive types in the Motoko programming language. +
+Unbounded integers +Int + + +inferred by default for negative literals + + +literals: 13, 0xf4, -20, +1, 1_000_000 + + +
+
+Unbounded naturals +Nat + + +non-negative numbers, trap upon underflow + + +inferred by default for non-negative literals + + +literals: 13, 0xf4, 1_000_000 + + +
+
+Bounded numbers (trapping) +Nat8, Nat16, Nat32, Nat64, Int8, Int16, Int32, Int64 + + +trap on over- and underflow + + +need type annotations specified + + +literals: 13, 0xf4, -20, 1_000_000 + + +
+
+Floating point numbers +Float + + +IEEE 754 double precision (64 bit) semantics, normalized NaN + + +inferred for fractional literals + + +literals: 0, -10, 2.71, -0.3e+15, 3.141_592_653_589_793_12 + + +
+
+Numeric operations +operators behave as you would expect (no surprises) +a - b +a + b +a & b +
+
+Characters and text +Char, Text +Unicode, no random access +'x', '\u{\6a}', '☃' +"boo", "foo \u{\62}ar ☃" +"Concat" # "enation" +
+
+Booleans +Bool +literals: true, false +a or b +a and b +not b +if (b) e1 else e2 +
+
+
+Functions +The next sections provide examples for working with functions in the Motoko programming language. +
+Function types +simple functions +Int.toText : Int -> Text +multiple arguments and return values +divRem : (Int, Int) -> (Int, Int) +can be generic/polymorphic +Option.unwrapOr : <T>(?T, default : T) -> T +first-class (can be passed around, stored) +map : <A, B>(f : A -> B, xs : [A]) -> [B] +let funcs : [<T>(T) -> T] = … +
+
+Function declarations and use +func() { … } short for func() : () = { … } +parametric functions +type instantiations may sometimes be omitted +anonymous functions (a.k.a. lambdas) +func add(x : Int, y : Int) : Int = x + y; +func applyNTimes<T>(n : Nat, x : T, f : T -> ()) { + if (n == 0) return; + f(x); + applyNTimes(n-1, x, f); +} +applyNTimes<Text>(10, "Hello!", func(x) = { Debug.print(x) } ); +
+
+
+Composite types +The next sections provide examples for working with composite types in the Motoko programming language. +
+Tuples +(Bool, Float, Text) +immutable, heterogeneous, fixed size +let tuple = (true, 1.2, "foo"); +tuple.1 > 0.0; +let (_,_,t) = tuple; +
+
+Options +?Text +is either a value of that type, or null +func foo(x : ?Text) : Text { + switch x { + case (null) { "No value" }; + case (?y) { "Value: " # y }; + }; +}; +foo(null); +foo(?"Test"); +
+
+Arrays (immutable) +[Text] +let days = ["Monday", "Tuesday", … ]; +assert(days.len() == 7); +assert(days[1] == "Tuesday"); +// days[7] will trap (fixed size) +for (d in days.vals()) { Debug.print(d) }; +
+
+Arrays (mutable) +[var Nat] +let counters = [var 1, 2, 3]; +assert(counters.len() == 3); +counters[1] := counters[1] + 1; +// counters[3] will trap (fixed size) +
+
+Records +{name : Text; points : var Int} +let player = { name = "Joachim"; var points = 0 }; +Debug.print( + player.name # " has " # + Int.toText(player.points) # " points." +); +player.points += 1; +
+
+Objects +{ get : () → Int; add : Int → () } +different syntax, same type as records +object self { + var points = 0; // private by default + public func get() = points; + public func add(p : Int) { points += p }; +} +
+
+Variants +{ #invincible; #alive : Int; #dead } +similar to enumerated types +type Health = { #invincible; #alive : Nat; #dead }; +func takeDamage(h : Health, p : Nat) : Health { + switch (h) { + case (#invincible) #invincible; + case (#alive hp) { + if (hp > p) (#alive (hp-p)) else #dead + }; + case (#dead) #dead; + } +} +
+
+
+Packages and modules +The next sections provide examples for working with packages and modules in the Motoko programming language. +
+Modules + + +types and values like objects + + +restricted to static content (pure, no state, …) + + +// the type of base/Int.mo +module { + toText : Int -> Text; + abs : Int -> Nat; + … +} +
+
+Module imports + + +base package provides basic features + + +additional libraries evolving with community support + + +import Debug "mo:base/Debug"; +import Int "mo:base/Int"; +
+
+
+Platform features +The next sections provide examples of the Motoko programming language platform-specific features. +
+Actor types + + +like object types, but marked as actor: + + +sharable arguments and no or async result type. + + +“canister” ≈ “actor” + + +type Receiver = actor { recv : Text -> async Nat }; +type Broadcast = actor { + register : Receiver -> (); + send : Text -> async Nat; +} +
+
+Sharable ≈ serializable + + +all primitive types + + +records, tuples, arrays, variants, options with immutable sharable components + + +actor types + + +shared function type + + +The following are not sharable: + + +mutable things + + +local functions + + +objects (with methods) + + +
+
+Complete actor example +typical canister main file +import Array "mo:base/Array"; +actor { + var r : [Receiver] = []; + public func register(a : Receiver) { + r := Array.append(r, [a]); + }; + public func send(t : Text) : async Nat { + var sum := 0; + for (a in r.values()) { + sum += await a.recv(t); + }; + return sum; + }; +} +
+
+Async/await +async T + + +asynchronous future or promise + + +introduced by async { … } (implicit in async function declaration) + + +await e suspends computation pending `e’s result + + +
+
+Actor import +import Broadcast "ic:ABCDEF23"; +actor Self { + public func go() { + Broadcast.register(Self); + }; + public func recv(msg : Text) : async Nat { + … + } +} +
+
+Principal and caller +a Principal type represents the identity of a user or canister/actor +actor Self { + let myself : Principal = Principal.fromActor(Self); + public shared(context) func hello() : async Text { + if (context.caller == myself) { + "Talking to yourself is the first sign of madness"; + } else { + "Hello, nice to see you"; + }; + }; +} +
+
+
+Type system +The next sections highlight details about type system used in the Motoko programming language. +
+Structural +type definitions do not create types, but name existing types +type Health1 = { #invincible; #alive : Nat; #dead }; +type Health2 = { #invincible; #alive : Nat; #dead }; + +let takeDamage : (Health1, Nat) -> Health1 = …; +let h : Health2 = #invincible; +let h' = takeDamage(h, 100); // works +
+
+Subtyping +Mortal <: Health +type Health = { #invincible; #alive : Nat; #dead }; +type Mortal = { #alive : Nat; #dead }; + +let takeDamage : (Health, Nat) -> Health = …; +let h : Mortal = #alive 1000; +let h' = takeDamage(h, 100); // also works +t1 <: t2: t1 can be used wherever t2 is expected +
+
+Generic types +type List<T> = ?{head : T; tail : List<T>}; + +let l : List<Nat> = ?{head = 0; tail = ?{head = 1 ; tail = null }}; +
+
+
+Error handling +try … catch … + +throw … +
+
+Class declaration example +The following table compares class declarations in Motoko with class declarations in JavaScript and TypeScript. + + + + + + + + + +Motoko +JavaScript/TypeScript + + + + +class Counter(initValue:Nat) { + var _value = initValue; + public func get() : Nat { + _value + }; + func f(x: Nat) {}; +} +class Counter { + private _value; + constructor(initValue) { _value = initValue } + public get() { return _value } + private f(x) {} +} + + +class Foo() = Self { + func f() : Foo = Self +} + + + + + +
+
\ No newline at end of file diff --git a/modules/operators-guide/ops-nav.xml b/modules/operators-guide/ops-nav.xml new file mode 100644 index 000000000..1cb8d21fc --- /dev/null +++ b/modules/operators-guide/ops-nav.xml @@ -0,0 +1,28 @@ + + + +
+ +Untitled +2021-05-09 + + + +Operators + + +Concepts + + +How to + + +Tutorials + + +Reference + + + + +
\ No newline at end of file diff --git a/modules/operators-guide/pages/ops-guide.xml b/modules/operators-guide/pages/ops-guide.xml new file mode 100644 index 000000000..76bd461c1 --- /dev/null +++ b/modules/operators-guide/pages/ops-guide.xml @@ -0,0 +1,13 @@ + + + +
+ +Operators +2021-05-09 + +
+Operators +Welcome to the documentation for node providers and data center operators. +
+
\ No newline at end of file diff --git a/modules/quickstart/examples/vscode-plugin.xml b/modules/quickstart/examples/vscode-plugin.xml new file mode 100644 index 000000000..a36fce170 --- /dev/null +++ b/modules/quickstart/examples/vscode-plugin.xml @@ -0,0 +1,32 @@ + + + +
+ +Install the language editor plug-in +2021-05-09 + +
+Install the language editor plug-in +If you are planning to write a program using {proglang} and use Visual Studio Code (VSCode) as your editor, you can install the {proglang} language client plug-in for VSCode. +The {proglang} plug-in provides syntax highlighting, type information, and auto-completion features. +To install the plug-in: + + +Download and install Visual Studio Code, if it not already installed on your local computer. + + +Click View, then select Extensions. + + +Type motoko in the Search field. + + +Select the Motoko language support published by DFINITY Foundation, then click Install. + + +If your program has dependencies, you might also want to install the Vessel package manager for {proglang}. +For instructions, see the ReadMe. +To download the latest release, go to the vessel GitHub repository. +
+
\ No newline at end of file diff --git a/modules/quickstart/pages/local-quickstart.xml b/modules/quickstart/pages/local-quickstart.xml new file mode 100644 index 000000000..d72db379b --- /dev/null +++ b/modules/quickstart/pages/local-quickstart.xml @@ -0,0 +1,271 @@ + + + +
+ +Local development +2021-08-05 + +This Quick Start scenario assumes that you are installing the {sdk-short-name} for the first time and are running the Internet Computer as part of your local development environment. +To get started, let’s build and deploy a simple Hello application that has just one function—called greet. The greet function accepts one text argument and returns the result with a greeting similar to Hello, everyone! in a terminal if you run the application using the command-line or in an HTML page if you access the application in a browser. +
+Before you begin +Before you download and install this release of the {sdk-short-name}, verify the following: + + +You have an internet connection and access to a shell terminal on your local macOS or Linux computer. +Currently, the {sdk-short-name} only runs on computers with a macOS or Linux operating system. + + +You have node.js installed if you want to include the default template files for front-end development in your project. + + +This tutorial assumes you know how to perform common tasks—like opening a terminal and running commands—on your computer. +If you aren’t sure how to open a new terminal shell on your local computer or how to install node.js, see Preliminary steps for newcomers. +If you are comfortable meeting the prerequisites without instructions, continue to . +
+
+Download and install +You can download the latest version of the {sdk-long-name} directly from within a terminal shell on your local computer. +To download and install: + + +Open a terminal shell on your local computer. +For example, open Applications, Utilities, then double-click Terminal or press spacebar to open Search, then type terminal. + + +Download and install the {sdk-short-name} package by running the following command: +sh -ci "$(curl -fsSL https://sdk.dfinity.org/install.sh)" +This command prompts you to read and accept the license agreement before installing the DFINITY execution command-line interface (CLI) and its dependencies on your local computer. + + +Type y and press Return to continue with the installation. +The command displays information about the components being installed on the local computer. + + +
+
+Verify the SDK is ready to use +If the installation script runs without any errors, everything you need to start developing programs that run on the {platform} will be available on your local computer. +To verify the SDK is ready to use: + + +Open a terminal shell on your local computer, if you don’t already have one open. + + +Check that you have the DFINITY execution command-line interface (CLI) installed and the dfx executable is available in your PATH by running the following command: +dfx --version +The command displays version information for the dfx command-line executable similar to the following: +dfx 0.8.0 + + +Preview usage information for the other dfx command-line sub-commands by running the following command: +dfx --help +The command displays usage information for the dfx parent command and its subcommands. + + +
+
+Create a new project +Applications for the Internet Computer start as projects. +You create projects using the dfx parent command and its subcommands. +For this tutorial, we’ll start with the default sample application to illustrate creating an application using the starter files in a project. +When you create a new project, the dfx command-line interface adds a default project directory structure to your workspace. We cover the template files that make up a project directory in the Explore the default project tutorial. +To create a new project for your first application: + + +Open a terminal shell on your local computer, if you don’t already have one open. + + +Create a new project named hello by running the following command: +dfx new hello +The dfx new hello command creates a new hello project directory, template files, and a new hello Git repository for your project. +If you use a different project name instead of hello, make note of the name you used. You’ll need to use that project name in place of the hello project name throughout these instructions. + + +Change to your project directory by running the following command: +cd hello + + +
+
+Start the local network +Before you can build your first project, you need to connect to the Internet Computer network either running locally in your development environment or running remotely on a subnet that you can access. +These instructions assume you are running the Internet Computer locally. If you are connecting to an external Internet Computer network, you can skip this section. +As a best practice, this step requires you to have two terminal shells open, so that you can start and see network operations in one terminal and manage your project in another. +To start the network locally: + + +Open a new second terminal window or tab on your local computer. + + +Navigate to the root directory for your project, if necessary. +You should now have two terminals open with your project directory as your current working directory in both terminals. + + +Start the Internet Computer network on your local computer in your second terminal by running the following command: +dfx start +Depending on your platform and local security settings, you might see a warning displayed. +If you are prompted to allow or deny incoming network connections, click Allow. + + +Leave the terminal window that displays network operations open and switch your focus to the first terminal window where you created your new project. +You perform the remaining steps in the terminal that doesn’t display network operations. + + +
+
+Register, build, and deploy the application +After you connect to the Internet Computer network running locally in your development environment, you can register, build, and deploy your application locally. +To deploy your first application locally: + + +Check that you are still in the root directory for your project, if needed. + + +Ensure that node modules are available in your project directory, if needed, by running the following command: +npm install +For more information about this step, see Ensuring node is available in a project. + + +Register, build, and deploy your first application by running the following command: +dfx deploy +The dfx deploy command output displays information about the operations it performs. +For example, this step registers two network-specific identifiers—one for the hello main program and one for the hello_assets front-end user interface—and installation information similar to the following: +Creating a wallet canister on the local network. +The wallet canister on the "local" network for user "default" is "rwlgt-iiaaa-aaaaa-aaaaa-cai" +Deploying all canisters. +Creating canisters... +Creating canister "hello"... +"hello" canister created with canister id: "rrkah-fqaaa-aaaaa-aaaaq-cai" +Creating canister "hello_assets"... +"hello_assets" canister created with canister id: "ryjl3-tyaaa-aaaaa-aaaba-cai" +Building canisters... +Building frontend... +Installing canisters... +Creating UI canister on the local network. +The UI canister on the "local" network is "r7inp-6aaaa-aaaaa-aaabq-cai" +Installing code for canister hello, with canister_id rrkah-fqaaa-aaaaa-aaaaq-cai +Installing code for canister hello_assets, with canister_id ryjl3-tyaaa-aaaaa-aaaba-cai +Authorizing our identity (default) to the asset canister... +Uploading assets to asset canister... + /index.html 1/1 (573 bytes) + /index.html (gzip) 1/1 (342 bytes) + /index.js 1/1 (605692 bytes) + /index.js (gzip) 1/1 (143882 bytes) + /main.css 1/1 (484 bytes) + /main.css (gzip) 1/1 (263 bytes) + /sample-asset.txt 1/1 (24 bytes) + /logo.png 1/1 (25397 bytes) + /index.js.map 1/1 (649485 bytes) + /index.js.map (gzip) 1/1 (149014 bytes) +Deployed canisters. +If you created a project with a different name, however, your canister names will match your project name instead of hello and hello_assets. +You should also note that the first time you deploy, dfx creates a default identity and a local cycle wallet controlled by your default identity. +A cycles wallet is a special type of canister that enables you to transfer cycles to other canisters. +To deploy this sample application locally, you don’t need to know anything about your default developer identity, using a cycles wallet, or managing cycles. We’ll cover these topics later, but for now, just note that these are created for you automatically. + + +Call the hello canister and the predefined greet function by running the following command: +dfx canister call hello greet everyone +Let’s take a closer look at this example command: + + +The dfx canister call command requires you to specify a canister name and a method—or function—to call. + + +hello specifies the name of the canister you want to call. + + +greet specifies the name of the function you want to call in the hello canister. + + +everyone is the text data type argument that you want to pass to the greet function. + + +Remember, however, that if you created a project with a different name, the canister name will match your project name and you’ll need to modify the command line to match the name you used instead of hello. + + +Verify the command displays the return value of the greet function. +For example: +("Hello, everyone!") + + +
+
+Test the application front-end +Now that you have verified that your application has been deployed and tested its operation using the command line, let’s verify that you can access the front-end using your web browser. + + +Start the development server with npm start + + +Open a browser. + + +Navigate to http://localhost:8080/ + + +Navigating to this URL displays a simple HTML page with a sample asset image file, an input field, and a button. +For example: ++ + + + + +Sample HTML page + + + +Type a greeting, then click Click Me to return the greeting. +For example: + + + + +Hello + + + +
+
+Stop the local network +After testing the application in the browser, you can stop the local Internet Computer network so that it doesn’t continue running in the background. +To stop the local network: + + +In the terminal that displays development server, press Control-C to interrupt the development server process. + + +In the terminal that displays network operations, press Control-C to interrupt the local network process. + + +Stop the local Internet Computer network running on your local computer by running the following command: +dfx stop + + +
+
+Next steps +This Quick Start touched on only a few key steps to introduce the basic workflow for developing programs of your own. +You can find more detailed examples and tutorials to help you learn about how to use Motoko and how to develop applications to run on the Internet Computer throughout the documentation. +Here are some suggestions for where to go next: + + +Tutorials to explore building simple applications using a local development environment. + + +Convert ICP tokens to cycles if you have ICP tokens that you want to convert to cycles to enable you to deploy applications to the Internet Computer network. + + +Network deployment if you have cycles and are ready to deploy an application to the Internet Computer network. + + +What is Candid? to learn how the Candid interface description language enables service interoperability and composability. + + +Motoko at-a-glance to learn about the features and syntax for using Motoko. + + +
+
\ No newline at end of file diff --git a/modules/quickstart/pages/network-quickstart.xml b/modules/quickstart/pages/network-quickstart.xml new file mode 100644 index 000000000..9f241b7fc --- /dev/null +++ b/modules/quickstart/pages/network-quickstart.xml @@ -0,0 +1,385 @@ + + + +
+ +Network deployment +2021-08-05 + +This Quick Start scenario assumes that you are installing the {sdk-short-name} for the first time and deploying the default project on the Internet Computer running remotely. +If you are only deploying projects in a local development environment, see the Local development scenario. +To get started, let’s build and deploy a simple Hello application that has just one function—called greet. +The greet function accepts one text argument and returns the result with a greeting similar to Hello, everyone! in a terminal if you run the application using the command-line or in an HTML page if you access the application in a browser. +
+Before you begin +Before you download and install this release of the {sdk-short-name}, verify the following: + + +You have an internet connection and access to a shell terminal on your local macOS or Linux computer. +Currently, the {sdk-short-name} only runs on computers with a macOS or Linux operating system. + + +You have node.js installed if you want to access the default front-end for the default project. + + +You have ICP tokens or cycles available for you to use. +You must have cycles available to complete this tutorial. To get cycles, you must either convert ICP tokens to cycles or be provided cycles from another source, for example, from a canister controlled by another developer or from a third-party cycles provider. This tutorial assumes that you have an account with ICP tokens available and illustrates how to convert ICP tokens into cycles and transfer those cycles to a cycles wallet that you control. +For information about how to get ICP tokens, see How you can get ICP tokens. +For an introduction to using the Network Nervous System application to manage ICP tokens, see Network nervous system application quick start. +For information about using your default cycles wallet after you have created it, see Use the default cycles wallet. + + +This tutorial assumes you know how to perform common tasks—like opening a terminal and running commands—on your computer. +If you aren’t sure how to open a new terminal shell or how to install software packages like node.js, see Preliminary steps for newcomers. +If you are comfortable meeting the prerequisites without instructions, continue to . +
+
+Download and install +You can download the latest version of the {sdk-long-name} directly from within a terminal shell on your local computer. If you have previously installed the {sdk-short-name}, you can skip this section and start with Create a new project. +To download and install: + + +Open a terminal shell on your local computer. +For example, open Applications, Utilities, then double-click Terminal or press spacebar to open Search, then type terminal. + + +Download and install the {sdk-short-name} package by running the following command: +sh -ci "$(curl -fsSL https://sdk.dfinity.org/install.sh)" +This command prompts you to read and accept the license agreement before installing the DFINITY execution command-line interface (CLI) and its dependencies on your local computer. + + +Type y and press Return to continue with the installation. +The command displays information about the components being installed on the local computer. + + +
+
+Verify the SDK is ready to use +If the installation script runs without any errors, everything you need to start developing programs that run on the {platform} will be available on your local computer. +To verify the SDK is ready to use: + + +Open a terminal shell on your local computer, if you don’t already have one open. + + +Check that you have the DFINITY execution command-line interface (CLI) installed and the dfx executable is available in your PATH by running the following command: +dfx --version +The command displays version information for the dfx command-line executable similar to the following: +dfx 0.8.0 + + +Preview usage information for the other dfx command-line sub-commands by running the following command: +dfx --help +The command displays usage information for the dfx parent command and its subcommands. + + +
+
+Create a new project +Applications for the Internet Computer start as projects. +You create projects using the dfx parent command and its subcommands. +For this tutorial, we’ll start with the default sample application to illustrate creating an application using the starter files in a project. +When you create a new project, the dfx command-line interface adds a default project directory structure to your workspace. We cover the template files that make up a project directory in the Explore the default project tutorial. +To create a new project for your first application: + + +Open a terminal shell on your local computer, if you don’t already have one open. + + +Create a new project named hello by running the following command: +dfx new hello +The dfx new hello command creates a new hello project directory, template files, and a new hello Git repository for your project. +If you use a different project name instead of hello, make note of the name you used. You’ll need to use that project name in place of the hello project name throughout these instructions. + + +Change to your project directory by running the following command: +cd hello + + +
+
+Check the connection to the network +Before you can deploy your first project on the Internet Computer, you need to connect to the network gateway running remotely on a subnet that you can access. +There is a reserved network alias that you can use to access the Internet Computer running remotely on nodes in data centers. The network alias is a system setting that’s defined internally, so there’s nothing you need to configure in your projects by default. +To check your connection to the Internet Computer network: + + +Check that you are in the root directory for your project, if needed. + + +Check the current status of the Internet Computer network and your ability to connect to it by running the following command for the network alias ic: +dfx ping ic + + +Verify that the dfx ping ic command returns information about the Internet Computer network to which you are connecting. +For example, you should see output similar to the following: +{ + "ic_api_version": "0.18.0" "impl_hash": "d639545e0f38e075ad240fd4ec45d4eeeb11e1f67a52cdd449cd664d825e7fec" "impl_version": "8dc1a28b4fb9605558c03121811c9af9701a6142" "replica_health_status": "healthy" "root_key": [48, 129, 130, 48, 29, 6, 13, 43, 6, 1, 4, 1, 130, 220, 124, 5, 3, 1, 2, 1, 6, 12, 43, 6, 1, 4, 1, 130, 220, 124, 5, 3, 2, 1, 3, 97, 0, 129, 76, 14, 110, 199, 31, 171, 88, 59, 8, 189, 129, 55, 60, 37, 92, 60, 55, 27, 46, 132, 134, 60, 152, 164, 241, 224, 139, 116, 35, 93, 20, 251, 93, 156, 12, 213, 70, 217, 104, 95, 145, 58, 12, 11, 44, 197, 52, 21, 131, 191, 75, 67, 146, 228, 103, 219, 150, 214, 91, 155, 180, 203, 113, 113, 18, 248, 71, 46, 13, 90, 77, 20, 80, 95, 253, 116, 132, 176, 18, 145, 9, 28, 95, 135, 185, 136, 131, 70, 63, 152, 9, 26, 11, 170, 174] +} + + +
+
+Confirm your developer identity and ledger account +All ICP token transactions are recorded in a ledger canister running on the Internet Computer. +The ledger canister consists of account identifiers and balances for all ICP token holders. +Before you can transfer any ICP tokens you hold in your ledger account, you need to send a secure and properly-signed message that verifies your identity to the ledger and authorizes your developer identity to complete the transaction. +Depending on how you have set up custody for holding your ICP tokens, the hardware, software, and steps required to connect to the ledger and complete a transaction can vary. +For example, you might connect to the ledger and start a transaction from a hardware wallet, using a hardware security module (HSM) appliance, through the Network Nervous System (NNS) front-end application, or using the {sdk-short-name} dfx command-line interface. +Each approach presents a different interface for signing and sending messages to the ledger and representing your identity as an account holder. +
+About your developer identity +The first time you use the {sdk-short-name}, the dfx command-line tool creates a default developer identity for you. This identity is represented by a principal data type and a textual representation of the principal often referred to as your principal identifier. +This representation of your identity is similar to a Bitcoin or Ethereum address. +However, the principal associated with your developer identity is typically not the same as your account identifier in the ledger. The principal identifier and the account identifier are related—both provide a textual representation of your identity—but they use different formats. +
+
+Connect to the ledger to get account information +For the purposes of this tutorial—where there’s no hardware wallet or external application to connect to the ledger—we’ll use your developer identity to retrieve your ledger account identifier, then transfer ICP tokens from the ledger account identifier to a cycles wallet canister controlled by your developer identity. +To look up your account in the ledger: + + +Confirm the developer identity you are currently using by running the following command: +dfx identity whoami +In most cases, you should see that you are currently using default` developer identity. +For example: +default + + +View the textual representation of the principal for your current identity by running the following command: +dfx identity get-principal +This command displays output similar to the following: +tsqwz-udeik-5migd-ehrev-pvoqv-szx2g-akh5s-fkyqc-zy6q7-snav6-uqe + + +Get the account identifier for your developer identity by running the following command: +dfx ledger account-id +This command displays the ledger account identifier associated with your developer identity. +For example, you should see output similar to the following: +03e3d86f29a069c6f2c5c48e01bc084e4ea18ad02b0eec8fccadf4487183c223 + + +Check your account balance by running the following command: +dfx ledger --network ic balance +This command displays the ICP token balance from the ledger account. +For example, you should see output similar to the following: +10.00000000 ICP + + +
+
+
+Convert ICP tokens to cycles +Now that you have confirmed your account information and current ICP token balance, you can convert some of those ICP tokens to cycles and move them into a cycles wallet. +To transfer ICP tokens to create a cycles wallet: + + +Create a new canister with cycles by transferring ICP tokens from your ledger account by running a command similar to the following: +dfx ledger --network ic create-canister <principal-identifier> --amount <icp-tokens> +This command converts the number of ICP tokens you specify for the --amount argument into cycles, and associates the cycles with a new canister identifier controlled by the principal you specify. +For example, the following command converts .25 ICP tokens into cycles and specifies the principal identifier for the default identity as the controller of the new canister: +dfx ledger --network ic create-canister tsqwz-udeik-5migd-ehrev-pvoqv-szx2g-akh5s-fkyqc-zy6q7-snav6-uqe --amount .25 +If the transaction is successful, the ledger records the event and you should see output similar to the following: +Transfer sent at BlockHeight: 20 +Canister created with id: "gastn-uqaaa-aaaae-aaafq-cai" + + +Install the cycles wallet code in the newly-created canister placeholder by running a command similar to the following: +dfx identity --network ic deploy-wallet <canister-identifer> +For example: +dfx identity --network ic deploy-wallet gastn-uqaaa-aaaae-aaafq-cai +This command displays output similar to the following: +Creating a wallet canister on the ic network. +The wallet canister on the "ic" network for user "default" is "gastn-uqaaa-aaaae-aaafq-cai" + + +
+
+Validate your cycles wallet +After you convert ICP tokens to cycles, you can validate the cycles wallet canister and check your current cycles balance. +To validate your cycles wallet: + + +Verify the canister identifier for the cycles wallet you deployed by running the following command: +dfx identity --network ic get-wallet +The command displays the canister identifier for your cycles wallet with output similar to the following: +gastn-uqaaa-aaaae-aaafq-cai + + +Check that your cycles wallet canister is properly configured and holds a balance of cycles by running a command similar to the following: +dfx wallet --network ic balance +The command returns the balance for the your cycles wallet. +For example: +15430122328028812 cycles. +You can also access your default cycles wallet in a web browser by using a URL similar to the following: +https://<WALLET-CANISTER-ID>.raw.ic0.app +The first time you access the application, you see a notice that you are using an Anonymous Device and are prompted to authenticate your identity, authorize access to the wallet, and register your device. + + +Click Authenticate to continue to the Internet Identity service. + + +Enter your User Number if you have previously registered an identity or register with the service as a new user. +For more information about the Internet Identity service and how to register multiple authentication devices and methods, see How to use the Internet Identity service. + + +Authenticate using your user number and the authentication method—for example, a security key or fingerprint—you have registered. + + +Click Proceed to access to the default cycles wallet application. + + +Register the device you are using for this session by copying the command displayed in the Register Device page and running it in a terminal. +For example, call the authorize method for the cycles wallet canister with a command similar to the following: +dfx canister --no-wallet --network ic call "gastn-uqaaa-aaaae-aaafq-cai" authorize '(principal "ejta3-neil3-qek6c-i7rdw-sxreh-lypfe-v6hjg-6so7x-5ugze-3iohr-2qe")' +Be sure that the command you copy has the --no-wallet option and the correct network (ic) alias. +You should recognize the canister identifier—in this example, gastn-uqaaa-aaaae-aaafq-cai—as the cycles wallet associated with your identity. +If this is your first wallet on the network, however, you might not recognize the principal being authorized. The use of a different principal is the expected behavior in this case. +When the browser refreshes after running the authorize command, the cycles wallet for your principal account is displayed. + + +View your cycles balance and activity in the browser. +For example: + + + + + +cycles wallet + + +For more information about the commands and methods available for working with the default cycles wallet, see Use the default cycles wallet. + + +
+
+Register, build, and deploy the application +After you have validated your cycles wallet balance, you can register, build, and deploy your sample application. +To deploy your first application on the Internet Computer: + + +In your terminal shell, check that you are still in the root directory for your project. + + +Ensure that node modules are available in your project directory, if needed, by running the following command: +npm install +For more information about this step, see Ensuring node is available in a project. + + +Register, build, and deploy your first application by running the following command: +dfx deploy --network ic +The --network option specifies the network alias or URL for deploying the application. +This option is required to install on the Internet Computer running remotely. +The dfx deploy command output displays information about the operations it performs. +For example, this step registers two network-specific identifiers—one for the hello main program and one for the hello_assets front-end user interface—and installation information similar to the following: +Deploying all canisters. +Creating canisters... +Creating canister "hello"... +"hello" canister created on network "ic" with canister id: "5o6tz-saaaa-aaaaa-qaacq-cai" +Creating canister "hello_assets"... +"hello_assets" canister created on network "ic" with canister id: "5h5yf-eiaaa-aaaaa-qaada-cai" +Building canisters... +Building frontend... +Installing canisters... +Installing code for canister hello, with canister_id 5o6tz-saaaa-aaaaa-qaacq-cai +Installing code for canister hello_assets, with canister_id 5h5yf-eiaaa-aaaaa-qaada-cai +Authorizing our identity (default) to the asset canister... +Uploading assets to asset canister... + /index.html 1/1 (472 bytes) + /index.html (gzip) 1/1 (314 bytes) + /index.js 1/1 (260215 bytes) + /index.js (gzip) 1/1 (87776 bytes) + /main.css 1/1 (484 bytes) + /main.css (gzip) 1/1 (263 bytes) + /sample-asset.txt 1/1 (24 bytes) + /logo.png 1/1 (25397 bytes) + /index.js.map 1/1 (842511 bytes) + /index.js.map (gzip) 1/1 (228404 bytes) + /index.js.LICENSE.txt 1/1 (499 bytes) + /index.js.LICENSE.txt (gzip) 1/1 (285 bytes) +Deployed canisters. +If you didn’t convert enough ICP tokens to cycles to complete the operation, you can add cycles to your cycles wallet by running a command similar to the following: +dfx ledger --network ic top-up gastn-uqaaa-aaaae-aaafq-cai --amount 1.005 +This command converts an additional 1.005 ICP tokens to cycles for the gastn-uqaaa-aaaae-aaafq-cai cycles wallet identifier. +The command returns output similar to the following: +Transfer sent at BlockHeight: 81520 +Canister was topped up! + + +Call the hello canister and the predefined greet function by running the following command: +dfx canister --network ic call hello greet '("everyone": text)' +Let’s take a closer look at this example: + + +Using the --network ic option indicates that the canister you want to call is deployed on the ic network. The ic network alias is an internally-reserved alias for accessing the Internet Computer. + + +Note that the --network ic option must precede the operation subcommand, which, in this case, is the dfx canister call command. + + +The hello argument specifies the name of the canister you want to call. + + +The greet argument specifies the name of the function you want to call in the hello canister. + + +The text string everyone is the argument that you want to pass to the greet function. + + + + +Verify the command displays the return value of the greet function. +For example: +("Hello, everyone!") + + +Rerun the dfx wallet balance command or refresh the browser to see your new cycle balance and recent activity. + + +
+
+Test the application front-end +Now that you have verified that your application has been deployed and tested its operation using the command line, let’s verify that you can access the front-end using your web browser. +To access the application front-end: + + +Open a browser. + + +Navigate to the front-end for the application using a URL that consists of the hello_assets identifier and the boundary.ic0.app suffix. +If you didn’t make a note of the canister identifier, you can look it up by running the following command: +dfx canister --network ic id hello_assets +For example, the full URL should look similar to the following: +https://gsueu-yaaaa-aaaae-aaagq-cai.raw.ic0.app +Navigating to this URL displays the HTML entry page for the template application. +For example: + + + + +HTML page with prompt + + + +Type a greeting, then click Click Me to return the greeting. + + +
+
+Next steps +Now that you have seen how to deploy an application on the Internet Computer network, you are ready to develop and deploy programs of your own. +You can find more detailed examples and tutorials to help you learn about how to use Motoko and how to develop applications for the Internet Computer throughout the documentation. +Here are some suggestions for where to go next: + + +Tutorials to explore building front-end and back-end applications in a local development environment. + + +What is Candid? to learn how the Candid interface description language enables service interoperability and composability. + + +Motoko at-a-glance to learn about the features and syntax for using Motoko. + + +
+
\ No newline at end of file diff --git a/modules/quickstart/pages/newcomers.xml b/modules/quickstart/pages/newcomers.xml new file mode 100644 index 000000000..e3ee94984 --- /dev/null +++ b/modules/quickstart/pages/newcomers.xml @@ -0,0 +1,130 @@ + + + +
+ +Preliminary steps for newcomers +2021-08-05 + +If this is the first time you are installing developer tools on your computer, you might need to take a few extra steps to prepare your environment. +However, there are often multiple ways to perform each of these tasks. +If you need more help than provided here, see the documentation for the operating system you are using. + +The instructions here assume that you are using a macOS computer. +If you have a Linux development environment, the steps to follow depend on the specific Linux distribution and version you use. + +Before you install the {sdk-short-name}, you need to know: + + +How to open and run commands in a terminal + + +How to check for and install packages and dependencies + + +How to create and navigate to new directories + + +How to view and update your PATH on the platform you use + + +The steps in this section describe how to prepare a basic development environment. +
+Open a terminal +You need to know how to open a terminal and navigate to directories to install the {sdk-short-name} and to start and stop the {IC} running locally when trying any of the tutorials. +To open the Terminal application on macOS: + + +Open the Finder. + + +Click Applications, open Utilities, then double-click Terminal. +Alternatively, you can press the spacebar keyboard keys to open Search, then type terminal. +The terminal is where you are going to execute command-line instructions. +To execute a command, you type or copy and paste an instruction, then press Return. + + +Check your current path by running the print working directory–pwd—command, then pressing Return. +pwd +This command displays your current directory with a path like /Users/<your-user-name>. +After you open the Terminal application, you can open new terminal shell at any time by clicking Shell, then selecting New Window or New Tab. +By default, a new terminal shell always opens in your home directory with a path like /Users/<your-user-name>. + + +
+
+Check for packages +The Homebrew application is a package manager for macOS that makes it easy to install and update packages—that is, external programs—that you need to have available in a local development environment. +The node.js package provides a JavaScript runtime environment and modules for front-end user interface development. +The node.js package is not required to build programs, but you’ll probably need it if you want to add a graphical user interface to your program. + +If your development environment is Linux, you can use a package manager of your choice instead of Homebrew to install packages and manage dependencies. + +To check and install packages: + + +Check whether you have the Homebrew package manager installed by running the following command: +brew --version +If the command returns version information, continue to the next step. +If Homebrew isn’t installed, copy and paste the following command in your terminal: +/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" + + +Check whether you have the node.js package manager installed by running the following command: +node --version +If the command returns version information, continue to . +If node.js isn’t installed, copy and paste the following command in your terminal: +brew install node + + +
+
+Create a working folder +By default, a new terminal shell always opens in your home directory with a path like /Users/<your-user-name>. +To keep your workspace tidy, you can create a separate folder for your {IC} projects. +Creating a working folder for {IC} projects is optional, but can make it easier to find and navigate between projects. +A separate folder is especially useful if you plan to experiment with any of the tutorials beyond the Quick start. +To create a new working folder: + + +Open a terminal shell on your local computer, if you don’t already have one open. + + +Create a new folder called ic-projects in your home directory by running the following command: +mkdir ic-projects + + +Change to the new working folder by running the following command: +cd ic-projects + + +
+
+View directories in your PATH +The PATH environment variable is an important setting that your operating system uses to locate +the set of directories where executable programs are located. +Because every operating system has its own set of directories where it expects to find programs, you need to know how to view and update the PATH environment variable so that you can verify that the {sdk-short-name} command-line executable—dfx—is in one of the directories listed. +On macOS computers, the default location for the dfx executable is /usr/local/bin and this directory is typically included in the default set of paths. +Therefore, updating the PATH variable is usually not necessary for computers running macOS. +If you are using a Linux distribution, however, you should know how to do the following: + + +Verify the location of the dfx executable. + + +View the set of directories in your current PATH. + + +Update the PATH environment variable, if necessary. + + +On most operating systems, you can run a command similar to the following to view the set of directories in your current PATH: +export $PATH +To check the location of the dfx executable after you install the {sdk-short-name}, you might run a command similar to the following: +which dfx +If the dfx executable is not in one of the directories listed in your current $PATH, you need to move the executable or update the PATH setting. +The specific steps for updating the PATH depend on your operating system, but, in many cases, you can run a command similar to the following and specifying the appropriate directory, such as ~/bin: +export PATH=<path-to-directory-for-dfx> +Now you’re ready to install the {sdk-short-name} and get coding! +
+
\ No newline at end of file diff --git a/modules/quickstart/pages/quickstart-intro.xml b/modules/quickstart/pages/quickstart-intro.xml new file mode 100644 index 000000000..bfb8fedf7 --- /dev/null +++ b/modules/quickstart/pages/quickstart-intro.xml @@ -0,0 +1,61 @@ + + + +
+ +Quick start +2021-08-05 + +This {sdk-long-name} provides tools, sample code, and documentation to help you create programs to run on the Internet Computer. +The Quick Start tutorial assumes that you are installing the {sdk-short-name} for the first time and illustrates how to create, build, and deploy your first application. +To keep the instructions simple and focused on the task at hand, the Quick start is split into two scenarios: + + +In the Local development scenario, you create and deploy the sample application with Internet Computer processes that run locally to simulate connecting to the network. + + +In the Network deployment scenario, you create the sample application locally but connect to the Internet Computer running remotely on computers in an external data center. + + +If you need some help setting up your development environment—for example, if you aren’t sure how to open a new terminal, install packages, or create folders and navigate between directories—you might want to start with the Preliminary steps for newcomers. +
+Default application +Both scenarios build and deploy a simple Hello application that has just one function—called greet. The greet function accepts one text argument and returns the result with a greeting similar to Hello, everyone! in a terminal if you run the application using the command-line or in an alert pop-up window if you access the application in a browser. +The default application consists of back-end code written in Motoko, a programming language specifically designed for interacting with the Internet Computer, and a simple webpack-based front-end. +
+
+Getting ICP tokens and cycles +As discussed in Tokens and cycles, cycles are required to power canister operations for applications running on the Internet Computer. +As a developer, you have a few different options for acquiring and managing cycles for your applications: + + +Purchase or claim ICP tokens through an exchange that lists ICP tokens available for trade, then convert your tokens to cycles using the {sdk-short-name} command-line interface or the Network Nervous System application. + + +Register for cycles by signing up for an account or cycles wallet through a provider offering those services. + + +Coordinate with other developers to send and receive cycles directly to and from canisters through a cycles wallet or another application. + + +Because only canisters require and consume cycles—to perform operations and to pay for the resources they use—cycles are always transferred between canisters and not to users or developers. You can manage the distribution of cycles, however, through a cycles wallet created for you or using a similar application. +
+
+Want to learn more? +If you are looking for more information before getting started or want to view a demonstration of how to deploy before you try it for yourself, check out the following related resources: + + +How you can use ICP tokens (overview) + + +Building on the Internet Computer: Fundamentals (video) + + +What is the DFINITY Canister SDK (video) + + +Deploying your first application (video) + + +
+
\ No newline at end of file diff --git a/modules/release-notes/pages/0.6.20-rn.xml b/modules/release-notes/pages/0.6.20-rn.xml new file mode 100644 index 000000000..479adf4b3 --- /dev/null +++ b/modules/release-notes/pages/0.6.20-rn.xml @@ -0,0 +1,85 @@ + + + +
+ +Highlights of what’s new in 0.6.20 +2021-08-05 + +The 0.6.20 release has both user-facing and internal enhancements, including fixes and updates to Motoko, the Motoko base library, and Candid. +
+New features and capabilities +The most significant new features and capabilities include updates in the following functional areas: + + +DFX + + +Candid + + +Motoko + + +
+DFX + + +A new notification message that the DFINITY Canister SDK sends anonymous usage data to DFINITY Stiftung by +default has been added to dfx commands. +The notification message is only displayed once, the first time you run any dfx subcommand. +For example, the first time you run dfx new to create a new project, the notification is displayed before any other project creation messages. +The purpose of this notification is to inform you that dfx is configured to collect anonymous information about dfx command activity and errors. +Collecting anonymous data is enabled by default in an effort to improve the developer experience based on usage patterns and behavior. +If you want to prevent the collection of data about dfx usage, you can explicitly opt-out by setting the following environment +variable: +DFX_TELEMETRY_DISABLED=1 +To find out more about the data collected and what your consent means, see the DFINITY Canister SDK Terms and Conditions. + + +The dfx commands that support the --network option have been updated to support URLs when specifying the network value. +Previously, the --network option required you to specify a network name that matched a network aliases configured in the project’s dfx.json file. + + +
+
+Candid +The Candid web interface has been updated to provide easier navigation and a better user experience. +The updates to the Candid web interface include the following new features and improvements: + + +A new Console drawer provides quick access to method output and a list of all available methods as links for fast navigation. + + +Canister methods and their related form elements are more clearly separated and annotated. + + +Method output is selectable and easier to toggle between text, UI, and JSON formats. + + +The layout is now responsive to provide an optimized display when viewing service using mobile devices or other media. + + +
+
+Motoko + + +The Motoko base documentation examples are now executable in the browser. + + +The Motoko compiler supports specifying command-line arguments using --args <file> and --args0 <file>. +The new options enable the compiler to read newline and NUL terminated arguments from a specified file name. + + +
+
+
+Issues fixed in this release +This section covers any reported issues that have been fixed in this release. +
+
+Known issues and limitations +This section covers any known issues or limitations that might affect how you work with the {sdk-short-name} in specific environments or scenarios. +
+
\ No newline at end of file diff --git a/modules/release-notes/pages/0.6.21-rn.xml b/modules/release-notes/pages/0.6.21-rn.xml new file mode 100644 index 000000000..470c0d89b --- /dev/null +++ b/modules/release-notes/pages/0.6.21-rn.xml @@ -0,0 +1,60 @@ + + + +
+ +Highlights of what’s new in 0.6.21 +2021-08-05 + +The 0.6.21 release primarily consists of changes to support new features that are not yet complete, including fixes and updates to DFX commands, Motoko, the Motoko base library, and Candid. +
+New features and capabilities +The most significant new features and capabilities include updates in the following functional areas: + + +DFX + + +Candid + + +Motoko + + +
+DFX + + +Two new subcommands—get-wallet and set-wallet—have been added to the dfx identity command to support working with wallet canisters. +In a future release, you will be able to use these commands locally for testing purposes. However, the commands are not currently supported on any version of the Internet Computer network available for you to run locally or on the public Internet Computer network. + + +
+
+Candid + + +Candid changelog + + +
+
+Motoko + + +The Motoko compiler now reports errors and warnings with an additional error code. +You can use the error code to look up a more detailed description for a given error by passing the --explain flag with a code to the compiler. +Note that detailed descriptions are not yet available for most error codes and will be added incrementally in upcoming releases. + + +
+
+
+Issues fixed in this release +This section covers any reported issues that have been fixed in this release. +
+
+Known issues and limitations +This section covers any known issues or limitations that might affect how you work with the {sdk-short-name} in specific environments or scenarios. +
+
\ No newline at end of file diff --git a/modules/release-notes/pages/0.6.22-rn.xml b/modules/release-notes/pages/0.6.22-rn.xml new file mode 100644 index 000000000..d06b5a945 --- /dev/null +++ b/modules/release-notes/pages/0.6.22-rn.xml @@ -0,0 +1,78 @@ + + + +
+ +Highlights of what’s new in 0.6.22 +2021-08-05 + +The 0.6.22 release consists of changes to support new features that are not yet complete, including fixes and updates to DFX commands, Motoko, the Motoko base library, and Candid. +
+New features and capabilities +The most significant new features and capabilities include updates in the following functional areas: + + +DFX + + +Sample applications + + +Candid + + +Motoko + + +
+DFX + + +The dfx canister call command can now pass a randomly-generated value to a canister method when an argument is required but not provided. + + +The dfx canister call command can take canister identifiers for local canisters even if the canister is installed on a remote network. + + +The dfx replica command has been fixed so that it does not attempt to write the replica pid to a nonexistent directory. + + +The default webpack.config.js file used when you create new projects has been modified to comment out the configuration to enable TypeScript. +Previously, the webpack.config.js file configured ts-loader to process files with the .js file extension, which could lead to errors. +This configuration is now disabled by default and the commented-out configuration only processes .ts, .tsx, and .jsx files through ts-loader. + + +
+
+Sample applications + + +There have been updates, improvements, and new sample applications added to the examples repository. +All of Motoko sample apps in the examples repository have been updated to work with the latest release of the {sdk-short-name}. +There are also new sample apps to illustrate using arrays (Quicksort) and building create/read/update/delete (CRUD) operations for a web application Superheroes. + + +The LinkedUp sample application has been updated to work with the latest release of Motoko and the SDK. + + +
+
+Candid + + +Candid changelog + + +
+
+Motoko + + +The Motoko compiler now reports errors and warnings with an additional error code. +You can use the error code to look up a more detailed description for a given error by passing the --explain flag with a code to the compiler. +Note that detailed descriptions are not yet available for most error codes and will be added incrementally in upcoming releases. + + +
+
+
\ No newline at end of file diff --git a/modules/release-notes/pages/0.6.23-rn.xml b/modules/release-notes/pages/0.6.23-rn.xml new file mode 100644 index 000000000..87197800e --- /dev/null +++ b/modules/release-notes/pages/0.6.23-rn.xml @@ -0,0 +1,15 @@ + + + +
+ +Highlights of what’s new in 0.6.23 +2021-08-05 + +The 0.6.23 release consists of changes to support new features and enhancements that are not yet complete. +
+New features and capabilities +The most significant new feature enables you to use a locally-installed @dfinity/bootstrap server. +For information about updates to Candid, see the Candid changelog. +
+
\ No newline at end of file diff --git a/modules/release-notes/pages/0.6.24-rn.xml b/modules/release-notes/pages/0.6.24-rn.xml new file mode 100644 index 000000000..1e986b493 --- /dev/null +++ b/modules/release-notes/pages/0.6.24-rn.xml @@ -0,0 +1,145 @@ + + + +
+ +Highlights of what’s new in 0.6.24 +2021-08-05 + +The 0.6.24 release primarily consists of changes to support new features that are not yet complete, including fixes and updates to DFX commands, Motoko, the Motoko base library, and Candid. +
+New features and capabilities +The most significant new features and capabilities include updates in the following functional areas: + + +DFX + + +Candid + + +Motoko + + +
+DFX + + +With this release, you must have a wallet canister with cycles to deploy or manage applications on the Internet Computer. +For local development, dfx automatically creates a wallet for you when you run dfx canister create or dfx deploy commands within each project. +Wallets are also created automatically if you deploy to the Internet Computer using the ic network alias before the network is upgraded to require a cycle balance. +To deploy and manage applications on the main Internet Computer network, you must provide the DFINITY Foundation with a principal associated with your user identity and receive a wallet canister identifier in return. +To deploy applications on the Internet Computer network: + + +Download and install the {sdk-short-name}. + + +Run the dfx identity get-principal command to create your default identity and principal: +dfx identity get-principal +Running the command displays output similar to the following: +Creating the "default" identity. + - generating new key at /Users/pubs/.config/dfx/identity/default/identity.pem +Created the "default" identity. +wre5u-xietp-k5jz4-sdaaz-g3x4l-zjzxa-lxnly-fp2mk-j3j77-25qat-pqe + + +Run the dfx identity set-wallet command to associate your wallet canister identifier with your default identity. +dfx identity set-wallet <wallet-canister-identifier> + + +Open the wallet application in a web browser by navigating to the canister with a URL similar to the following: +https://<WALLET-CANISTER-ID>.ic0.app + + + + +A new command-line option enables you to specify the number of initial cycles to transfer to a newly-created canister. +The dfx canister create and dfx deploy commands now support a new --with-cycles <number-of-cycles> option. +This option allows you to specify the initial cycle balance of a canister created by your wallet. +You can use this option when running the Internet Computer network locally or connected to the current ic network (Sodium) for testing purposes. However, because wallets and cycle balances are not currently used for canisters you create while connected to the current ic network (Sodium), the --with-cycles option does not affect any canister operations. +For example, you might run the following dfx canister create command to initialize 8000000000 cycles for all of the canisters in a project: +dfx canister create --with-cycles 8000000000 --all +If using dfx deploy, you might run the following command to initialize 8000000000 cycles for the backend canister in a project: +dfx deploy --with-cycles 8000000000 backend + +You must have a wallet canister with a cycles balance on the network where you want to create or deploy additional canisters. + + + +You can now use the new dfx toolchain command to manage the version of the dfx command-line interface you are using for your projects. +The dfx toolchain command enables you to install, uninstall, and set the default version of dfx that you want to use. +You can specify the version by the complete version number, the major and minor version number, or a tag name. +For example: +dfx toolchain install 0.6.24 # complete version +dfx toolchain install 0.6 # major minor version +dfx toolchain install latest # tag name + + +A new deploy-wallet subcommand enables you to specify the canister identifier for your cycles wallet WebAssembly module (WASM). +For example, if you have an account with a third party exchange provider and receive a wallet canister identifier, you can run a command similar to the following to deploy the wallet and uses its cycles for development: +dfx identity deploy-wallet <canister-identifier> + +The deploy-wallet feature is intended for a future use case. The command is only applicable if you received the wallet canister identifier as part of a transfer operation that converted ICP tokens to cycles. +In addition, the deploy-wallet subcommand is not intended for use with the current version of Internet Computer running locally or on the remote network. + + + +
+
+Candid + + +New Candid documentation for developers provides type mapping information for Rust and JavaScript. + + +Candid now supports additional native Rust types and Typescript. + + +For additional information, see the Candid changelog. + + +
+
+Motoko + + +The Motoko compiler (moc) now accepts the -Werror flag to turn warnings into errors. + + +The language server now returns documentation comments alongside +completions and hover notifications. + + +Motoko supports wrapping arithmetic and bit-wise operations on NatN and IntN. +The conventional arithmetic operators on NatN and IntN trap on overflow. +If wrap-around semantics is desired, the operators +%, -%, % and *% can be used. The corresponding assignment operators (+%= etc.) are also available. +Likewise, the bit fiddling operators (&, |, ^, <<, >>, <<>,<>> etc.) are now also available on NatN and IntN. The right shift operator (>>) is an unsigned right shift on NatN and a signed right shift on IntN; the +>> operator is not available on these types. +The motivation for this change is to eventually deprecate and remove the +WordN types. +Therefore, the wrapping arithmetic operations on WordN are deprecated and their use will print a warning. +For information about replacing Word types, see Word types. + + +For values x of type Blob, an iterator over the elements of the blob x.vals() is introduced. +It works like x.bytes(), but returns the elements as type Nat8. + + +The base library documentation tool mo-doc now generates cross-references for types in signatures. +With this enhancement, when you view a signature like fromIter : I.Iter<Nat> → List.List<Nat>, you can click I.Iter or List.List to navigate to the appropriate definition. + + +Improvements to the type checker and compiler provide better handling for object literals. + + +
+
+
+Issues fixed in this release +This section covers any reported issues that have been fixed in this release. +
+
+Known issues and limitations +This section covers any known issues or limitations that might affect how you work with the {sdk-short-name} in specific environments or scenarios. +
+
\ No newline at end of file diff --git a/modules/release-notes/pages/0.6.25-rn.xml b/modules/release-notes/pages/0.6.25-rn.xml new file mode 100644 index 000000000..703b4d768 --- /dev/null +++ b/modules/release-notes/pages/0.6.25-rn.xml @@ -0,0 +1,40 @@ + + + +
+ +Highlights of what’s new in 0.6.25 +2021-08-05 + +The 0.6.25 release primarily consists of changes to support new features that are not yet complete, including fixes and updates to DFX commands, Motoko, the Motoko base library, and Candid. +
+New features and capabilities +The most significant new features and capabilities include the following updates: + + +This release introduces environment variables for specifying canister identifiers. +You can now use the CANISTER_ID_{canister.name} and CANISTER_CANDID_PATH_{canister.name} +environment variables to reference canister identifiers and the path to the canister Candid description (.did file) during the build process. +These environment variables enable you to construct the JavaScript for front-end assets using the correct canister identifiers. +The environment variables are intended to replace the import syntax for dependent canisters described in Entry and output configuration which is being deprecated and will be removed in a future release. + + +A new dfx identity import subcommand enables you to import a security certificate to create an identity. +For example, if you use a hardware wallet or a key generation utility to generate a PEM file for authenticating your identity, you can now import that PEM file into dfx to create a new identity. +After importing the PEM file, you can run the dfx identity use command to set that identity as your default context. +For example, to import the my-external-id.pem and create an identity named alice, you would run the following command: +dfx identity import alice my-external-id.pem +After running this command, you would run the following command to begin using the new identity: +dfx identity use alice + + +
+
+Issues fixed in this release +This section covers any reported issues that have been fixed in this release. +
+
+Known issues and limitations +This section covers any known issues or limitations that might affect how you work with the {sdk-short-name} in specific environments or scenarios. +
+
\ No newline at end of file diff --git a/modules/release-notes/pages/0.6.26-rn.xml b/modules/release-notes/pages/0.6.26-rn.xml new file mode 100644 index 000000000..125e5bce5 --- /dev/null +++ b/modules/release-notes/pages/0.6.26-rn.xml @@ -0,0 +1,57 @@ + + + +
+ +Highlights of what’s new in 0.6.26 +2021-08-05 + +The 0.6.26 release primarily consists of changes to support new features that are not yet complete, including fixes and updates to DFX commands, Motoko, the Motoko base library, and Candid. +
+New features and capabilities +The most significant new feature included in this release is the publication of the Internet Computer Interface Specification. +The Internet Computer Interface Specification details many technical properties that describe the lower-level interfaces for interacting with the Internet Computer. +For example, the Internet Computer Interface Specification describes the HTTPS endpoints that are exposed to handle incoming requests and how low-level bindings enable canisters to interact with system components. +If you use existing tools—like the DFINITY Canister SDK or Canister Development Kit for Rust—to work with canisters, these tools interact with the lower-level interfaces described in the Internet Computer Interface Specification on your behalf. +If you want to create your own tooling for working with canisters, however, the Internet Computer Interface Specification includes the technical details you need to understand how the Internet Computer external interfaces work. +If you are interested in expanding the Internet Computer ecosystem, you’ll also find information in the Internet Computer Interface Specification to help you in developing the following types of projects: + + +Building front-end agents for user-facing interaction in any programming language, including popular languages such as Python, Golang, or C. + + +Building back-end Canister Development Kits (CDKs) in any language that can compile down to WebAssembly bytecode. + + +Building local development tools such as command line interfaces or Internet Computer emulators and debuggers. + + +Implementing features and enhancements to improve the developer experience for deploying and managing canisters running remotely on the network. + + +
+
+Issues fixed in this release +This section covers any reported issues that have been fixed in this release. +This release fixes an issue with memory allocation in the default cycles wallet that caused an error after creating and deploying canisters. +If you encountered this issue, you might have seen an error message similar to the following: +The Replica returned an error: code 5, message: "Canister 6dtaa-vaaaa-aaaab-aaipa-cai exceeded its allowed memory allocation" +This release updates the default cycles wallet to provide better handling of unused memory and how memory is allocated when creating and deploying canisters. +
+
+Known issues and limitations +This section covers any known issues or limitations that might affect how you work with the {sdk-short-name} in specific environments or scenarios. +
+Only the default wallet canister principal can perform canister management tasks +The introduction of the cycles wallet canister changes the default principal used to perform key canister management tasks, such as registering a new canister identifier and deploying a new canister on the Internet Computer. +This change introduces some inconsistencies in the identity used to perform certain tasks and can result in potential access control issues. +You should note that none of the tutorials have been updated to reflect this specific change in behavior yet and the current version of the Add access control with identities tutorial is known to be invalid for this release. +If you want to experiment with access control using the Add access control with identities tutorial, you should install the {sdk-short-name} version 0.6.23 (or older). +
+
+Incompatibility when using the JavaScript agent directly in a project +If you access the @dfinity/agent JavaScript agent directly in a project—that is, without going through the bootstrap server—you will not be able to import the bls certification scheme with the agent-js release. +If your application uses the JavaScript agent directly, you should use the latest version of the agent. +
+
+
\ No newline at end of file diff --git a/modules/release-notes/pages/0.7.0-rn.xml b/modules/release-notes/pages/0.7.0-rn.xml new file mode 100644 index 000000000..a45c5da9d --- /dev/null +++ b/modules/release-notes/pages/0.7.0-rn.xml @@ -0,0 +1,171 @@ + + + +
+ +Highlights of what’s new in 0.7.0 +2021-08-05 + +The 0.7.0 release primarily consists of changes to support new features that are not yet complete, including fixes and updates to DFX commands, Motoko, the Motoko base library, and Candid. +The most significant new features and capabilities are updates to the following: + + +DFX + + +Motoko + + +
+New features and capabilities +
+DFX + + +Addition of ledger subcommands +dfx now supports a dedicated dfx ledger subcommand. This allows you to interact with the ledger +canister installed on the Internet Computer. Example commands include dfx ledger account-id which +prints the Account Identifier associated with your selected identity, dfx ledger transfer which +allows you to transfer ICP from your ledger account to another, and dfx ledger create-canister which +allows you to create a canister from ICP. +For more information on dfx ledger subcommands, see dfx ledger. + + +Addition of wallet subcommands +dfx now supports a dedicated dfx wallet subcommand. This allows you to interact with the cycles wallet associated with your selected identity. +The following are just some of the available commands: + + +dfx wallet balance returns the selected identity’s cycles wallet balance. + + +dfx wallet list-addresses displays the assigned controllers & custodians of the cycles wallet. +You can use dfx wallet send <destination> <amount> +to send cycles to another wallet. +For more information on dfx wallet see dfx wallet. + + + + +Add an output type to the request-status subcommand. +This change allows you to specify the format for the return result for dfx canister request-status. Formatting options include idl, raw, and pp. + + +The default network for projects is now ic. +The default network is now the mainnet ic unless otherwise specified. Additionally, --network ic now points to the mainnet Internet Computer (Sodium has been deprecated.) + + +Automatic creation of a candid UI canister +A dedicated candid UI canister is installed on a local network when using dfx canister install or dfx deploy. + + +Compress some content types +You can now store gzip content encodings of assets with media types if the encoding is smaller than the source contents. Supported file types are text/*, */javascript, and */html. + + +Add the encoding size when listing assets +Now when assets are listed, a new length field returns the size of encodings. + + +Add new command dfx canister info +This allows you to retrieve certified canister information. Access to this information is limited to the controller of the canister and the SHA256 hash of its WASM module. If there is no WASM module installed, the hash will be None. + + +New method deletes asset canister assets that no longer exist in a project—breaking change +The keys() method is no longer supported. Use the list() method to delete missing project assets. For example: +assert_command dfx canister call --query e2e_project_assets get '(record{key="/will-delete-this.txt";accept_encodings=vec{"identity"}})' +assert_command dfx canister call --query e2e_project_assets list '(record{})' +assert_match '"/will-delete-this.txt"' + + +Run an emulator instead of the replica +To run a dfx project using an emulator instead of the replica, you can now run dfx start --emulator. + + +Rely on npmjs.org to get the version of agent-js to install +This decouples the version of dfx from the release version of agent-js. Additionally, it allows for debug builds to install properly (as dfx has a non-release version). + + +You can now install the DFINITY Canister SDK on for M1 Macs running Darwin. + + +Allow upload of assets of any size to the asset canister. +The following asset canister call methods are added: + create_batch() + create_chunk() + commit_batch() + get() +** get_chunk() ++ +Reworks the asset installer in dfx to use these methods. It can therefore upload assets that exceed the message ingress size. + + +Add --no-wallet flag and --wallet option +--no-wallet allows users to bypass specifying a wallet ID. +--wallet allows users to specify a particular wallet to use for calls. + + +Implement the HTTP request proposal in dfx bootstrap webserver +Adds support for http requests in the base storage canister (with a default to /index.html). + + +This does not support encodings other than identity, and doesn’t return any headers. +This also upgrades tokio and reqwest in order to work correctly. There are some performance issues to note (this is slower than the icx-http-server). +
+
+Motoko + + +Reformat to style guidelines. + + +Add type bindings +Add Nat.Nat, Nat8.Nat8, etc. to libraries for primitive types. + + +
+
+
+Issues fixed in this release +This section covers any reported issues that have been fixed in this release. +
+DFX + + +Deleting a canister on a network removes entries for other networks +This change fixes a bug where deleting a canister on a network removed all other entries for the canister in the canister_ids.json file. + + +Error message: already in use (os error 48) when issuing dfx start. +This fixes an error which occurred when starting a replica soon after stopping it. + + +The dfx new command should not require node +This fixes the inability to use the dfx new command to create projects on machines that do not have node.js installed. + + +Missing webpack.config plugin +This adds the missing ProvidePlugin to webpack.config for new projects. + + +Allow new projects assets to contain non-utf8 files +Previously assets were forced to be valid UTF-8 strings. After this change if a string cannot be converted, in-place variable replacements are ignored. + + +
+
+Motoko + + +No longer confused by distinct, but eponymous, type definitions. + + +Numbers of eponymous types and specializations from 1 (not 2) + + +Avoids long chains of type equalities by normalizing before translation + + +
+
+
\ No newline at end of file diff --git a/modules/release-notes/pages/0.7.1-rn.xml b/modules/release-notes/pages/0.7.1-rn.xml new file mode 100644 index 000000000..07ce1c2f8 --- /dev/null +++ b/modules/release-notes/pages/0.7.1-rn.xml @@ -0,0 +1,67 @@ + + + +
+ +Highlights of what’s new in 0.7.1 +2021-08-05 + +The 0.7.1 release includes new features and fixes to DFX commands, Motoko, the Motoko base library, and Candid. +
+New features and capabilities +The most significant new features and capabilities include the following updates for DFX commands: + + +An update to the dfx canister sign command enables you to sign request_status messages for update calls. +If you are using dfx canister sign to call a method that generates an update message, the command also signs a corresponding request_status message and appends it to the message.json file as signed_request_status. +After you send the message using the dfx canister send command, you can check the request_status of the call by running the following command: +dfx canister send message.json --status +This change is particularly useful if you are using the dfx canister sign and dfx canister send commands to call the ledger or governance canister to make a transaction or stake tokens as a two-step process. + + +There are new deposit_cycles and uninstall_code management canister methods that are also exposed as dfx canister subcommands. +The two new commands are dfx canister deposit-cycles and dfx canister uninstall-code. +For example, you can now send cycles from your cycles wallet to a specific canister by running a command similar to the following: +dfx canister deposit-cycles 125000000000 hello_world +You can uninstall code for a deployed WASM module by running a command similar to the following: +dfx canister uninstall-code hello_world + + +A new --no-artificial-delay option enables you to reduce the time it takes for the local Internet Computer to start. +This change adds the --no-artificial-delay flag to dfx start and dfx replica commands. +By default, the local Internet Computer replica that is installed with the {sdk-short-name} has an artificial consensus delay to simulate the delay users might see in a networked environment. +With this new flag, you can skip the built-in delay when you start the local Internet Computer by running either the dfx start --no-artificial-delay or dfx replica --no-artificial-delay command. +For example, you can start the local Internet Computer without a delay by running the following command: +dfx start -no-artificial-delay +If you use this option, however, you might an increase in the CPU used by the local Internet Computer replica. + + +
+
+Breaking change +The {sdk-short-name} version 0.7.1 introduces a change to the default principal used when you run dfx canister call commands. +Depending on the version of the {sdk-short-name} that you were previously using, this change might require changes to your program code or to the way you call methods in deployed canisters. + + +The cycles wallet canister identifier is not longer used as the message caller by default. +In some previous versions of the {sdk-short-name}, the dfx canister call command would use the cycles wallet canister identifier as the message caller to perform queries and update calls by default. +The --no-wallet command-line option was introduced to allow you to bypass the cycles wallet canister identifier and perform query and update calls using the currently-selected identity. +However, using the cycles wallet canister identifier to execute dfx canister call commands resulted in each call being treated as an inter-canister call and the calls would take longer than necessary to resolve. +With this release, dfx canister call commands no longer use the cycles wallet canister identifier to execute query and update calls by default. +If you want to execute a query or update call using the cycles wallet, you can run a command similar to the following: +dfx canister --wallet=cycles-wallet-id call canister method + + +
+
+Issues fixed in this release +This section covers any reported issues that have been fixed in this release. + + +Allow consistent use of canisters names or identifiers in dfx canister commands. +Previously, dfx canister commands were inconsistent about whether you could specify a canister using a canister name or a canister identifier. +With this change, all dfx canister commands now accept either a canister name as specified in the local dfx.json configuration file or a valid canister identifier as listed in the canister_ids.json file. + + +
+
\ No newline at end of file diff --git a/modules/release-notes/pages/0.7.2-rn.xml b/modules/release-notes/pages/0.7.2-rn.xml new file mode 100644 index 000000000..05e332e7b --- /dev/null +++ b/modules/release-notes/pages/0.7.2-rn.xml @@ -0,0 +1,22 @@ + + + +
+ +Highlights of what’s new in 0.7.2 +2021-08-05 + +The 0.7.2 release includes updates and fixes that are primarily internal to improve existing features and functions rather than user-visible. +The most significant changes in this release include the following: + + +Support for the latest version of the Internet Computer specification and replica. + + +The availability of new application subnets enable you to now deploy projects on the Internet Computer. + + +The default cycle balance for new cycles wallet canisters is now set to 3T (three trillion) cycles on application subnets and 4T (four trillion) on verified application subnets. + + +
\ No newline at end of file diff --git a/modules/release-notes/pages/0.7.7-rn.xml b/modules/release-notes/pages/0.7.7-rn.xml new file mode 100644 index 000000000..bfa0c8736 --- /dev/null +++ b/modules/release-notes/pages/0.7.7-rn.xml @@ -0,0 +1,22 @@ + + + +
+ +Highlights of what’s new in 0.7.7 +2021-08-05 + +The 0.7.7 release includes updates and fixes that are primarily internal to improve existing features and functions rather than user-visible. +The most significant changes in this release include the following: + + +Support for the latest version of the Internet Computer specification and replica. + + +Updating to latest versions of Motoko, Candid, and agent-rs + + +Changes to dfx new project template and JavaScript codegen + + +
\ No newline at end of file diff --git a/modules/release-notes/pages/0.8.0-rn.xml b/modules/release-notes/pages/0.8.0-rn.xml new file mode 100644 index 000000000..fb7a3c9bc --- /dev/null +++ b/modules/release-notes/pages/0.8.0-rn.xml @@ -0,0 +1,92 @@ + + + +
+ +Highlights of what’s new in 0.8.0 +2021-08-05 + +The 0.8.0 release includes updates and fixes that are primarily internal to improve existing features and functions rather than user-visible, as well as potentially breaking changes to some frontend projects. + + +improvements to codegen from 0.7.7 + + +set-wallet command no longer requires --force flag + + +
+Instructions on migrating to dfx 0.8.0 +If your project does not have a frontend that relies on the JavaScript files that have been generated under .dfx/local, you should not expect to have any issues with dfx 0.8.0. +If you have an existing project that depends on dfx-generated frontend files, you may need to make some adjustments when upgrading to 0.8.0. Depending on your situation you may want to choose to set up environment variables or to make a minimum set of changes. We will document both cases here. +
+Environment variables +With webpack, we are providing environment variables by using an EnvironmentPlugin. At the top of webpack.config.js, we read from the root canister_ids.json and the one inside .dfx/local to map the canister IDs into environment variables, and then replace the process.env values in the code during development or at build time. +// webpack.config.js +let localCanisters, prodCanisters, canisters; + +try { + localCanisters = require(path.resolve(".dfx", "local", "canister_ids.json")); +} catch (error) { + console.log("No local canister_ids.json found. Continuing production"); +} + +function initCanisterIds() { + try { + prodCanisters = require(path.resolve("canister_ids.json")); + } catch (error) { + console.log("No production canister_ids.json found. Continuing with local"); + } + + const network = + process.env.DFX_NETWORK || + (process.env.NODE_ENV === "production" ? "ic" : "local"); + + canisters = network === "local" ? localCanisters : prodCanisters; + + for (const canister in canisters) { + process.env[canister.toUpperCase() + "_CANISTER_ID"] = + canisters[canister][network]; + } +} +initCanisterIds(); +With your bundler, whether it is Webpack or another bundler of your choice, you will need to account for the following: + + +Identifying canister ids. The output no longer hardcodes the canister ids into JavaScript, so you will need to provide that code using your own strategy. Other bundlers that allow for custom scripting should be able to re-use the webpack config logic. + + +Determining NODE_ENV. During development, the app should call agent.fetchRootKey(), but it should not fetch the root key in production. + + +Copying the codegen, as we do in the dfx new template, is optional. You still have access to the .did.js and .did.d.ts files in .dfx, so you can choose to ignore the new index.js format if it is inconvenient, and continue providing your own Actor.createActor pattern as before. + + +Return types - if you do not want to use the dfx-provided files, consider using the JSDoc comments that we have come up with. If the code knows that your actor has a type of ActorSubclass<_SERVICE>, for your particular service, the development process is significantly enhanced in compatible editors. + + +
+
+Minimal Update +If you are looking to minimally modify your project, here is all you need to do, assuming you are starting from the 0.7.2 starter: +You can continue using a query parameter in your URL, you can access it via +// src/example_assets/src/index.js +import { idlFactory as example_idl } from 'dfx-generated/example/example.did.js'; +import canisterIds from '../../../.dfx/local/canister_ids.json' + +const example_id = new URLSearchParams(window.location.search).get("exampleId") || canisterIds.example.local; + +const agent = new HttpAgent(); +agent.fetchRootKey(); +const example = Actor.createActor(example_idl, { agent, canisterId: example_id }); +And you can modify the aliases reducer to point to the path, rather than hardcoding the old <canister-name>.js file +// webpack.config.js + +// Old +["dfx-generated/" + name]: path.join(outputRoot, name + ".js"), +// New +["dfx-generated/" + name]: path.join(outputRoot), +Then, you can dfx deploy like normal and visit your working site with http://localhost:8000/?canisterId=ryjl3-tyaaa-aaaaa-aaaba-cai&exampleId=rrkah-fqaaa-aaaaa-aaaaq-cai. +
+
+
\ No newline at end of file diff --git a/modules/release-notes/pages/sdk-release-notes.xml b/modules/release-notes/pages/sdk-release-notes.xml new file mode 100644 index 000000000..988f436e6 --- /dev/null +++ b/modules/release-notes/pages/sdk-release-notes.xml @@ -0,0 +1,49 @@ + + + +
+ +Developer Release Notes +2021-08-05 + +The {sdk-long-name} enables developers to develop applications to run on the Internet Computer. +The Motoko new programming language is bundled with the {sdk-long-name} to provide native support for creating tamper-proof software and open internet services. +The {sdk-short-name} provides everything you need to perform the following key tasks: + + +Author canisters in Motoko and compile them to WebAssembly. + + +Simulate the Internet Computer network running locally on your development computer. + + +Deploy compiled programs as canisters. + + +Interact with your application service using a command-line interface or through a web browser. + + + +The current release of the {sdk-long-name} is intended to introduce you to building applications that run on the Internet Computer and to provide access to the Internet Computer network for application testing, demonstration, and exploration.. +The {sdk-long-name} should not be used for developing production applications at this time. + +
+Known issues and limitations +This section covers any known issues or limitations that might affect how you work with the {sdk-short-name} in specific environments or scenarios. + + +Creating a new project displays errors or warnings. +By default, creating a new project installs node dependencies to support building a front-end for your project. +Depending on your environment, the installation of node dependencies might display errors or warnings generated by the npm package manager. +The errors and warnings issued by the npm package manager do not prevent you from successfully creating a new project and, in most cases, can be safely ignored. + + +
+
+Additional questions and feedback +Joining the DFINITY Developer Forum is an effective way to learn from community members, ask questions, solicit help from other developers, and provide insight and feedback about your experiences. +If you have questions that aren’t answered by the community, you might also want to check out Troubleshooting topics for information about common issues, workarounds for known issues, or help troubleshooting warnings or errors. +For technical support, send email to DFINITY Support. +A self-service Help Center of Knowledge Base articles will also be coming soon. +
+
\ No newline at end of file diff --git a/modules/token-holders/pages/custody-options-intro.xml b/modules/token-holders/pages/custody-options-intro.xml new file mode 100644 index 000000000..c98d2419c --- /dev/null +++ b/modules/token-holders/pages/custody-options-intro.xml @@ -0,0 +1,90 @@ + + + +
+ +Choosing self-custody for digital assets +2021-08-05 + +Self-custody is a token distribution option that enables you to have sole responsibility over your digital assets and over the management of your private keys, without the need of a third party to act on your behalf. +If you have made the choice to control your digital assets yourself, you should be aware that there are different kinds of self-custody solutions and that those solutions vary in their security and ease of use. +Before you decide on a specific self-custody solution, you should spend some time learning about the various options available and how they differ. +This guide provides a brief introduction to the concept of cold storage as part of your custody strategy and the most common types of cold storage currently available. +For additional information about cold storage and other custody options, you should do your own research and be sure that you understand the ramifications of your choices thoroughly before proceeding. +
+Cold storage +Cold storage means that you are keeping private keys stored offline in a device that is not connected to the internet. +Cold storage is a popular solution for self-custody of digital assets because it makes it more difficult for your keys to be compromised if there is a software security breach or if your cold storage solution is lost or stolen. +For more information about approaches to cold storage and best practices for securing your private keys, see the following additional resources: + + +Cold storage + + +Best Practices when using a Hardware Wallet + + +10 Rules for the Secure Use of Cryptocurrency Hardware Wallets + + +
+
+Common cold storage options +The most common types of cold storage include the following: + + + + + + + + + + + +
+Hardware wallets +A hardware wallet is a physical device that holds your digital assets. +Private keys are stored in a secure part of the device that does not come into contact with the internet. +The partitioned storage on the physical device reduces the risks that are associated with devices connected to the internet. +Because you are relying on a physical device, however, losing the device also means losing access to your digital assets. +In most cases, you can recover from the loss of a hardware wallet because the assets stored on hardware wallets are secured using a secret seed phrase. +. If you copy and secure the seed phrase—for example, by storing it in the form of a paper wallet—you can initialize a new device with the seed phrase and regain access to your digital assets. +For more information, see +Crypto Wallets, Explained. +
+
+Air-gapped computers +An air-gapped computer is isolated from insecure networks that interact with the internet or unsecured local area networks in your home. +Converting a standard personal computer or similar device into an air-gapped computer might require you to physically remove network cards, disable certain software, or be prepared to completely wipe the machine before connecting it to the internet again. +Depending on how secure you want you air-gapped computer to be, one option is to use a bootable image that provides a minimal operating system to collect your digital assets then remove any artifacts from that process and reboot the computer normally after completing any transaction. +For more information, see Extreme Security Measures for the Extra Paranoid and +The Ultimate Defense: What Is an Air Gapped Computer?. +
+
+Paper wallets +A paper wallet is a piece of printed paper that contains your important key information (in some cases, even a QR code) and is used for facilitating digital asset transactions. +Paper wallets are often not recommended because they are susceptible to degradation and could be insecure or lost easily. +As a backup to a hardware wallet, however, you might want to create a paper wallet and store it in a secure locations such as a safe deposit box. +For more information, see Paper wallets. +
+
+
+Keeping assets safe +It is ultimately your responsibility to research the cold storage and custody solutions available to you. +Regardless of the type of self-custody solution you select, it is also your responsibility to keep your digital assets safe. +With this in mind, you should take note of the following general recommendations: + + +Do not use a work computer to configure a digital asset storage solution. Your private personal data could be lost or +compromised while hosted on a work computer, especially if that computer is routinely connected to the internet. + + +Do not leave your cold storage wallet or any private information in a public place where it could be compromised. + + +Do not lose your private key. If lost, you will be permanently unable to access your digital assets. + + +
+
\ No newline at end of file diff --git a/modules/token-holders/pages/nns-app-quickstart.xml b/modules/token-holders/pages/nns-app-quickstart.xml new file mode 100644 index 000000000..56ebbb950 --- /dev/null +++ b/modules/token-holders/pages/nns-app-quickstart.xml @@ -0,0 +1,602 @@ + + + +
+ +Network nervous system application quick start +2021-08-05 + +As a decentralized blockchain, all changes to the configuration and behavior of the Internet Computer are controlled by an algorithmic governance system called the Network Nervous System (NNS). +The NNS controls all aspects of the Internet Computer network configuration and is responsible for performing many network management operations. For example, the Network Nervous System (NNS) is responsible for: + + +Upgrading the protocol and guest operating system software used by the nodes that provide computing capacity to the network. + + +Inducting new node operators and machines into the network. + + +Creating new subnets to increase network capacity. + + +Splitting subnets to balance network load. + + +Configuring parameters that control how much must be paid by users for compute capacity. + + +Monitoring canister activity and node performance for +malicious behavior and statistical deviations. + + +De-activating malicious software or under-performing nodes to protect the network. + + +The requests for changes and updates to the network are submitted to the NNS in the form of proposals. +The NNS decides to adopt or reject proposals based on voting activity by certain network participants. +
+What are neurons? +For network participants to be able to vote on proposals, they need to lock up a stake of ICP tokens for a given period of time to create a representative called a neuron. +Because neurons represent a stake of ICP tokens, they also represent an identity with a ledger canister account and a principal that controls the ledger account. +Neurons provide the stability required for responsible governance of the Internet Computer by ensuring that the ICP tokens they represent cannot be exchanged for a specific period of time referred to as the lock-up period. +The following diagram provides a simplified view of the workflow for creating a neuron and the relationship between the neuron and ledger canisters. + + + + +create dissolve neuron api + +
+Governance and voting rewards +When a person or organization has ICP tokens locked up in a neuron, the neuron holder can propose and vote on governance issues. +To encourage participation, neuron holders are also paid for voting in proportion to the number of ICP tokens they have locked up and the length of the lock-up period up to a maximum of eight years. +The incentive paid to neuron holders for voting is called a voting reward. +
+
+Unlocking the stake held by a neuron +After network participants create a neuron, the locked balance of ICP tokens can only be unlocked by fully dissolving the neuron. +In its locked state, the neuron has a fixed non-zero dissolve delay equivalent to the lock-up period. +For example, assume you have a stake of 100 ICP tokens locked up for a period of five years. +After successfully created the neuron with these settings, your dissolve delay is five years. +Based on the dissolve delay that decreases as time progresses, a dissolve timer determines how long it will take to completely dissolve a neuron. +When the dissolve timer reaches zero, the neuron owner—the ICP token holder who created the neuron or an authenticated custodian—can dissolve the neuron and unlock the balance of ICP tokens. +The dissolved neuron ceases to exist and the stake of ICP tokens that the neuron represented is released to the appropriate ledger canister account. +
+
+
+Connect to the Internet Computer +To connect to the Internet Computer using the Network Nervous System (NNS) application: + + +Open a browser and navigate to the Network Nervous System (NNS) application. + + +Click Login to connect to Internet Identity. +If you haven’t previously registered and received an identification number, you can click Register with Internet Identity to register. + +We strongly recommend you add multiple devices and authentication methods to your Internet Identity. For example, register multiple physical devices like your computer and phone with a security key and using the authentication options that those devices—and browsers running on them—support. + +For more information about creating an Internet Identity, see How to use Internet Identity. +After you have registered, you can click Login to authenticate using your identification number and the authentication method—for example, a security key or fingerprint—you have registered. + + +Click Proceed to access to the Network Nervous System (NNS) application. + + +
+
+Add an account +Logging on using an Internet Identity creates a Main account for you in the Internet Computer ledger. +If your ICP tokens are associated with your developer identity—that is, the identity created by the {sdk-short-name} dfx command-line interface—your Main account displays 0.00 for your ICP token balance. +For example: + + + + +nns app main + +Before transferring any tokens, you can create one or more linked subaccounts or attach a hardware wallet to your account. +To add an account for managing ICP tokens: + + +Open a browser and navigate to the Network Nervous System (NNS) application. + + +Click Login to connect using your Internet Identity. + + +Verify your identification number, then click Login to authenticate using the device and authentication method you have registered. + + +Click Proceed to access to the Network Nervous System (NNS) application. + + +On the default ICP tab, click Add Account. + + +Select the type of account to add. + + +New Linked Account creates a new subaccount linked to your Main account address in the ledger. + + +Attach Hardware Wallet adds a hardware wallet to your main account address in the ledger. (Support for the Ledger Nano hardware wallet is coming soon, but not available yet.) + + + + +Click New Linked Account, type an Account Name, then click Create. + + + + +new linked account + + + +
+
+Transfer ICP tokens between accounts +If you have selected self-custody for holding your ICP tokens and the tokens are associated with your developer identity instead of your registered Internet Identity, you need to transfer ICP tokens to your accounts if you want to manage them using the Network Nervous System (NNS) application. +To transfer ICP tokens controlled by your developer identity: + + +Open a terminal shell on your local computer. + + +Check that you are using an identity with control over the ledger account by running the following command: +dfx identity whoami +In most cases, you should see that you are currently using your default developer identity. +For example: +default + + +View the textual representation of the principal for your current identity by running the following command: +dfx identity get-principal +This command displays output similar to the following: +tsqwz-udeik-5migd-ehrev-pvoqv-szx2g-akh5s-fkyqc-zy6q7-snav6-uqe +Note that this identifier should be the same as the identifier you specified in the Know Your Customer (KYC) process if you were required to pass KYC verification to receive your ICP tokens. + + +Check the current balance in the ledger account associated with your identity by running the following command: +dfx ledger --network ic balance + + +Transfer ICP tokens to your Main account or a linked subaccount you create by running a command similar to the following: +dfx ledger --network ic transfer <destination-account-id> --icp <ICP-amount> --memo <numeric-memo> +For example, assume you have the following accounts: + + + + +accounts + +If you want to transfer one ICP token to the Main account, you can run the following command: +dfx ledger --network ic transfer dd81336dbfef5c5870e84b48405c7b229c07ad999fdcacb85b9b9850bd60766f --memo 12345 --icp 1 +If you also want to transfer one ICP token to the pubs account, you can run the following command: +dfx ledger --network ic transfer 183a04888eb20e73766f082bae01587830bd3cd912544f63fda515e9d77a96dc --icp 1 --memo 12346 +This example illustrates how to transfer ICP tokens to using a whole number with the --icp command-line option. + + +You can also specify fractional units of ICP tokens—called e8s—using the --e8s option, either on its own or in conjunction with the --icp option. + + +Alternatively, you can use the --amount to specify the number of ICP tokens to transfer with fractional units up to 8 decimal places, for example, as 5.00000025. + + +The destination address can be an address in the ledger canister running on the Internet Computer network, an account you have added using the Network Nervous System application, or the address for a wallet you have on an exchange. +If you transfer the ICP tokens to an account in the Network Nervous System application, you might need to refresh the browser to see the transaction reflected. +For more information about using the dfx ledger command-line options, see dfx ledger. + + +
+
+Stake ICP tokens in a neuron +After you transfer ICP tokens to the Network Nervous System application, you can use the Network Nervous System application to create and manage neurons, vote on proposals, and create canisters on the Internet Computer. +Neurons are required to participate in governance and earn rewards. +To create a neuron, you must lock up some number of ICP tokens for a period of time. The minimum stake required to create a neuron is one ICP token. +You can configure the period of time the stake is locked from six months up to a maximum of eight years. +To stake ICP tokens: + + +Open a browser and navigate to the Network Nervous System (NNS) application. + + +Click Login to connect using your Internet Identity. + + +Verify your identification number, then click Login to authenticate using the device and authentication method you have registered. + + +Click Proceed to access to the Network Nervous System (NNS) application. + + +Click Neurons, then click Stake Neuron. + + +Type the number of ICP tokens to stake, then click Create. + + +Set the dissolve delay for the neuron to control the length of time the stake is locked, then click Update Delay. +For example: + + + + +dissolve delay + + + +Click Yes, I’m sure to confirm the lock up period, then close the window to review the newly-created neuron properties. + + + + +neuron properties + + + +
+What you can do after creating a neuron +After you have locked the stake and created a neuron, you can: + + +Start the dissolve delay timer by clicking Start Unlock. + + +Increase the dissolve delay period by clicking Increase Dissolve Delay. + + +Stop the dissolve delay after starting the unlock countdown by clicking Lockup. + + +Increase the number of ICP tokens you have staked. + + +
+
+Starting and stopping the dissolve delay +Creating a new neuron does not automatically start the dissolve delay timer. +You must explicitly start the timer countdown by clicking Start Unlock. +For example, if you set a dissolve delay of one year and want to immediately begin the countdown, you should click Start Unlock as part of the process of creating the neuron. +If you change your mind and want to stop a current countdown in progress, you can click Lockup, +After you click Lockup to stop the dissolve delay, you can click Start Unlock to resume the countdown without changing the existing dissolve delay period. +If you want to continue a countdown already in progress but extend the lock up period, you can click Increase Dissolve Delay then select a longer dissolve delay. +
+
+Adding ICP tokens to an existing neuron +After you create a neuron, you can increase the number of ICP tokens you have staked in that neuron to increase your voting power and rewards. +For example, if you initially stake a small number of ICP tokens, then decide to purchase additional tokens, you have the option to create a new neuron or "top-up" your existing neuron. +To increase the stake in an existing neuron: + + +Follow the steps in Stake ICP tokens in a neuron to stake the original neuron using the Network Nervous System (NNS) application. + + +Look up the transaction in the Internet Computer Association transaction dashboard to get the neuron address. +You can use the account identifier for your main ICP ledger account to search for your transactions. + + +Return to the Network Nervous System (NNS) application, then click New Transaction. + + +Paste the neuron address from the transaction dashboard into the Destination address field, then click Continue. + + +Type the amount of ICP tokens you want to add to the specified neuron, then click Continue. + + +Verify the transaction details, then click Confirm and Send. + + + + +confirm top up + + + +Verify the completed transaction, then click Close. + + +Click the Neurons tab to see the increased stake. + + +
+
+
+Configure following rules +Active participation in governance is an important factor in the long-term health of the Internet Computer. +Voting on proposals is also an important factor in calculating the rewards you receive in return for locking up ICP tokens in neurons. +However, voting directly on every proposal submitted to the NNS presents several challenges. +For example, proposals might be submitted and require a vote when you are unavailable or propose changes that you lack the expertise to evaluate. +To address these challenges, you can configure neurons to vote automatically to adopt or reject proposals by following the votes of a group of neurons. +To maximize your rewards, you should vote on as many proposals as possible by following the active neuron holders who have interests aligned with your own. For example, you might follow the Internet Computer Association (ICA) on some topics such SubnetManagement and other neuron holders on topics such as Governance. +To configure how you follow other neuron holders: + + +Open a browser and navigate to the Network Nervous System (NNS) application. + + +Click Login to connect using your Internet Identity. + + +Verify your identification number, then click Login to authenticate using the device and authentication method you have registered. + + +Click Proceed to access to the Network Nervous System (NNS) application. + + +Click Neurons, then click the link for a specific neuron identifier to display its properties. + + +Click Edit Followees. + + +Choose a proposal topic. +For example, expand the Governance topic, then click Enter Followee. + + +Select a neuron holder to follow, then click Follow. +For example, click Follow for the Internet Computer Association. + + + + +follow ica + +The neuron holder is added to you Currently Following list. + + +Repeat for each topic where you want your neuron’s votes to automatically follow the votes of one or more other neuron holders. + + +
+
+Disburse dissolved neurons into an account +When the dissolve delay timer for a neuron reaches zero, you can disburse the neuron’s stake and transfer its locked ICP token balance to the ledger account you specify. +After you take this step, the neuron identifier and its ledger history are permanently removed from the governance canister. +To disburse a neuron and return its ICP tokens: + + +Open a browser and navigate to the Network Nervous System (NNS) application. + + +Click Login to connect using your Internet Identity. + + +Verify your identification number, then click Login to authenticate using the device and authentication method you have registered. + + +Click Proceed to access to the Network Nervous System (NNS) application. + + +Click Neurons, then click Unlocked neuron that has reach the ended of its dissolve delay period. +For example: + + + + +unlocked neuron + + + +Click Disburse. +For example: + + + + +disburse + + + +Type an address or select an account to receive the ICP tokens. +For example, you might select the dev-projects linked account: + + + + +select account + + + +Verify the transaction information, then click Confirm and Send. +For example, check that the Destination address matches the intended address of the dev-projects linked account: + + + + +confirm send + + + +Verify the completed transaction, then click Close. +For example: + + + + + + +confirmation + ++ +If you transferred the ICP tokens to one of your accounts in the Internet Computer ledger canister, you can click the ICP tab and see your new balance reflected. +For example: ++ + + + + +updated icp + +
+
+Spawn new neurons +As you vote on proposals—either directly or by following the votes of other neurons—the maturity associated with your neuron increases, which in turn increases the rewards you earn for participating in governance. +When the maturity for a locked stake reaches a minimum threshold of one ICP, you can spawn a new neuron. +The spawn operation creates a new neuron that locks a new balance of ICP on the ledger. +For example, if you have a neuron that contains 100 ICP tokens and it has a maturity of 10 percent, you can spawn a new neuron that contains approximately 10 new ICP tokens. For the neuron with 100 ICP tokens to reach the minimum threshold for spawning, its maturity would need to be greater than one percent. +After you spawn a new neuron from an existing neuron, the maturity for the existing neuron falls to zero. +To spawn new neurons from an existing neuron: + + +Open a browser and navigate to the Network Nervous System (NNS) application. + + +Click Login to connect using your Internet Identity. + + +Verify your identification number, then click Login to authenticate using the device and authentication method you have registered. + + +Click Proceed to access to the Network Nervous System (NNS) application. + + +Click Neurons, then click the neuron that has reached the minimum maturity required to spawn a new neuron. + + +Click Spawn Neuron. +Keep in mind that the dissolve delay for a newly-spawned neurons is one day, giving you the option to collect value from the ICP tokens by unlocking them or to increase the dissolve delay to collect additional rewards. + + +For more information about maturity and spawning new neurons, see the following articles: + + +Earn Substantial Voting Rewards by Staking in the Network Nervous System + + +Understanding the Internet Computer’s Network Nervous System, Neurons, and ICP Utility Tokens + + +Getting Started on the Internet Computer’s Network Nervous System App & Wallet + + +
+
+Vote on proposals +You can choose the proposal types and proposal topics that you see and vote on—either directly or by following other neuron stakeholders—using filters in the Network Nervous System application. +For example, if you want to review and vote on all proposals that involve network participants such as data center identities and node operators, but aren’t interested in viewing proposals related to the current market value of ICP, as measured by an International Monetary Fund (IMF) Special Drawing Right (SDR), you can select the ParticipantManagement topic filter and deselect the ExchangeRate topic filter. +To manually vote on proposals: + + +Open a browser and navigate to the Network Nervous System (NNS) application. + + +Click Login to connect using your Internet Identity. + + +Verify your identification number, then click Login to authenticate using the device and authentication method you have registered. + + +Click Proceed to access to the Network Nervous System (NNS) application. + + +Click Voting. +You can click any of the proposals listed to view information about the proposal, including a brief description of the proposal, a link for viewing additional information about the proposal, the number of votes that were cast to adopt or reject the proposal, and the votes cast by your neurons. + + +Use the Topics, Reward Status, and Proposal Status filters to control the list of proposals displayed. +For example, open the Topics list to see if there are any proposal topics that you want to include in the proposal list that are not currently displayed and open the Proposal Status to verify that you are viewing all open proposals. + + +Click any Open proposal to see its details and the voting power for the neurons associated with your identity. + + +Select the neuron identifiers with voting power that you want to use to cast your vote. + + +Click Adopt or Reject to cast your vote. +For more information about voting and voting rewards, see the following articles: + + +Earn Substantial Voting Rewards by Staking in the Network Nervous System + + +Understanding the Internet Computer’s Network Nervous System, Neurons, and ICP Utility Tokens + + +Getting Started on the Internet Computer’s Network Nervous System App & Wallet + + + + +
+
+Submit a proposal +Currently, you can only submit proposals to the network nervous system by using the {sdk-short-name} command-line interface (dfx) using calls to the governance canister. +A separate command-line tool (icx-nns) for working with the governance canister is in development and this functionality will also be available in the Network Nervous System (NNS) application soon. +If you want to start submitting proposals right away, however, you can access a preliminary version of the icx-nns command-line tool by downloading a release from the icx-nns repository. +For information about how to download the icx-nns command-line tool and how to use it to submit proposals, see How to submit proposals to the Network Nervous System. +
+
+Deploy a canister with cycles +You must have cycles available to create and manage canisters, which are similar to smart contracts. +The Network Nervous System (NNS) application provides a convenient way for you to create and manage canisters by enabling you to convert ICP tokens into cycles and attach cycles to specific canister identifiers. +To create a new canister: + + +Open a browser and navigate to the Network Nervous System (NNS) application. + + +Click Login to connect using your Internet Identity. + + +Verify your identification number, then click Login to authenticate using the device and authentication method you have registered. + + +Click Proceed to access to the Network Nervous System (NNS) application. + + +Click Canisters, then click Create or Link Canister. + + +Click Create New Canister to create a new cycles wallet canister. +If you already have a cycles wallet canister, you can click Link Canister to Account to link an existing canister identifier to your account in the Network Nervous System (NNS) application. + + +Select one of your accounts that holds ICP tokens as the source account. +For example, if you have both a Main account and a Dev-Projects account, you might select Dev-Projects account if that account holds the ICP tokens that you want converted into cycles. + + +Click Amount and type the number of ICP tokens or e8s that you want to convert into cycles, then click Review Cycles Purchase. +The amount you specify must convert to a value greater than the 2T (two trillion) cycles minimum required to create a new canister identifier. +For example: + + + + +convert to cycles + + + +Review the ICP tokens to cycles details, then click Confirm to continue. +After you click Confirm, you can review: + + + + +the new canister identifier + + +the number of cycles available for the canister to use + + +the controlling principal that currently has full management rights for the new canister + + ++ +To change, the principal used as the controller of the canister, click Change Controllers. +To add cycles to the canister, click Add Cycles. +. Return to the Canisters tab to see the canisters you have created. ++ +For example: ++ + + + + +canister list + +
+
\ No newline at end of file diff --git a/modules/token-holders/pages/seed-donations.xml b/modules/token-holders/pages/seed-donations.xml new file mode 100644 index 000000000..08b9cd402 --- /dev/null +++ b/modules/token-holders/pages/seed-donations.xml @@ -0,0 +1,462 @@ + + + +
+ +Neuron/ICP Instructions for Seed Participants +2021-08-05 + +THANK YOU for being a Seed participant. +You have been granted ICP at a rate of 30 tokens per Swiss Franc of value donated in 2017, which Genesis Unlock is disbursing in the form of a basket of 49 voting neurons. +These neurons already exist inside the Network Nervous System, the completely open, tokenized governance system that controls the Internet Computer blockchain network. Your neurons contain the ICP you have been awarded, staked inside. Your neurons have been configured to vote automatically and are already earning voting rewards for you. You do not need to do anything to initialize your neurons in order to continue earning voting rewards. +A neuron is like a savings account where you must provide notice of withdrawals. The configured notice period is called the “dissolve delay”. You can start and stop dissolving a neuron at any time. The greater the dissolve delay, the greater the neuron’s voting power, and the greater the voting rewards it receives. +We are pleased to inform you that your neurons have been pre-aged! At the moment of Genesis Unlock, their age was already set to 18 months old. This is important, because neuron age significantly increases your voting power and the voting rewards you receive. + +When you start dissolving a neuron, the blockchain will reset its age to zero immediately. Therefore, be very careful to only begin dissolving neurons when you wish to unstake the ICP inside. + +Genesis Unlock created 49 neurons for you. They have dissolve delays of 0 days, 30 days, 60 days, 90 days and so on. Apart from the first neuron which has a dissolve delay of 0 days (which can be dissolved immediately), the other dissolve delays may have a small random number of days either added or removed. +To configure one of your neurons, for example to change how it votes, or to place it into dissolving mode, follow these steps: + +This process is not currently possible on macOS computers with M1 chips. You can only install the {sdk-short-name} dfx and the Candid compiler didc on Intel-based macOS and Linux computers. + + + + + + + + + + + + + + + + + + +
+Derive a native Internet Computer principal from your Ethereum seed +As an early contributor or seed donor, you wrote down a 12-word mnemonic seed phrase that was generated by the DFINITY Chrome extension. To create an identity, you must derive a private key from your seed phrase and import that private key into the DFINITY Canister SDK. This step is required before you can . +
+Secure your environment +The safety and security of your private key is your responsibility and there is no substitute for planning ahead, bringing the right equipment, having the right skills, and using good judgment. We strongly recommend you proceed using an air-gapped computer to reduce the risk of having your private key compromised. Depending on the hardware available, you might want to physically remove your network controller, microphone, speakers, and other components, or disable them in your BIOS. Covert channels can be established through a variety of different mediums, including sound, light, radio-frequency, and physical media. Be sure to evaluate the capabilities of your system before settling on a configuration that makes sense for you. If you don’t know what you are doing, you should consult with a computer security expert. Do not contact the DFINITY Foundation for help with securing your environment. +
+
+Install Keysmith +You need Keysmith to derive your private/public key pair from you seed phrase. +To install Keysmith, you must either or . +
+Fetch the release binary +If you want to download the Keysmith release binary, keep in mind that you must perform this action on a computer with a network connection. If you are using an air-gapped computer, then you must copy the release binary from your networked computer to your air-gapped computer. How you do this will depend on your configuration. +To download the Keysmith release binary, fetch release v1.5.0 from Github. +Keysmith supports the following operating systems and architectures: + + +Darwin / AMD64 – for macOS models with an Intel chip (how to check) + + +Darwin / ARM64 – for newer macOS models with an M1 chip (how to check) + + +Linux / AMD64 + + +Linux / ARM32 + + +Linux / ARM64 + + +Windows / AMD64 + + +Download the .tar.gz file matching your architecture and operating system. +If you have a newer M1-based macOS, download keysmith-darwin-arm64.tar.gz. +Although you can install keysmith on macOS computers with an M1 chip, you can only install the {sdk-short-name} dfx command-line interface on Intel-based macOS computers. +For an Intel-based macOS, download keysmith-darwin-amd64.tar.gz. +
+
+Verify the SHA256 checksum of your download +Open a terminal and change to the download directory. On a Mac this is +cd ~/Downloads +Compute the SHA256 checksum of your download. +openssl dgst -sha256 keysmith-*.tar* +Make sure the output matches one of the following lines: +SHA256(keysmith-darwin-amd64.tar.gz)= ad7383d60bced19580fa37b77e133b1e80416b482e4c5326ac2fd17a7710a318 +SHA256(keysmith-darwin-arm64.tar.gz)= da1a4ac5ae04b85d4c5b0a3deb6442fb7c456dcf97cbd6ff8153316c5dbb29a9 +SHA256(keysmith-linux-amd64.tar.gz)= 7901c3a23aef298f930d1dddf8eee23bc51a55ffda670accfd7b9e37748913d8 +SHA256(keysmith-linux-arm32.tar.gz)= 0ab44e74cc502aa653dcb28962bcada5cbefb9e0ec41853a03fb4745c5cd51a9 +SHA256(keysmith-linux-arm64.tar.gz)= 635c0bf98dd15f27b302ec0ea793f75c797441009c74500bd9d0a5df26092264 +SHA256(keysmith-windows-amd64.tar.gz)= cb398c39583b81d5170dd0a9539d902715317572f6a640b45d3d2db01946b8fa +If your browser already unzipped the .tar.gz for you and you have a file ending in .tar then make sure the output of openssl matches one of the following lines: +SHA256(keysmith-darwin-amd64.tar)= 97b8048f00e75d6adc8651aac1aa77d9bd9c150b0dbc0b0f6409f0d6bdbb24a4 +SHA256(keysmith-darwin-arm64.tar)= 07e296fbf33b0c06bd04a8ead30487762aa30ca2daf7e19948d74a96f2c34067 +SHA256(keysmith-linux-amd64.tar)= 1d2d986a971f8c7ef0eeb4b01624f023ef8dc9c71d2f0127f21fcc99aebdc99a +SHA256(keysmith-linux-arm32.tar)= 8eb8efecd9182822326f2e60fcff32c0b1541cce206a12b3f2e94547c66dfe63 +SHA256(keysmith-linux-arm64.tar)= 82264487e83cbfdd758c1227375758b7d1f0c864adb555775777e7d3afa19e08 +SHA256(keysmith-windows-amd64.tar)= b85224d4e9807b8335295193c12dd0cab22bd38881d14c1f1c21479801ace17d +
+
+Unpack and install keysmith +To extract the executable from the tarball, enter the following command into your terminal: +tar -f keysmith-*.tar* -x +Next, add the executable to your PATH by entering the commands below: +sudo install -d /usr/local/bin +sudo install keysmith /usr/local/bin +You will be prompted to enter your laptop password. +The password itself will not appear, simply type it and press enter. +
+
+Run it +keysmith +You should see: +usage: keysmith <command> [<args>] + +Available Commands: + account Print your account identifier. + generate Generate your mnemonic seed. + legacy-address Print your legacy address. + principal Print your principal identifier. + private-key Write your private key to a file. + public-key Print your public key. + version Print the version number. + x-public-key Print your extended public key. +If you are using macOS, making the keysmith binary executable might require you to change a permission setting using System Preferences > Security & Privacy > General. +
+
+Build Keysmith from source +If you want to build the Keysmith from source, keep in mind that you must perform this action on a computer with a network connection. If you are using an air-gapped computer, then you must copy the target binary from your networked computer to your air-gapped computer. How you do this will depend on your configuration. +Keysmith is written in Go, so if you choose to build it from source, then you must first download and install Go, verify that go is in your PATH, and configure your GOPATH and GOBIN environment variables. +Run the following command to build Keysmith from source. +go get github.com/dfinity/keysmith +
+
+
+Install the DFINITY Canister SDK +You can install the DFINITY Canister SDK by fetching the v0.7.0 release binary from our website. It is not yet possible to build the DFINITY Canister SDK from source. +Note that this action can only be performed on a networked computer. If you are using an air-gapped computer, then you must copy the release binary from your networked computer to your air-gapped computer. How you do this will depend on your configuration. +Run the following command to install the DFINITY Canister SDK. +sh -ci "$(curl -fsSL https://sdk.dfinity.org/install.sh)" +Warning: Note that dfx will currently not install on M1-based Macs. +
+
+Set your seed phrase for use with keysmith +Once you have installed Keysmith and the DFINITY Canister SDK, and you are confident that your environment is secure, then you are ready to enter your seed for use with keysmith. +For the duration of your session, you store your seed phrase in an environment variable. +It will be eliminated from your system when you turn your computer off. +read seed +Enter your seed phrase and finish with Return. +If you prefer to not have your seed phrase displayed as you type then use this command instead: +read -s seed +
+
+Check your legacy address and balance (optional) +At this point you can already verify your legacy address and ICPT balance. +The legacy address matches to what was formerly called "DFN address" in the Dfinity Chrome extension. +You may have copied it from the Chrome extension for your records back when you used the extension. +echo $seed | keysmith legacy-address -f - +The output is a 40 character hex string. It looks something like this: +2d89d96b10f7a9456a9154b2f5309ee70df5bce1 +You can check your ICPT balance as follows: +echo {} > dfx.json +GTC=renrk-eyaaa-aaaaa-aaada-cai +ADDR=$(echo $seed | keysmith legacy-address -f -) +dfx canister --network=https://ic0.app --no-wallet call $GTC balance '("'$ADDR'")' +The output is the number of ICPT associated with your address. +If you are an early contributor then you may have multiple addresses, all derived from your one seed phrase. To check the balance in each of them you do the following commands: +GTC=renrk-eyaaa-aaaaa-aaada-cai +ADDR=$(echo $seed | keysmith legacy-address -f - -i 0) +dfx canister --network=https://ic0.app --no-wallet call $GTC balance '("'$ADDR'")' +Then you repeat the last two lines with -i 1, -i 2, etc. +
+
+Derive and import your private key +Derive your private key from your seed phrase. +echo $seed | keysmith private-key -f - +This creates a file identity.pem containing your private key. +Import your private key(s) into the DFINITY Canister SDK and then remove it from the filesystem. +dfx identity import <name> identity.pem +rm identity.pem +Here, <name> is an alias that you can choose arbitrarily for your identity, e.g. "jane". +The command above displays output similar to the following: +Creating identity: "jane". +Created identity: "jane". +Make your new identity the currently-active one. +dfx identity use <name> +The command above displays output similar to the following: +Using identity: "jane". +At any time, you can list all available identities with +dfx identity list +
+
+
+Take control of your neurons +You will receive your tokens inside a set of neurons that have been pre-created for you. +The number of neurons will total 31 or 49 depending on whether you are an early contributor or seed donor, respectively. +Your tokens are disbursed equally over these neurons. +Claiming your neurons is the process of obtaining control over your neurons. +It is done for all neurons at once. +Your neurons differ by their dissolve delay. +For an explanation of dissolve delay see below. +To claim your neurons, you need to sign and send a message to the Genesis Token Canister. You can accomplish this in one step on a networked computer using dfx canister call, or as two separate steps, one on an air-gapped computer using dfx canister sign, and another on a networked computer using dfx canister send. We strongly recommend the latter approach to reduce the risk of having your private key compromised. +Regardless of which method you choose, you will need to download and install didc, the Candid compiler, on your networked computer. You can find the latest release here. Note that the binaries are suffixed by the operating systems they run on, didc-linux64 and didc-macos. Be sure to download the correct one. Below are commands to install didc on macos. If your’re using Linux, simply use the linux64 suffix instead. +sudo install -d /usr/local/bin +sudo install -m 0755 ~/Downloads/didc-macos /usr/local/bin/didc +Regardless of which method you choose, you will also need to download and extract the NNS canister interfaces on your networked computer. You can find the latest release here. Below are commands to extract the NNS canister interfaces. +pushd ~/Downloads +tar -f nns-ifaces-0.8.0.tar.gz -x +popd +Additionally, you will need to have dfx.json file available in the directory from which you are running dfx commands. You can create an empty dfx.json file in your current directory by running the following command. +echo {} > dfx.json +Note that if you’re using an air-gapped computer, then you’ll need to repeat this step since you’ll be running dfx commands in both places. +After downloading and installing didc, downloading and extracting the NNS canister interfaces, and creating your dfx.json file(s), you can or . +
+Claim in one step (not recommended) +Verify that you can connect to the Internet Computer. +dfx ping https://ic0.app +Derive your public key. +PUBLIC_KEY="$(echo $seed | keysmith public-key -f -)" +Call the Genesis Token Canister to claim your neurons. +CANISTER=renrk-eyaaa-aaaaa-aaada-cai +RESULT="$(dfx canister --network=https://ic0.app --no-wallet call $CANISTER claim_neurons '("'$PUBLIC_KEY'")' --output=raw)" +didc decode -t "(Result)" -d ~/Downloads/nns-ifaces-0.8.0/genesis_token.did $RESULT +
+
+Claim in two steps +
+On your air-gapped computer +Derive your public key. +PUBLIC_KEY="$(echo $seed | keysmith public-key -f -)" +Sign a message to claim your neurons. +Note that the time allotted to send a signed message is a fixed 5-minute window. The --expire-after option enables you to specify the point in time when the 5-minute window for sending the signed message should end. For example, if you set the --expire-after option to one hour (1h), then you must wait at least 55 minutes before you send the generated message and the signature for the message is only valid during the 5-minute window ending in the 60th minute. Hence, you would need to send the message after 55 minutes and before 60 minutes for the message to be recognized as valid. If you don’t specify the --expire-after option, then the default expiration is five minutes. +CANISTER=renrk-eyaaa-aaaaa-aaada-cai +dfx canister --network=https://ic0.app --no-wallet sign --expire-after=1h $CANISTER claim_neurons '("'$PUBLIC_KEY'")' +The command above results in a message.json file in your current directory. You must copy that file from your air-gapped computer to your networked computer. How you do this will depend on your configuration. +
+
+On your networked computer +Verify that you can connect to the Internet Computer. +dfx ping https://ic0.app +Send the signed message to the Genesis Token Canister to claim your neurons. As previously mentioned, you can only perform this action within the 5-minute window that you specified. +dfx canister --network=https://ic0.app --no-wallet send message.json +Unlike dfx canister call in the section , the command dfx canister send does not return output that can be parsed by didc. +Instead, it outputs only a request id. +In order to see the effect of your send request, you have to do an additional step. +Perform the following commands on your networked machine: +CANISTER=renrk-eyaaa-aaaaa-aaada-cai +RESULT="$(dfx canister --network=https://ic0.app --no-wallet call $CANISTER get_account '("paste legacy address here")' --output=raw)" +didc decode -t "(Result_2)" -d ~/Downloads/nns-ifaces-0.8.0/genesis_token.did $RESULT +The legacy address to paste here in the second line above is what was formerly called "DFN address" in the Chrome extension. +Note that the legacy address must be pasted without the 0x prefix and without the 8-character checksum at the end, i.e. it has exactly 40 characters in length. +Furthermore, the legacy address must be in all lowercase. +If you don’t remember it then you can obtain your legacy address by running this on your air-gapped machine: +echo $seed | keysmith legacy-address -f - +What you want to look for in the output of the get_account request is has_claimed = true and your principal. +For example, the output of the get_account command looks like this for an unclaimed account: +( + variant { + Ok = record { + authenticated_principal_id = null; + successfully_transferred_neurons = vec {}; + has_donated = false; + failed_transferred_neurons = vec {}; + neuron_ids = vec { record { id = 1_234_567_890_123_456_789 : nat64;}; ... + }; + has_claimed = false; + has_forwarded = false; + icpts = 12345 : nat32; + } + }, +) +And like this for a successfully claimed account: +( + variant { + Ok = record { + authenticated_principal_id = opt principal "a56gn-wnhrl-i76df-ewgfe-23jfd-dfh03-ergrg-fesr1-1jhs9-reg2o-ure"; + successfully_transferred_neurons = vec {}; + has_donated = false; + failed_transferred_neurons = vec {}; + neuron_ids = vec { record { id = 1_234_567_890_123_456_789 : nat64;}; ... + }; + has_claimed = true; + has_forwarded = false; + icpts = 12345 : nat32; + } + }, +) +
+
+
+Get you neuron identifiers +After you have claimed your neurons (in one step or two) you should look at your neuron identifier and keep them handy for the future. +You will need to reference them when you . +You can see your neuron identifiers in the output of the get_account of which you saw an example just above. +The neuron identifiers are the numbers that look like this: 1_234_567_890_123_456_789. +You could just copy paste them from the output of get_account. +A better alternative is to extract the neuron identifiers more conveniently into an one-per-line output as follows. On your networked computer do: +ADDR="write your legacy address here" +GTC=renrk-eyaaa-aaaaa-aaada-cai +dfx canister --network=https://ic0.app --no-wallet call $GTC get_account '("'$ADDR'")' | grep 2_024_218_412 | awk '$1=$1' RS=";" | grep = | sed -e 's/.*= //' +The result should be a list of 31 or 49 neuron identifiers. +If you are not in an airgapped setup you can do ADDR=$(echo $seed | keysmith legacy-address -f -) and don’t have to type your legacy address. +You can query individual neurons to learn more about them such as the dissolve delay, its age, its voting power, its state (locked, dissolving, dissolved). +To do that, issue the following commands on your networked computer. +Substitute …​ by the identifier of the neuron you are querying. +These commands query the governance canister. +NEURON_ID=... +CANISTER=rrkah-fqaaa-aaaaa-aaaaq-cai +RESULT="$(dfx canister --network=https://ic0.app --no-wallet call $CANISTER get_neuron_info "($NEURON_ID:nat64)" --output=raw)" +didc decode -t "(Result_2)" -d ~/Downloads/nns-ifaces-0.8.0/governance.did $RESULT +
+
+
+Enable disbursal by passing the KYC process +Before you can disburse ICPT from your dissolved genesis neuron you must pass KYC. +Note that this applies only to genesis neurons such as the ones given to seed donors. +It does not apply to neurons that you later create by staking already-liquid ICPT. +
+Derive your DFN address +The DFINITY Chrome extension generated a 12-word mnemonic seed phrase. From that seed phrase, an Ethereum-style address can be derived, which was referred to in the Chrome extension as the "DFN address". The KYC process requires that you submit your DFN address along with other information. +
+Using Keysmith +The easiest way to obtain your DFN address is to derive it from your seed phrase using Keysmith. The section already explained how to set up Keysmith and write your seed phrase into a file in a safe way. We assume here that you have carried out the steps at least up until that point. It is not important whether you have carried out any of the remaining steps on the way to claim your neurons. It is also not important whether you have installed the DFINITY Canister SDK. You only need Keysmith. +Derive your DFN address. +echo $seed | keysmith legacy-address -f - +The command above displays output similar to a typical Ethereum address, but without the leading 0x prefix, and you will use it without the 0x prefix. +
+
+Using the DFINITY Chrome extension +Alternatively, you may have already written down your DFN address when you ran the Chrome extension to make the donation, or taken a screenshot of it. In this case, you can use the DFN address from there and you do not have to derive it from your seed phrase. The following is to remind you where it was visible in the Chrome extension. +On the Chrome extension’s main page there was an information button (“i” in blue circle) next to the DFN balance: + + + + +Extension + +Clicking it presented a window displaying the DFN address: + + + + +Address + +The DFN address displayed in the Chrome extension has a 4-byte checksum at the end and the 0x prefix. For our purposes here, you have to delete the last 8 characters and the prefix. For example: 0x98b20cae8074067c29c07a0a4ad94346cc33ee948bdcfe41 becomes 98b20cae8074067c29c07a0a4ad94346cc33ee94 which is 40 hex characters long. +
+
+
+Derive your principal identifier +The KYC form will also ask you for your principal. Derive it with Keysmith. +echo $seed | keysmith principal -f - +The command above will display your principal identifier, which should look something like this: a56gn-wnhrl-i76df-ewgfe-23jfd-dfh03-ergrg-fesr1-1jhs9-reg2o-ure +You will be asked to enter your principal identifier on the KYC form. +
+
+Submit your information +To submit your information, you first go to the KYC landing page. +The landing page is a frontend hosted by the DFINITY Foundation and any information entered here is not shared with the external KYC provider. +If the DFN address is valid, you are forwarded to the KYC main page. +If you are not forwarded and instead see "Address not found" then your DFN address is invalid. Please double-check the address. For troubleshooting, see the subsection below. +Once you are on the KYC main page, you can submit your personal identifying information (PII). +Information entered on this page will be sent directly to the KYC provider. +
+
+Troubleshooting +If you have problems with your DFN address, then you can verify it using Etherscan. +After you connect to Etherscan, scroll down to row “51. tokens”, open the dropdown form by expanding the row, paste your DFN address in the field “<input> (address)” and click “Query”. For the example address 2d89d96b10f7a9456a9154b2f5309ee70df5bce1 you will see: + + + + +Etherscan + +If you made a seed donation then you will see the token amount that the FDC calculated. If the DFN address is incorrect then it will show a token amount of 0. +
+
+
+Instruct the neurons you wish to unstake to dissolve +Once you have claimed your neurons and completed the KYC process, you can start "dissolving" your neurons. +YOU ARE HIGHLY ENCOURAGED TO READ THIS BLOG POST BEFORE YOU START DISSOLVING YOUR NEURONS. THERE ARE MANY BENEFITS TO NEURON OWNERSHIP. BE SURE YOU UNDERSTAND EXACTLY WHAT YOU ARE GIVING UP BY DISSOLVING THEM. IN PARTICULAR, YOUR NEURONS A PRE-AGED AT 18-MONTHS, MEANING THAT YOUR VOTING REWARDS RECEIVE A MULTIPLIER EFFECT, WHICH YOU WILL LOSE WHEN YOUR NEURONS ENTER THE DISSOLVE STATE. +Dissolving a neuron is not instantaneous, but rather takes place over a period of time known as the "dissolve delay". +The dissolve delay is a parameter of the individual neuron. In general, different neurons have different dissolve delays. +When a neuron is dissolving, its dissolve delay falls over the passage of time, until either it is stopped by you, or it reaches zero. +Once the dissolve delay reaches zero, it stops falling, and only then can you instruct the neuron to disburse your ICP tokens. +Your neurons have dissolve delays of 0,1,2,…​,30 or 48 months. +To start the dissolution of one of your neurons, you must sign and send a message to the governance canister. You can accomplish this in one step on a networked computer using dfx canister call, or as two separate steps, one on an air-gapped computer using dfx canister sign, and another on a networked computer using dfx canister send. We strongly recommend the latter approach to reduce the risk of having your private key compromised. +
+Dissolve in one step (not recommended) +Verify that you can connect to the Internet Computer. +dfx ping https://ic0.app +Recall the identifier of the neuron you want to dissolve and declare it as an environment variable. +NEURON_ID=... +Call the governance canister to dissolve your neuron. +CANISTER=rrkah-fqaaa-aaaaa-aaaaq-cai +RESULT="$(dfx canister --network=https://ic0.app --no-wallet call $CANISTER manage_neuron "(record { id = opt record { id = $NEURON_ID:nat64 }; command = opt variant { Configure = record { operation = opt variant { StartDissolving = record {} } } } })" --output=raw)" +didc decode -t "(ManageNeuronResponse)" -d ~/Downloads/nns-ifaces-0.8.0/governance.did $RESULT +Note that if you want to dissolve all of your neurons, then you must repeat the step above for each neuron identifier. +
+
+Dissolve in two steps +
+On your air-gapped computer +Recall the identifier of the neuron you want to dissolve and declare it as an environment variable. +NEURON_ID=... +Sign a message to dissolve your neurons. +Recall the behavior of the --expire-after option to ensure that you deliver the message within the correct 5-minute window. +CANISTER=rrkah-fqaaa-aaaaa-aaaaq-cai +dfx canister --network=https://ic0.app --no-wallet sign --expire-after=1h $CANISTER manage_neuron "(record { id = opt record { id = $NEURON_ID:nat64 }; command = opt variant { Configure = record { operation = opt variant { StartDissolving = record {} } } } })" +The command above results in a message.json file in your current directory. You must copy that file from your air-gapped computer to your networked computer. How you do this will depend on your configuration. +
+
+On your networked computer +Verify that you can connect to the Internet Computer. +dfx ping https://ic0.app +Send the signed message to the governance canister to dissolve your neurons. As previously mentioned, you can only perform this action within the 5-minute window that you specified. +dfx canister --network=https://ic0.app --no-wallet send message.json +
+
+
+
+Disburse ICP from neurons that are fully dissolved +To disburse the ICP tokens locked your neuron, you must sign and send a message to the governance canister. As mentioned in previous sections, this can be accomplished in one step or two steps, and we recommend the latter. +
+Disburse in one step (not recommended) +Verify that you can connect to the Internet Computer. +dfx ping https://ic0.app +Recall your account identifier and declare it as an environment variable. +ACCOUNT_ID=$(echo $seed | keysmith account -f -) +Recall the identifier of the neuron you want to dissolve and declare it as an environment variable. +NEURON_ID=... +Disburse the ICP tokens locked in your neuron. +CANISTER=rrkah-fqaaa-aaaaa-aaaaq-cai +ACCOUNT_ID_WITHOUT_CHECKSUM_BYTES="$(printf ${ACCOUNT_ID:8} | fold -w 2 | xargs -I {} printf '%d:nat8; ' '0x{}')" +RESULT="$(dfx canister --network=https://ic0.app --no-wallet call $CANISTER manage_neuron "(record { id = opt record { id = $NEURON_ID:nat64 }; command = opt variant { Disburse = record { to_account = opt record { hash = vec { $ACCOUNT_ID_WITHOUT_CHECKSUM_BYTES } }; amount = null } } })" --output=raw)" +didc decode -t "(ManageNeuronResponse)" -d ~/Downloads/nns-ifaces-0.8.0/governance.did $RESULT +
+
+Disburse in two steps +
+On your air-gapped computer +Recall your account identifier and declare it as an environment variable. +ACCOUNT_ID=$(echo $seed | keysmith account -f -) +Recall the identifier of the neuron you want to dissolve and declare it as an environment variable. +NEURON_ID=... +Sign a message to disburse the ICP tokens locked your neuron. +Recall the behavior of the --expire-after option to ensure you that you deliver the message within the correct 5-minute window. +CANISTER=rrkah-fqaaa-aaaaa-aaaaq-cai +ACCOUNT_ID_WITHOUT_CHECKSUM_BYTES="$(printf ${ACCOUNT_ID:8} | fold -w 2 | xargs -I {} printf '%d:nat8; ' '0x{}')" +dfx canister --network=https://ic0.app --no-wallet sign --expire-after=1h $CANISTER manage_neuron "(record { id = opt record { id = $NEURON_ID:nat64 }; command = opt variant { Disburse = record { to_account = opt record { hash = vec { $ACCOUNT_ID_WITHOUT_CHECKSUM_BYTES } }; amount = null } } })" +The command above results in a message.json file in your current directory. You must copy that file from your air-gapped computer to your networked computer. How you do this will depend on your configuration. +
+
+On your networked computer +Verify that you can connect to the Internet Computer. +dfx ping https://ic0.app +Send the signed message to the governance canister to disburse the ICP tokens locked your neuron. As previously mentioned, you can only perform this action within the 5-minute window that you specified. +dfx canister --network=https://ic0.app --no-wallet send message.json +
+
+
+
\ No newline at end of file diff --git a/modules/token-holders/pages/self-custody-quickstart.xml b/modules/token-holders/pages/self-custody-quickstart.xml new file mode 100644 index 000000000..b81d2c6de --- /dev/null +++ b/modules/token-holders/pages/self-custody-quickstart.xml @@ -0,0 +1,185 @@ + + + +
+ +Self-custody quick start +2021-08-05 + +Within the Internet Computer ecosystem, Internet Computer Protocol tokens (ICP tokens) are a native utility token. +ICP tokens play a key role in both the governance and economics of the Internet Computer. +This Self-Custody Quick Start scenario assumes: + + +You are a new ICP token holder. + + +You want to understand what you can do with your ICP tokens. + + +You want to know how to convert, transfer, or lock your ICP tokens using the {sdk-short-name} command-line interface DFX. + + +If you aren’t yet a token holder, you’ll need to purchase ICP tokens from an exchange or receive a token grant before you can take custody. For an overview of how to get ICP tokens and custody options, see How you can get ICP tokens and Choosing self-custody for digital assets. +If you are using another application—such as the Network Nervous System (NNS) application or the user interface provided by a hardware wallet—to interact with your ICP tokens, you should refer to the documentation for that application. +This Self-Custody Quick Start focuses solely on interacting with ICP tokens using the {sdk-short-name} command-line interface DFX. +
+How you can use ICP tokens +The following diagram provides a simplified overview of the three most common ways you can use tokens. + + + + +developers guide:icp tokens how to use + +As this diagram suggests, how you use ICP tokens depends primarily on your goals in acquiring them. +If you are a developer or entrepreneur, ICP tokens can be converted to cycles. Cycles can then be used to build and deploy applications to deliver products and services to the market. +If you are a member of the community interested in participating in governance and influencing the direction of the Internet Computer, you can lock up ICP tokens in a stake—called a neuron—so that you can submit and vote on proposals. +
+
+Before you begin +To get started, verify the following: + + +You have an internet connection and access to a shell terminal on your local Intel-based macOS or Linux computer. + + +You know how to open a new terminal shell on your local computer and how to run basic command-line programs in the terminal. + + +You hold ICP tokens in a self-custody wallet. + + +You have downloaded and installed the {sdk-long-name} by running the following command in a terminal on your local computer: +sh -ci "$(curl -fsSL https://sdk.dfinity.org/install.sh)" + + +You have created a backup copy of the public/private key for the identity you are using for self-custody. +For example, if you are using the default developer identity created using the {sdk-long-name} dfx command-line interface, +you should have a backup of the ~/.config/dfx/identity/default/identity.pem file stored in a secure location. + + +You have a secure environment in which to perform operations involving ICP tokens. +As a security best practice, any operations that involve the transfer of ICP tokens would require both an air-gapped computer with minimal hardware and software and a computer connected to the network. +In practice, this requires moving files between two computers and taking other precautions to minimize risks. +For simplicity, this Self-custody quick start describes how to complete key tasks using a single computer connected to the network. + + +
+
+Connect to the ledger and get your account identifier +All ICP token transactions are recorded in a ledger canister running on the Internet Computer. +These instructions assume that you are using the default developer identity that dfx has created for you. +This identity is represented by a principal data type and a textual representation of the principal often referred to as your principal identifier. +This representation of your identity is similar to a Bitcoin or Ethereum address. +However, the principal associated with your developer identity is typically not the same as your account identifier in the ledger. The principal identifier and the account identifier are related—both provide a textual representation of your identity—but they use different formats. +To connect to the ledger and get account information: + + +Create an empty dfx.json file in your current directory by running the following command: +echo '{}' > dfx.json + + +Check the current status of the Internet Computer network and your ability to connect to it by running the following command +dfx ping ic +You should see output similar to the following: +{ + "ic_api_version": "0.18.0" "impl_hash": "d639545e0f38e075ad240fd4ec45d4eeeb11e1f67a52cdd449cd664d825e7fec" "impl_version": "8dc1a28b4fb9605558c03121811c9af9701a6142" "replica_health_status": "healthy" "root_key": [48, 129, 130, 48, 29, 6, 13, 43, 6, 1, 4, 1, 130, 220, 124, 5, 3, 1, 2, 1, 6, 12, 43, 6, 1, 4, 1, 130, 220, 124, 5, 3, 2, 1, 3, 97, 0, 129, 76, 14, 110, 199, 31, 171, 88, 59, 8, 189, 129, 55, 60, 37, 92, 60, 55, 27, 46, 132, 134, 60, 152, 164, 241, 224, 139, 116, 35, 93, 20, 251, 93, 156, 12, 213, 70, 217, 104, 95, 145, 58, 12, 11, 44, 197, 52, 21, 131, 191, 75, 67, 146, 228, 103, 219, 150, 214, 91, 155, 180, 203, 113, 113, 18, 248, 71, 46, 13, 90, 77, 20, 80, 95, 253, 116, 132, 176, 18, 145, 9, 28, 95, 135, 185, 136, 131, 70, 63, 152, 9, 26, 11, 170, 174] +} + + +(Optional) Confirm the developer identity you are currently using by running the following command: +dfx identity whoami +In most cases, you should see that you are currently using your default developer identity. +For example: +default + + +(Optional) View the textual representation of the principal for your current identity by running the following command: +dfx identity get-principal +This command displays output similar to the following: +tsqwz-udeik-5migd-ehrev-pvoqv-szx2g-akh5s-fkyqc-zy6q7-snav6-uqe + + +Get the account identifier for your developer identity by running the following command: +dfx ledger account-id +This command displays the ledger account identifier associated with your developer identity. +For example, you should see output similar to the following: +03e3d86f29a069c6f2c5c48e01bc084e4ea18ad02b0eec8fccadf4487183c223 + + +Check your account balance by running the following command: +dfx ledger --network ic balance +This command displays the ICP token balance from the ledger account. +For example, you should see output similar to the following: +10.00000000 ICP + + +
+
+Convert ICP tokens to cycles +If you want to use your ICP tokens in your ledger account to power application development, you first must convert them to cycles and transfer the cycles to a canister that will be your cycles wallet. +To convert ICP tokens to cycles: + + +Create a new canister with cycles by transferring ICP tokens from your ledger account by running a command similar to the following: +dfx ledger --network ic create-canister <controller-principal-identifier> --amount <icp-tokens> +This command converts the number of ICP tokens you specify for the --amount argument into cycles, and associates the cycles with a new canister identifier controlled by the principal you specify. +For example, the following command converts 1.25 ICP tokens into cycles and specifies the principal identifier for the default identity as the controller of the new canister: +dfx ledger --network ic create-canister tsqwz-udeik-5migd-ehrev-pvoqv-szx2g-akh5s-fkyqc-zy6q7-snav6-uqe --amount 1.25 +If the transaction is successful, the ledger records the event and you should see output similar to the following: +Transfer sent at BlockHeight: 20 +Canister created with id: "53zcu-tiaaa-aaaaa-qaaba-cai" + + +Install the cycles wallet code in the newly-created canister placeholder by running a command similar to the following: +dfx identity --network ic deploy-wallet <canister-identifer> +For example: +dfx identity --network ic deploy-wallet 53zcu-tiaaa-aaaaa-qaaba-cai +This command displays output similar to the following: +Creating a wallet canister on the ic network. +The wallet canister on the "ic" network for user "default" is "53zcu-tiaaa-aaaaa-qaaba-cai" + + +
+
+Transfer ICP tokens to another account +If you want to transfer ICP tokens to another account in the ledger, you need to know the account identifier for the destination account. +To transfer ICP tokens to another account: + + +Check that you are using an identity with control over the ledger account by running the following command: +dfx identity whoami + + +Check the current balance in the ledger account associated with your identity by running the following command: +dfx ledger --network ic balance + + +Transfer ICP tokens to another account by running a command similar to the following: +dfx ledger --network ic transfer <destination-ledger-account-id> --icp <ICP-amount> --memo <numeric-memo> +For example: +dfx ledger --network ic transfer ae6e1a76da5725bbbf0c5c035aaf0525b791e0f0f7cce27d8e27826389871406 --icp 5 --memo 12345 +This example illustrates how to transfer ICP tokens to the specified account using a whole number with the --icp command-line option. + + +You can also specify fractional units of ICP tokens—called e8s—using the --e8s option, either on its own or in conjunction with the --icp option. + + +Alternatively, you can use the --amount to specify the number of ICP tokens to transfer with fractional units up to 8 decimal places, for example, as 5.00000025. + + +The destination address can be an address in the ledger canister running on the Internet Computer network, an account you have added using the Network Nervous System application, or the address for a wallet you have on an exchange. +If you transfer the ICP tokens to an account in the Network Nervous System application, you might need to refresh the browser to see the transaction reflected. +For more information about using the dfx ledger command-line options, see dfx ledger. + + +
+
+Lock ICP tokens by staking them in a neuron +If you want to lock up ICP tokens to participate in governance and earn rewards, you must use the Network Nervous System (NNS) application or dfx canister call commands. +Because locking up ICP tokens to create staked neurons is a more complex process when using the {sdk-short-name} command-line interface than it is when using the Network Nervous System (NNS) application, the steps aren’t included in this guide. +For information about the Network Nervous System, see Understanding the Internet Computer’s Network Nervous System, Neurons, and ICP Utility Tokens. +For additional details about setting the locked period and dissolve delay for a neuron, see Getting Started | The Internet Computer Network Nervous System Application & Wallet +
+
\ No newline at end of file From 3f7b86b8ea2fd205bc881f623b14d8a016c01b63 Mon Sep 17 00:00:00 2001 From: dprats Date: Thu, 5 Aug 2021 13:48:20 -0700 Subject: [PATCH 2/4] convert some files to markdown --- modules/ROOT/nav.text | 352 +++++ modules/ROOT/pages/download.text | 65 + modules/ROOT/pages/http-middleware.text | 217 +++ modules/developers-guide/dev-nav.text | 75 + .../pages/about-this-guide.text | 6 + .../developers-guide/pages/cli-reference.text | 61 + .../pages/cli-reference/dfx-bootstrap.text | 96 ++ .../pages/cli-reference/dfx-build.text | 112 ++ .../pages/cli-reference/dfx-cache.text | 213 +++ .../pages/cli-reference/dfx-canister.text | 1249 +++++++++++++++++ .../pages/cli-reference/dfx-config.text | 103 ++ .../pages/cli-reference/dfx-deploy.text | 116 ++ .../pages/cli-reference/dfx-envars.text | 89 ++ .../pages/cli-reference/dfx-help.text | 40 + .../pages/cli-reference/dfx-identity.text | 583 ++++++++ .../pages/cli-reference/dfx-ledger.text | 496 +++++++ .../pages/cli-reference/dfx-new.text | 76 + .../pages/cli-reference/dfx-parent.text | 195 +++ .../pages/cli-reference/dfx-ping.text | 60 + .../pages/cli-reference/dfx-replica.text | 51 + .../pages/cli-reference/dfx-start.text | 86 ++ .../pages/cli-reference/dfx-stop.text | 63 + .../pages/cli-reference/dfx-upgrade.text | 65 + .../pages/computation-and-storage-costs.text | 135 ++ .../pages/concepts/canisters-code.text | 245 ++++ .../pages/concepts/concepts-intro.text | 37 + .../pages/concepts/data-centers.text | 71 + .../pages/concepts/governance.text | 41 + .../pages/concepts/nodes-subnets.text | 51 + .../pages/concepts/tokens-cycles.text | 139 ++ .../pages/concepts/what-is-IC.text | 78 + .../pages/customize-projects.text | 98 ++ .../pages/default-wallet.text | 579 ++++++++ .../developers-guide/pages/design-apps.text | 107 ++ modules/developers-guide/pages/glossary.text | 141 ++ .../pages/install-upgrade-remove.text | 140 ++ .../pages/lang-service-ide.text | 110 ++ .../developers-guide/pages/sample-apps.text | 127 ++ modules/developers-guide/pages/sdk-guide.text | 56 + .../pages/troubleshooting.text | 203 +++ .../pages/tutorials-intro.text | 85 ++ .../pages/tutorials/at-a-glance.text | 34 + .../pages/tutorials/calculator.text | 305 ++++ .../pages/tutorials/counter-tutorial.text | 303 ++++ .../pages/tutorials/custom-frontend.text | 438 ++++++ .../pages/tutorials/define-an-actor.text | 316 +++++ .../pages/tutorials/explore-templates.text | 553 ++++++++ .../pages/tutorials/hello-location.text | 330 +++++ .../pages/tutorials/intercanister-calls.text | 481 +++++++ .../pages/tutorials/multiple-actors.text | 321 +++++ .../tutorials/multiple-factorial-actors.text | 300 ++++ .../pages/tutorials/my-contacts.text | 403 ++++++ .../pages/tutorials/phonebook.text | 261 ++++ .../pages/tutorials/scalability-cancan.text | 171 +++ .../pages/tutorials/simple-cycles.text | 298 ++++ .../pages/webpack-config.text | 320 +++++ .../pages/work-with-languages.text | 516 +++++++ .../pages/working-with-canisters.text | 458 ++++++ 58 files changed, 12720 insertions(+) create mode 100644 modules/ROOT/nav.text create mode 100644 modules/ROOT/pages/download.text create mode 100644 modules/ROOT/pages/http-middleware.text create mode 100644 modules/developers-guide/dev-nav.text create mode 100644 modules/developers-guide/pages/about-this-guide.text create mode 100644 modules/developers-guide/pages/cli-reference.text create mode 100644 modules/developers-guide/pages/cli-reference/dfx-bootstrap.text create mode 100644 modules/developers-guide/pages/cli-reference/dfx-build.text create mode 100644 modules/developers-guide/pages/cli-reference/dfx-cache.text create mode 100644 modules/developers-guide/pages/cli-reference/dfx-canister.text create mode 100644 modules/developers-guide/pages/cli-reference/dfx-config.text create mode 100644 modules/developers-guide/pages/cli-reference/dfx-deploy.text create mode 100644 modules/developers-guide/pages/cli-reference/dfx-envars.text create mode 100644 modules/developers-guide/pages/cli-reference/dfx-help.text create mode 100644 modules/developers-guide/pages/cli-reference/dfx-identity.text create mode 100644 modules/developers-guide/pages/cli-reference/dfx-ledger.text create mode 100644 modules/developers-guide/pages/cli-reference/dfx-new.text create mode 100644 modules/developers-guide/pages/cli-reference/dfx-parent.text create mode 100644 modules/developers-guide/pages/cli-reference/dfx-ping.text create mode 100644 modules/developers-guide/pages/cli-reference/dfx-replica.text create mode 100644 modules/developers-guide/pages/cli-reference/dfx-start.text create mode 100644 modules/developers-guide/pages/cli-reference/dfx-stop.text create mode 100644 modules/developers-guide/pages/cli-reference/dfx-upgrade.text create mode 100644 modules/developers-guide/pages/computation-and-storage-costs.text create mode 100644 modules/developers-guide/pages/concepts/canisters-code.text create mode 100644 modules/developers-guide/pages/concepts/concepts-intro.text create mode 100644 modules/developers-guide/pages/concepts/data-centers.text create mode 100644 modules/developers-guide/pages/concepts/governance.text create mode 100644 modules/developers-guide/pages/concepts/nodes-subnets.text create mode 100644 modules/developers-guide/pages/concepts/tokens-cycles.text create mode 100644 modules/developers-guide/pages/concepts/what-is-IC.text create mode 100644 modules/developers-guide/pages/customize-projects.text create mode 100644 modules/developers-guide/pages/default-wallet.text create mode 100644 modules/developers-guide/pages/design-apps.text create mode 100644 modules/developers-guide/pages/glossary.text create mode 100644 modules/developers-guide/pages/install-upgrade-remove.text create mode 100644 modules/developers-guide/pages/lang-service-ide.text create mode 100644 modules/developers-guide/pages/sample-apps.text create mode 100644 modules/developers-guide/pages/sdk-guide.text create mode 100644 modules/developers-guide/pages/troubleshooting.text create mode 100644 modules/developers-guide/pages/tutorials-intro.text create mode 100644 modules/developers-guide/pages/tutorials/at-a-glance.text create mode 100644 modules/developers-guide/pages/tutorials/calculator.text create mode 100644 modules/developers-guide/pages/tutorials/counter-tutorial.text create mode 100644 modules/developers-guide/pages/tutorials/custom-frontend.text create mode 100644 modules/developers-guide/pages/tutorials/define-an-actor.text create mode 100644 modules/developers-guide/pages/tutorials/explore-templates.text create mode 100644 modules/developers-guide/pages/tutorials/hello-location.text create mode 100644 modules/developers-guide/pages/tutorials/intercanister-calls.text create mode 100644 modules/developers-guide/pages/tutorials/multiple-actors.text create mode 100644 modules/developers-guide/pages/tutorials/multiple-factorial-actors.text create mode 100644 modules/developers-guide/pages/tutorials/my-contacts.text create mode 100644 modules/developers-guide/pages/tutorials/phonebook.text create mode 100644 modules/developers-guide/pages/tutorials/scalability-cancan.text create mode 100644 modules/developers-guide/pages/tutorials/simple-cycles.text create mode 100644 modules/developers-guide/pages/webpack-config.text create mode 100644 modules/developers-guide/pages/work-with-languages.text create mode 100644 modules/developers-guide/pages/working-with-canisters.text diff --git a/modules/ROOT/nav.text b/modules/ROOT/nav.text new file mode 100644 index 000000000..a3ec94dc5 --- /dev/null +++ b/modules/ROOT/nav.text @@ -0,0 +1,352 @@ +--- +date: 2021-08-05 +title: Untitled +--- + +- [**Introduction**](introduction:welcome.xml) + + - [For: First-Timers](introduction:welcome.xml#for-first-timers) + + - [For: Developers](introduction:welcome.xml#for-developers) + + - [For: Protocol + Enthusiasts](introduction:welcome.xml#for-protocol-enthusiasts) + +- [Quick Start](quickstart:quickstart-intro.xml) + + - [Local Development](quickstart:local-quickstart.xml) + + - [Network Deployment](quickstart:network-quickstart.xml) + +- Developer Docs + + - Getting Started + + - Introducing the SDK + + - [Install, upgrade, or remove + software](developers-guide:install-upgrade-remove.xml) + + - [Release notes](release-notes:sdk-release-notes.xml) + + - [0.8.0](release-notes:0.8.0-rn.xml) + + - [0.7.7](release-notes:0.7.7-rn.xml) + + - [0.7.2](release-notes:0.7.2-rn.xml) + + - [0.7.1](release-notes:0.7.1-rn.xml) + + - [0.7.0](release-notes:0.7.0-rn.xml) + + - [0.6.26](release-notes:0.6.26-rn.xml) + + - [0.6.25](release-notes:0.6.25-rn.xml) + + - [0.6.24](release-notes:0.6.24-rn.xml) + + - [0.6.23](release-notes:0.6.23-rn.xml) + + - [0.6.22](release-notes:0.6.22-rn.xml) + + - [0.6.21](release-notes:0.6.21-rn.xml) + + - [0.6.20](release-notes:0.6.20-rn.xml) + + - Introducing DFX + + - [DFX commands](developers-guide:cli-reference.xml) + + - [DFX environment + variables](developers-guide:cli-reference/dfx-envars.xml) + + - [Glossary](developers-guide:glossary.xml) + + - Building on the Internet Computer + + - Learn how to: + + - [Develop software on the + IC](developers-guide:sdk-guide.xml) + + - [Design apps](developers-guide:design-apps.xml) + + - [Manage + projects](developers-guide:customize-projects.xml) + + - [Manage + canisters](developers-guide:working-with-canisters.xml) + + - [Use the default cycles + wallet](developers-guide:default-wallet.xml) + + - [Explore the default + project](developers-guide:tutorials/explore-templates.xml) + + - [Query using an + actor](developers-guide:tutorials/define-an-actor.xml) + + - [Pass text + arguments](developers-guide:tutorials/hello-location.xml) + + - [Increment a natural + number](developers-guide:tutorials/counter-tutorial.xml) + + - [Use integers in calculator + functions](developers-guide:tutorials/calculator.xml) + + - [Import library + modules](developers-guide:tutorials/phonebook.xml) + + - [Use multiple + actors](developers-guide:tutorials/multiple-actors.xml) + + - [Make inter-canister + calls](developers-guide:tutorials/intercanister-calls.xml) + + - [Add access control with + identities](developers-guide:tutorials/access-control.xml) + + - [Accept cycles from a + wallet](developers-guide:tutorials/simple-cycles.xml) + + - [Troubleshoot + issues](developers-guide:troubleshooting.xml) + + - Explore our languages + + - [Develop using different + languages](developers-guide:work-with-languages.xml) + + - [Motoko](language-guide:motoko.xml) + + - [Motoko + Playground](https://m7sm4-2iaaa-aaaab-qabra-cai.raw.ic0.app/) + + - [Motoko Base + Library](base-libraries:stdlib-intro.xml) + + - Motoko Guide + + - [About the language + guide](language-guide:about-this-guide.xml) + + - [Introduction](language-guide:motoko-introduction.xml) + + - [Basic concepts and + terms](language-guide:basic-concepts.xml) + + - [Mutable + state](language-guide:mutable-state.xml) + + - [Local objects and + classes](language-guide:local-objects-classes.xml) + + - [Actors and async + data](language-guide:actors-async.xml) + + - [Error handling](language-guide:errors.xml) + + - [Pattern + matching](language-guide:pattern-matching.xml) + + - [Sharing data and + behavior](language-guide:sharing.xml) + + - [Modules and + imports](language-guide:modules-and-imports.xml) + + - [Imperative control + flow](language-guide:control-flow.xml) + + - [Structural + equality](language-guide:structural-equality.xml) + + - [Actor + classes](language-guide:actor-classes.xml) + + - [Principals and caller + identification](language-guide:caller-id.xml) + + - [Managing cycles](language-guide:cycles.xml) + + - [Stable variables and upgrade + methods](language-guide:upgrades.xml) + + - [Language quick + reference](language-guide:language-manual.xml) + + - [Compiler + reference](language-guide:compiler-ref.xml) + + - [Motoko + grammar](language-guide:motoko-grammar.xml) + + - [Motoko style + guidelines](language-guide:style.xml) + + - [Rust](rust-guide:rust-intro.xml) + + - [Hello, World! Quick + Start](rust-guide:rust-quickstart.xml) + + - [Simple counter + tutorial](rust-guide:rust-counter.xml) + + - [Basic dependency + tutorial](rust-guide:multiply-dependency.xml) + + - [Profile tutorial](rust-guide:rust-profile.xml) + + - [Optimize a Rust + program](rust-guide:rust-optimize.xml) + + - [Candid](candid-guide:candid-intro.xml) + + - [What is Candid?](candid-guide:candid-concepts.xml) + + - [How to](candid-guide:candid-howto.xml) + + - [Reference](candid-guide:candid-ref.xml) + + - [Supported types](candid-guide:candid-types.xml) + + - [Candid + specification](https://github.com/dfinity/candid) + + - [Candid Rust crate](https://docs.rs/candid) + + - Introducing the Internet Identity + + - [What is Internet + Identity](ic-identity-guide:what-is-ic-identity.xml) + + - [How to use the Internet + Identity](ic-identity-guide:auth-how-to.xml) + + - Frontend development + + - [Add frontend + assets](developers-guide:webpack-config.xml) + + - [Customize the + front-end](developers-guide:tutorials/custom-frontend.xml) + + - [Add a + stylesheet](developers-guide:tutorials/my-contacts.xml) + +- Protocol Docs + + - .[Concepts](developers-guide:concepts/concepts-intro.xml) + + - [What is the {IC}](developers-guide:concepts/what-is-IC.xml) + + - [Internet Computer Interface + Specification](interface-spec:index.xml) + + - [Nodes and + sub-networks](developers-guide:concepts/nodes-subnets.xml) + + - [Decentralized data + centers](developers-guide:concepts/data-centers.xml) + + - [Canisters and + code](developers-guide:concepts/canisters-code.xml) + + - [Tokens and + cycles](developers-guide:concepts/tokens-cycles.xml) + + - [Neurons and + governance](developers-guide:concepts/governance.xml) + +- General Docs + + - Overview of self-custody + + - [Choosing self-custody for digital + assets](token-holders:custody-options-intro.xml) + + - [Self-custody quick + start](token-holders:self-custody-quickstart.xml) + + - Overview of ledger + + - [Ledger quick start](integration:ledger-quick-start.xml) + + - Overview of the NNS App + + - [NNS App quick start](token-holders:nns-app-quickstart.xml) + +- Additional Resources + + - Developer videos + + - [Internet + Identity](https://www.youtube.com/watch?v=oxEr8UzGeBo&list=PLuhDt1vhGcrf4DgKZecU3ar_RA1cB0vUT&index=11&ab_channel=DFINITY) + + - [Motoko](https://www.youtube.com/watch?v=4eSceDOS-Ms&list=PLuhDt1vhGcrf4DgKZecU3ar_RA1cB0vUT&index=21&ab_channel=DFINITY) + + - [Building a multiplayer game for the Internet + Computer](https://www.youtube.com/watch?v=GzkRsbqPaA0&ab_channel=DFINITY) + + - [Deploying static sites to the Internet + Computer](https://www.youtube.com/watch?v=b_nc6yx5_DQ&list=PLuhDt1vhGcrf4DgKZecU3ar_RA1cB0vUT&index=7&ab_channel=DFINITY) + + - [Zero to fullstack: web apps on the Internet Computer + ](https://www.youtube.com/watch?v=2miweY9-vZc&list=PLuhDt1vhGcrf4DgKZecU3ar_RA1cB0vUT&index=6&ab_channel=DFINITY) + + - Protocol videos + + - [Technical library](https://dfinity.org/technicals/) + + - Developer tooling + + - [DFINITY Canister SDK](ROOT:download.xml) + + - [Rust CDK](https://github.com/dfinity/cdk-rs) + + - [Vessel Package + Manager](https://github.com/kritzcreek/vessel) + + - [Motoko VS Code + Extension](https://marketplace.visualstudio.com/items?itemName=dfinity-foundation.vscode-motoko) + + - [Agent JS](https://github.com/dfinity/agent-js) + + - [Sudograph](https://github.com/sudograph/sudograph) + + - [Cycles Wallet](https://github.com/dfinity/cycles-wallet) + + - [Motoko + Playground](https://m7sm4-2iaaa-aaaab-qabra-cai.raw.ic0.app/) + + - [Quill](https://github.com/dfinity/quill) + + - Examples + + - [Awesome + DFINITY](https://github.com/dfinity/awesome-dfinity) + + - [CanCan](https://github.com/dfinity/cancan) + + - [Mini Motoko examples](https://github.com/dfinity/examples) + + - Community created resources + + - [ic.rocks (Block explorer)](https://ic.rocks/) + + - [Plug (Browser-based wallet + extension)](https://plugwallet.ooo/) + + - [Fleek (Netlify for the open web)](https://fleek.co/) + + - [Cycles Faucet](http://faucet.dfinity.org/) + + - [Computation and Storage + Costs](developers-guide:computation-and-storage-costs.xml) + +- Community + + - [Developer Discord](https://discord.gg/cA7y6ezyE2) + + - [Developer Forum](https://forum.dfinity.org/) diff --git a/modules/ROOT/pages/download.text b/modules/ROOT/pages/download.text new file mode 100644 index 000000000..0d378e05d --- /dev/null +++ b/modules/ROOT/pages/download.text @@ -0,0 +1,65 @@ +--- +date: 2021-08-05 +title: Download center +--- + +Currently, you can download the {sdk-long-name} directly from within a +terminal shell on your local computer. With this installation option, +you can be logged on as any user and no additional software is required. + +# Install the latest directly from a terminal {#install-latest} + +To download and install from a terminal shell: + +1. Open a terminal shell on your local computer. + + For example, on macOS open the Applications folder, then open + Utilities and double-click **Terminal**. + +2. Download and install the SDK package by running the following `curl` + command: + + ``` bash + sh -ci "$(curl -fsSL https://sdk.dfinity.org/install.sh)" + ``` + +# Install a specific version from a terminal {#install-version} + +If you want to install a specific version, for example, to test against +a previous version, you can modify the installation command to include a +version. + +To download and install a specific version from a terminal shell: + +1. Open a terminal shell on your local computer. + +2. Set the `DFX_VERSION` environment variable to the version of the + {sdk-short-name} package you want to install as a prefix to `curl` + command. + + For example, to install version 0.8.0, you would run the following + command: + + ``` bash + DFX_VERSION=0.8.0 sh -ci "$(curl -fsSL https://sdk.dfinity.org/install.sh)" + ``` + +::: note +If you are using the DFX_VERSION environment variable to install a +version of the {sdk-short-name} not yet publicly available, see this +[article](http-middleware.xml) for an overview of what's changed. +::: + +# Next steps {#_next_steps} + +For information about the next steps to take, see +[Tutorials](developers-guide/tutorials-intro.xml) in the [*SDK Developer +Tools*](developers-guide/sdk-guide.xml). + +To learn more about writing programs for the Internet Computer before +you start experimenting with code, see +[Concepts](developers-guide/concepts/concepts-intro.xml). + +For information about writing programs for the Internet Computer using +Motoko, see the [*Motoko Programming Language +Guide*](language-guide/motoko.xml). diff --git a/modules/ROOT/pages/http-middleware.text b/modules/ROOT/pages/http-middleware.text new file mode 100644 index 000000000..788ba7abd --- /dev/null +++ b/modules/ROOT/pages/http-middleware.text @@ -0,0 +1,217 @@ +--- +date: 2021-08-05 +title: Introducing a new approach to handling HTTP requests and serving + assets +--- + +If you are installing any 0.7.0 (or later) version of the +{sdk-short-name}, you might have noticed that those versions have +introduced some major improvements for handling HTTP queries and +front-end assets. When these changes are officially rolled into the next +publicly-available release of the {sdk-short-name}, they will change how +you build and deploy applications on the Internet Computer. + +If you are creating new projects, the changes to the underlying +architecture will have little, if any, effect on your development +workflow. In fact, you might find that the new architecture makes +building applications that run on the Internet Computer a more familiar +experience. + +If you have any existing projects, however, you'll need to plan for a +one-time migration to the new architecture. Migration to the new +architecture doesn't have to be completed immediately, but updating your +projects to take advantage of the changes will ultimately make it easier +to upload and manage front-end assets. + +# Replacing the bootstrap code: a recap {#_replacing_the_bootstrap_code_a_recap} + +Before we describe the new architecture, it's useful to have some +context about the old approach that we are replacing and how the code +has worked up to this point. Previously, developing a front-end on the +Internet Computer involved adding a front-end assets canister with a +`retrieve()` function. The `retrieve()` function would take a path and +return a blob. The blob returned by the `retrieve()` function would then +have an `index.js` file that contained some JavaScript and static HTML +called the `bootstrap` code. After you deployed an application as smart +contract---called a +[canister](developers-guide/glossary.xml#g-canister)---on the Internet +Computer, accessing the canister using the `.ic0.app` URL +executed the `bootstrap` code, which in turn, performed the following +steps: + +- Created a secure worker to contain your private key. + +- Polyfilled the `window.ic` to provide some mechanics to the running + application so that it can communicate with the Internet Computer. + +- Called the canister's `retrieve()` method with `index.js` as the + path, and evaluate it. + +- Passed control of the document object model (DOM) and the page to + the canister's JavaScript code. + +This `bootstrap` workflow is quite different from how people usually +build web applications. For example, this approach did not support +loading HTML directly or downloading assets like PNG files. Asset +handling required either loading the assets from another domain (for +example, an AWS bucket) or loading the assets in JavaScript, +transforming them into data URI, then setting the `src` attribute +accordingly. Handling assets in this way led to problems in the browser, +such as: + +- Not waiting for re-layout of pages. + +- Deferred loading of assets. + +- Executing JavaScript out of band. + +The `bootstrap` approach provided advantages in terms of security and +decentralization, but those advantages were offset by the poor HTTP and +asset handling that front-end developers and application users didn't +expect to experience. + +Over the last year, the {sdk-short-name} team has been gathering and +evaluating feedback from the developer community. Based on that +feedback, the team has decided to provide a more flexible developer +experience while continuing to provide an equivalent security model. + +# Enabling canisters to respond to HTTP requests {#_enabling_canisters_to_respond_to_http_requests} + +After considering the advantages and disadvantages of different +proposals, the team decided on an architecture that would allow +canisters to answer HTTP requests directly. With this new approach, the +{sdk-short-name} implements an HTTP middleware server. + +The HTTP middleware server handles the processing for the HTTP request +by doing the following: + +- Receiving the HTTP request and converting its method, uri, headers + and body into a Candid structure. + +- Resolving the canister identifier for the request. + +- Instantiating an agent to talk to the canister. + +- Calling an `http_request()` query method. + +If the canister implements the `http_request()` method, the HTTP +middleware decodes the response, takes the headers and body, and +constructs an HTTP response. If the canister does not implement the +`http_request()` method, for backward compatibility, the middleware +returns a bootstrap polyfill that points out the deprecation as a +warning. For any errors in the process, the HTTP middleware returns the +following error codes: + +- 400 Bad Request for any invalid requests (for example, if the HTTP + middleware could not find or decode a canister ID). + +- 500 Internal Server Error for errors from the HTTP middleware itself + (for example, if it could not connect to a replica) + +- 502 Bad Gateway if an error is coming from the replica itself + (including canister trapping). + +If any of these errors occur, the `dfx` command-line interface provides +additional details in the response body. + +# Revisiting the asset storage canister {#_revisiting_the_asset_storage_canister} + +To make this transition easier, new and existing projects built with the +newer version of `dfx` will include an improved asset canister that +supports the `http_request()` method by default. This means that assets +you upload---including binary assets like images---will be available +directly from your browser using their URL. For example, in a new +project, the `sample-asset.txt` file would be uploaded and available +after publishing to the Internet Computer at +[https://\.raw.ic0.app/sample-asset.txt](https://.raw.ic0.app/sample-asset.txt). + +In the future, we will also provide additional support for managing the +asset canister cache, handling default assets, and providing +HTTP-specific features. + +# Routing {#_routing} + +Both the `/api` (for replicas) and `/_` (for tool purposes) routes are +reserved by the HTTP request specification. All other routes are +available for you to use as needed within your application, eliminating +the need to rely on a separate hash router. + +# Structure of a new DFX project {#_structure_of_a_new_dfx_project} + +Before going into how to migrate an existing project, let's take a look +at a new project. The front-end changes include the following: + +- The `dfx.json` includes a `frontend` key for the asset canister that + now points to an `index.html` file instead of the `index.js` + JavaScript entry point. + +- The `package.json` file now supports Webpack 5 by default. + +- The `webpack.config.js` file now generates the list of canister + imports for for each canister that has a `frontend` key in a + different way. + +- The `src/_assets/src/index.html` file is a new + template file that you can replace with your own `index.html` file + for your front-end. It is served by default by the asset canister + when a file isn't found. + +- The `index.js` file has been modified to support agent and actor + creation. + +# Agent and actor creation {#_agent_and_actor_creation} + +With the new architecture, we explicitly create an agent instance, then +create the actor that we'll use for our canister. In the `index.js` +file, this means that where before there was only one `import` from +files generated by `dfx`, now there are two. + +For example, the new `index.js` file in a project provides code similar +to this: + + import { Actor, HttpAgent } from '@dfinity/agent'; + import { idlFactory as example_idl, canisterId as example_id } from 'dfx-generated/example'; + + const agent = new HttpAgent(); + const example = Actor.createActor(example_idl, { agent, canisterId: example_id }); + +Explicitly creating the agent and actor like this example illustrates is +better for a couple reasons: + +- First, the agent itself is entirely configurable by the application, + and so is the actor. For example, authentication can only be set + when the agent is constructed, so if you want to manage a user + identity, you'll need to do it before creating the agent. + +- Second, being explicit about creating the agent and actor gives you + much more control over when you instantiate those objects. If you + want a React hook or an Angular service to create the actor, this + approach allows you to do so easily. + +# Migrating an existing project {#_migrating_an_existing_project} + +If you have an existing project, chances are it will not work seamlessly +after you update the {sdk-short-name}. Unfortunately, a direct migration +path isn't possible in this case. The best way to migrate your current +front-end is to create a new project and move your code manually to the +new structure. + +## Certified and uncertified front-end assets {#_certified_and_uncertified_front_end_assets} + +With the launch of the Internet Computer main network Beta, all projects +serve front-end assets use the new HTTP query architecture. In addition, +the Internet Computer launch introduces a new capability to serve +front-end assets as certified data that has been signed and can be +considered authenticated and secure or as raw, uncertified data. +Front-end assets that don't go through the certification process are +served using the `raw.ic0.app` URL suffix. Certified front-end assets +use the `.ic0.app` URL suffix. + +All of the current tutorials illustrate applications that serve +uncertified front-end assets. Learning how to build an application that +uses certified query results for front-end assets is an advanced +development topic. For information about how to return certified data in +response to queries, see the [Interface +specification](interface-spec/index.xml) and connect with other +developers through the [DFINITY Developer +Forum](https://forum.dfinity.org/). diff --git a/modules/developers-guide/dev-nav.text b/modules/developers-guide/dev-nav.text new file mode 100644 index 000000000..20cd0bbc7 --- /dev/null +++ b/modules/developers-guide/dev-nav.text @@ -0,0 +1,75 @@ +--- +date: 2021-05-09 +title: Untitled +--- + +- [Concepts](concepts/concepts-intro.xml) + + - [What is the {IC}](concepts/what-is-IC.xml) + + - [Nodes and sub-networks](concepts/nodes-subnets.xml) + + - [Decentralized data centers](concepts/data-centers.xml) + + - [Canisters and code](concepts/canisters-intro.xml) + + - [Tokens and cycles](concepts/tokens-cycles.xml) + + - [Neurons and governance](concepts/governance.xml) + +- [How to](sdk-guide.xml) + + - [Install, upgrade, or remove + software](install-upgrade-remove.xml) + + - [Design apps](customize-projects.xml) + + - [Manage projects](customize-projects.xml) + + - [Develop using different backend + languages](work-with-languages.xml) + + - [Add frontend assets](webpack-config.xml) + + - [Manage canisters](working-with-canisters.xml) + + - [Troubleshoot issues](troubleshooting.xml) + +- [Tutorials](tutorials-intro.xml) + + - [Explore the default project](tutorials/explore-templates.xml) + + - [Query using an actor](tutorials/define-an-actor.xml) + + - [Pass text arguments](tutorials/hello-location.xml) + + - [Increment a natural number](tutorials/counter-tutorial.xml) + + - [Use integers in calculator functions](tutorials/calculator.xml) + + - [Import library modules](tutorials/phonebook.xml) + + - [Use multiple actors](tutorials/multiple-actors.xml) + + - [Customize the front-end](tutorials/custom-frontend.xml) + + - [Add a stylesheet](tutorials/my-contacts.xml) + + - [Make inter-canister calls](tutorials/intercanister-calls.xml) + + - [Create scalable apps](tutorials/scalability-cancan.xml) + + - [Add access control with + identities](tutorials/access-control.xml) + +- [Reference](cli-reference.xml) + + - [DFX commands](cli-reference.xml) + + - [Candid interface description language](candid-reference.xml) + + - [Language server protocol client](lang-service-ide.xml) + + - [Glossary](glossary.xml) + +- [Examples](sample-apps.xml) diff --git a/modules/developers-guide/pages/about-this-guide.text b/modules/developers-guide/pages/about-this-guide.text new file mode 100644 index 000000000..e6f01515f --- /dev/null +++ b/modules/developers-guide/pages/about-this-guide.text @@ -0,0 +1,6 @@ +--- +date: 2020-06-05 +title: About this guide +--- + +# About this guide {#_about_this_guide} diff --git a/modules/developers-guide/pages/cli-reference.text b/modules/developers-guide/pages/cli-reference.text new file mode 100644 index 000000000..e1f68cdb3 --- /dev/null +++ b/modules/developers-guide/pages/cli-reference.text @@ -0,0 +1,61 @@ +--- +date: 2021-08-05 +title: Command-line reference +--- + +The DFINITY command-line execution environment (`dfx`) is the primary +tool for creating, deploying, and managing the applications you develop +for the Internet Computer platform. + +You can use the `dfx` parent command with different flags and +subcommands to perform different types of operations. + +The basic syntax for running `dfx` commands is: + +``` bash +dfx [option] [subcommand] [flag] +``` + +Depending on the subcommand, the options and flags you specify might +apply to the parent command or to a specific subcommand. For example, +the flags for enabling or suppressing verbose logging are specified for +the `dfx` parent command, then applied to any subcommands. + +When you have the {sdk-short-name} installed, you can use the following +commands to specify the operation you want to perform. For reference +information and examples that illustrate using these commands, select an +appropriate command. + +- [dfx](cli-reference/dfx-parent.xml) + +- [dfx bootstrap](cli-reference/dfx-bootstrap.xml) + +- [dfx build](cli-reference/dfx-build.xml) + +- [dfx cache](cli-reference/dfx-cache.xml) + +- [dfx canister](cli-reference/dfx-canister.xml) + +- [dfx config](cli-reference/dfx-config.xml) + +- [dfx deploy](cli-reference/dfx-deploy.xml) + +- [dfx help](cli-reference/dfx-help.xml) + +- [dfx identity](cli-reference/dfx-identity.xml) + +- [dfx ledger](cli-reference/dfx-ledger.xml) + +- [dfx new](cli-reference/dfx-new.xml) + +- [dfx ping](cli-reference/dfx-ping.xml) + +- [dfx replica](cli-reference/dfx-replica.xml) + +- [dfx start](cli-reference/dfx-start.xml) + +- [dfx stop](cli-reference/dfx-stop.xml) + +- [dfx upgrade](cli-reference/dfx-upgrade.xml) + +- [dfx wallet](cli-reference/dfx-wallet.xml) diff --git a/modules/developers-guide/pages/cli-reference/dfx-bootstrap.text b/modules/developers-guide/pages/cli-reference/dfx-bootstrap.text new file mode 100644 index 000000000..b6d17e2c6 --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-bootstrap.text @@ -0,0 +1,96 @@ +--- +date: 2021-08-05 +title: dfx bootstrap +--- + +Use the `dfx bootstrap` command to start the bootstrap web server +defined in the `dfx.json` configuration file or specified using +command-line options. + +The bootstrap web server you specify is used to serve the front-end +static assets for your project. + +# Basic usage {#_basic_usage} + +``` bash +dfx bootstrap [option] +``` + +# Flags {#_flags} + +You can use the following optional flags with the `dfx bootstrap` +command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +# Options {#_options} + +You can specify the following options for the `dfx bootstrap` command. + ++------------------------+---------------------------------------------+ +| Option | Description | ++========================+=============================================+ +| `ip` \ | Specifies the IP address that the bootstrap | +| | server listens on. If you don't specify an | +| | IP address, the `address` setting you have | +| | configured in the `dfx.json` configuration | +| | file is used. By default, the server | +| | address is 127.0.0.1. | ++------------------------+---------------------------------------------+ +| \--network \ | Specifies the network to connect to if you | +| | want to override the default local network | +| | endpoint (`http://127.0.0.1:8080/api`). | ++------------------------+---------------------------------------------+ +| \--port \ | Specifies the port number that the | +| | bootstrap server listens on. By default, | +| | port number 8081 is used. | ++------------------------+---------------------------------------------+ +| \--root \ | Specifies the directory containing static | +| | assets served by the bootstrap server. By | +| | default, the path to static assets is: | +| | `$HOME/.cache/dfinity/versions/$D | +| | FX_VERSION/js-user-library/dist/bootstrap`. | ++------------------------+---------------------------------------------+ +| \--timeout \ | Specifies the maximum amount of time, in | +| | seconds, the bootstrap server will wait for | +| | upstream requests to complete. By default, | +| | the bootstrap server waits for a maximum of | +| | 30 seconds. | ++------------------------+---------------------------------------------+ + +# Examples {#_examples} + +You can use the `dfx bootstrap` command to start a web server for your +application using custom settings, including a specific server address, +port number, and static asset location. + +For example, to start the bootstrap server using a specific IP address +and port number, you would run a command similar to the following: + +``` bash +dfx bootstrap --ip 192.168.47.1 --port 5353 +``` + +The command displays output similar to the following: + +``` bash +binding to: V4(192.168.47.1:5353) +replica(s): \http://127.0.0.1:8080/api +Webserver started... +``` + +To use the default server address and port number but specify a custom +location for static assets and longer timeout period, you might run a +command similar to the following: + +``` bash +dfx bootstrap --root $HOME/ic-projects/assets --timeout 60 +``` + +You can use CTRL-C to stop the bootstrap server. diff --git a/modules/developers-guide/pages/cli-reference/dfx-build.text b/modules/developers-guide/pages/cli-reference/dfx-build.text new file mode 100644 index 000000000..ea820de63 --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-build.text @@ -0,0 +1,112 @@ +--- +date: 2021-08-05 +title: dfx build +--- + +Use the `dfx build` command to compile your program into a WebAssembly +module that can be deployed on the {IC}. You can use this command to +compile all of the programs that are defined for a project in the +project's `dfx.json` configuration file or a specific canister. + +Note that you can only run this command from within the project +directory structure. For example, if your project name is `hello_world`, +your current working directory must be the `hello_world` top-level +project directory or one of its subdirectories. + +The `dfx build` command looks for the source code to compile using the +information you have configured under the `canisters` section in the +`dfx.json` configuration file. + +# Basic usage {#_basic_usage} + +``` bash +dfx build [flag] [option] [--all | canister_name] +``` + +# Flags {#_flags} + +You can use the following optional flags with the `dfx build` command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `--check` | Builds canisters using a temporary, | +| | hard-coded, locally-defined canister | +| | identifier for testing that your program | +| | compiles without connecting to the {IC} | +| | network. | ++----------------------+-----------------------------------------------+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +# Options {#_options} + +You can specify the following option for the `dfx build` command. + ++------------------------+---------------------------------------------+ +| Option | Description | ++========================+=============================================+ +| `--network ` | Specifies the {IC} network you want to | +| | connect to. You can use this option to | +| | override the network specified in the | +| | `dfx.json` configuration file. | ++------------------------+---------------------------------------------+ + +# Arguments {#_arguments} + +You can specify the following arguments for the `dfx build` command. + ++------------------------+---------------------------------------------+ +| Argument | Description | ++========================+=============================================+ +| `--all` | Builds all of the canisters configured in | +| | the project's `dfx.json` file. | ++------------------------+---------------------------------------------+ +| `canister_name` | Specifies the name of the canister you want | +| | to build. If you are not using the `--all` | +| | option, you can continue to use `dfx build` | +| | or provide a canister name as an argument | +| | (the canister name must match at least one | +| | name that you have configured in the | +| | `canisters` section of the `dfx.json` | +| | configuration file for your project.) | ++------------------------+---------------------------------------------+ + +# Examples {#_examples} + +You can use the `dfx build` command to build one or more WebAssembly +modules from the programs specified in the `dfx.json` configuration file +under the `canisters` key. For example, if your `dfx.json` configuration +file defines one `hello_world` canister and one `hello_world_assets` +canister, then running `dfx build` compiles two WebAssembly modules: + +``` json +Unresolved directive in dfx-build.adoc - include::example$sample-dfx.json[] +``` + +Note that the file name and path to the programs on your file system +must match the information specified in the `dfx.json` configuration +file. + +In this example, the `hello_world` canister contains the main program +code and the `hello_world_assets` canister store front-end code and +assets. If you want to keep the `hello_world_assets` canister defined in +the `dfx.json` file, but only build the back-end program, you could run +the following command: + +``` bash +dfx build hello_world +``` + +Building a specific canister is useful when you have multiple canisters +defined in the dfx.json file, but want to test and debug operations for +canisters independently. + +To test whether a canister compiles without connecting to any {IC} +network, you would run the following command: + +``` bash +dfx build --check +``` diff --git a/modules/developers-guide/pages/cli-reference/dfx-cache.text b/modules/developers-guide/pages/cli-reference/dfx-cache.text new file mode 100644 index 000000000..6d3cd828b --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-cache.text @@ -0,0 +1,213 @@ +--- +date: 2021-08-05 +title: dfx cache +--- + +Use the `dfx cache` command with flags and subcommands to manage the +`dfx` version cache. + +The basic syntax for running `dfx cache` commands is: + +``` bash +dfx cache [subcommand] [flag] +``` + +Depending on the `dfx cache` subcommand you specify, additional +arguments, options, and flags might apply. For reference information and +examples that illustrate using `dfx cache` commands, select an +appropriate command. + ++----------------------+-----------------------------------------------+ +| Command | Description | ++======================+===============================================+ +| [`delete`](#delete) | Deletes the specified version of `dfx` from | +| | the local cache. | ++----------------------+-----------------------------------------------+ +| `help` | Displays usage information message for a | +| | specified subcommand. | ++----------------------+-----------------------------------------------+ +| [ | Installs the specified version of `dfx` from | +| `install`](#install) | the local cache. | ++----------------------+-----------------------------------------------+ +| [`list | Lists the versions of `dfx` currently | +| `](#_dfx_cache_list) | installed and used in current projects. | ++----------------------+-----------------------------------------------+ +| [`show | Show the path of the cache used by this | +| `](#_dfx_cache_show) | version of the `dfx` executable. | ++----------------------+-----------------------------------------------+ + +To view usage information for a specific subcommand, specify the +subcommand and the `--help` flag. For example, to see usage information +for `dfx cache delete`, you can run the following command: + +``` bash +dfx cache delete --help +``` + +# dfx cache delete {#delete} + +Use the `dfx cache delete` command to delete a specified version of +`dfx` from the version cache on the local computer. + +## Basic usage {#_basic_usage} + +``` bash +dfx cache delete [version] [flag] +``` + +## Flags {#_flags} + +You can use the following optional flags with the `dfx cache delete` +command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +## Arguments {#_arguments} + +You can specify the following argument for the `dfx cache delete` +command. + ++----------------------+-----------------------------------------------+ +| Command | Description | ++======================+===============================================+ +| `version` | Specifies the version of `dfx` you to delete | +| | from the local cache. | ++----------------------+-----------------------------------------------+ + +## Examples {#_examples} + +You can use the `dfx cache delete` command to permanently delete +versions of `dfx` that you no longer want to use. For example, you can +run the following command to delete `dfx` version `0.6.2`: + +``` bash +dfx cache delete 0.6.2 +``` + +# dfx cache install {#install} + +Use the `dfx cache install` command to install `dfx` using the version +currently found in the `dfx` cache. + +## Basic usage {#_basic_usage_2} + +``` bash +dfx cache install [flag] +``` + +## Flags {#_flags_2} + +You can use the following optional flags with the `dfx cache install` +command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +## Examples {#_examples_2} + +You can use the `dfx cache install` command to force the installation of +`dfx` from the version in the cache. For example, you can run the +following command to install `dfx`: + +\+ + +``` bash +dfx cache install +``` + +# dfx cache list {#_dfx_cache_list} + +Use the `dfx cache list` command to list the `dfx` versions you have +currently installed and used in projects. + +If you have multiple versions of `dfx` installed, the cache list +displays an asterisk (\*) to indicate the currently active version. + +## Basic usage {#_basic_usage_3} + +``` bash +dfx cache list [flag] +``` + +## Flags {#_flags_3} + +You can use the following optional flags with the `dfx cache list` +command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +## Examples {#_examples_3} + +You can use the `dfx cache list` command to list the `dfx` versions you +have currently installed and used in projects. For example, you can run +the following command to list versions of `dfx` found in the cache: + +``` bash +dfx cache list +``` + +This command displays the list of `dfx` versions found similar to the +following: + +``` bash +0.6.4 * +0.6.3 +0.6.0 +``` + +# dfx cache show {#_dfx_cache_show} + +Use the `dfx cache show` command to display the full path to the cache +used by the `dfx` version you are currently using. + +## Basic usage {#_basic_usage_4} + +``` bash +dfx cache show [flag] +``` + +## Flags {#_flags_4} + +You can use the following optional flags with the `dfx cache show` +command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +## Examples {#_examples_4} + +You can use the `dfx cache show` command to display the path to the +cache used by the `dfx` version you are currently using: + +``` bash +dfx cache show +``` + +This command displays the path to the cache used by the `dfx` version +you are currently using: + +``` bash +/Users/pubs/.cache/dfinity/versions/0.6.4 +``` diff --git a/modules/developers-guide/pages/cli-reference/dfx-canister.text b/modules/developers-guide/pages/cli-reference/dfx-canister.text new file mode 100644 index 000000000..62c0b87ff --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-canister.text @@ -0,0 +1,1249 @@ +--- +date: 2021-08-05 +title: dfx canister +--- + +Use the `dfx canister` command with flags and subcommands to manage +canister operations and interaction with the {platform}. In most cases, +you use `dfx canister` subcommands after you compile a program to manage +the canister lifecycle and to perform key tasks such as calling program +functions. + +The basic syntax for running `dfx canister` commands is: + +``` bash +dfx canister [subcommand] [flag] +``` + +Depending on the `dfx canister` subcommand you specify, additional +arguments, options, and flags might apply or be required. To view usage +information for a specific `dfx canister` subcommand, specify the +subcommand and the `--help` flag. For example, to see usage information +for `dfx canister call`, you can run the following command: + +``` bash +dfx canister call --help +``` + +For reference information and examples that illustrate using +`dfx canister` commands, select an appropriate command. + ++----------------------+-----------------------------------------------+ +| Command | Description | ++======================+===============================================+ +| [`call`]( | Calls a specified method on a deployed | +| #_dfx_canister_call) | canister. | ++----------------------+-----------------------------------------------+ +| [`create`](#_ | Creates a new \"empty\" canister by | +| dfx_canister_create) | registering a canister identifier on an {IC} | +| | network. | ++----------------------+-----------------------------------------------+ +| [`delete`](#_ | Deletes a currently stopped canister. | +| dfx_canister_delete) | | ++----------------------+-----------------------------------------------+ +| `help` | Displays usage information message for a | +| | specified subcommand. | ++----------------------+-----------------------------------------------+ +| [`id` | Displays the identifier for a canister. | +| ](#_dfx_canister_id) | | ++----------------------+-----------------------------------------------+ +| [`install`](#_d | Installs compiled code as a canister on the | +| fx_canister_install) | replica. | ++----------------------+-----------------------------------------------+ +| [`request | Requests the status of a call to a canister. | +| -status`](#_dfx_cani | | +| ster_request_status) | | ++----------------------+-----------------------------------------------+ +| [`set-con | Specifies the identity name or principal to | +| troller`](#_dfx_cani | use as the new controller for a specified | +| ster_set_controller) | canister on the Internet Computer network. | ++----------------------+-----------------------------------------------+ +| [`send`]( | Send a previously-signed `message.json` to a | +| #_dfx_canister_send) | specified canister identifier. For example, | +| | if you want to send a message that calls the | +| | network nervous system (NNS) governance | +| | canister to manage neurons, you might want to | +| | separate message signing from message | +| | delivery for security reasons. | ++----------------------+-----------------------------------------------+ +| [`sign`]( | Create a signed `message.json` file before | +| #_dfx_canister_send) | making a call to a specified canister | +| | identifier. For example, if you want to send | +| | a message that calls the network nervous | +| | system (NNS) governance canister to manage | +| | neurons, you might want to separate message | +| | signing from message delivery for security | +| | reasons. | ++----------------------+-----------------------------------------------+ +| [`start`](# | Restarts a stopped canister. | +| _dfx_canister_start) | | ++----------------------+-----------------------------------------------+ +| [`status`](#_ | Requests the running status of a canister. | +| dfx_canister_status) | | ++----------------------+-----------------------------------------------+ +| [`stop`]( | Stops a currently running canister. | +| #_dfx_canister_stop) | | ++----------------------+-----------------------------------------------+ + +# Overriding the default network {#_overriding_the_default_network} + +By default, `dfx canister` commands run on the local network specified +in the `dfx.json` file. If you want to send a `dfx canister` subcommand +to a specific network provider address and port number without changing +the settings in your `dfx.json` configuration file, you can explicitly +specify the URL for the network using the `--network` option. + +For example, to register unique canister identifiers for a project when +the {IC} runs on your local computer, you can run the following command: + +``` bash +dfx canister create --all +``` + +If you want to register unique canister identifiers for the same project +when the {IC} runs on the network that uses the `ic` alias in the +`dfx.json` file, you can run the following command: + +``` bash +dfx canister --network ic create --all +``` + +Similarly, you can call a canister and function running on a remote {IC} +network using a command similar to the following: + +``` bash +dfx canister --network \http://192.168.3.1:5678 call counter get +``` + +Note that you must specify the `--network` parameter before the canister +operation (`create` or `call`) and any additional arguments such as the +canister name (`counter`), and function (`get`). + +# dfx canister call {#_dfx_canister_call} + +Use the `dfx canister call` command to call a specified method on a +deployed canister. + +## Basic usage {#_basic_usage} + +``` bash +dfx canister call [option] canister_name method_name [argument] [flag] +``` + +## Flags {#_flags} + +You can use the following optional flags with the `dfx canister call` +command. + ++---------------------+------------------------------------------------+ +| Flag | Description | ++=====================+================================================+ +| `--async` | Enables you to continue without waiting for | +| | the result of the call to be returned by | +| | polling the replica. | ++---------------------+------------------------------------------------+ +| `-h`, `--help` | Displays usage information. | ++---------------------+------------------------------------------------+ +| `--query` | Enables you to send a query request to a | +| | deployed canister. For best performance and | +| | network efficiency, you should use this flag | +| | when you explicitly want to use the query | +| | method to retrieve information. For | +| | information about the difference between query | +| | and update calls, see [Canisters include both | +| | program and | +| | state](. | +| | ./concepts/canisters-code.xml#canister-state). | ++---------------------+------------------------------------------------+ +| `--update` | Enables you to send an update request to a | +| | deployed canister. By default, canister calls | +| | use the update method. | ++---------------------+------------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++---------------------+------------------------------------------------+ + +## Options {#_options} + +You can use the following options with the `dfx canister call` command. + ++---------------------+------------------------------------------------+ +| Option | Description | ++=====================+================================================+ +| `--output ` | Specifies the output format to use when | +| | displaying a method's return result. The valid | +| | values are `idl` and `raw`. | ++---------------------+------------------------------------------------+ +| `--type ` | Specifies the data format for the argument | +| | when making the call using an argument. The | +| | valid values are `idl` and `raw`. | ++---------------------+------------------------------------------------+ + +## Arguments {#_arguments} + +You can specify the following arguments for the `dfx canister call` +command. + ++---------------------+------------------------------------------------+ +| Argument | Description | ++=====================+================================================+ +| `canister_name` | Specifies the name of the canister to call. | +| | The canister name is a required argument and | +| | should match the name you have configured for | +| | a project in the `canisters` section of the | +| | `dfx.json` configuration file. | ++---------------------+------------------------------------------------+ +| `method_name` | Specifies the method name to call on the | +| | canister. The canister method is a required | +| | argument. | ++---------------------+------------------------------------------------+ +| `argument` | Specifies the argument to pass to the method. | +| | Depending on your program logic, the argument | +| | can be a required or optional argument. You | +| | can specify a data format type using the | +| | `--type` option if you pass an argument to the | +| | canister. By default, you can specify | +| | arguments using the | +| | [Candid](../../candid-guide/candid-intro.xml) | +| | (`idl`) syntax for data values. For | +| | information about using Candid and its | +| | supported types, see [Interact with a service | +| | in a | +| | terminal](. | +| | ./../candid-guide/candid-howto.xml#idl-syntax) | +| | and [Supported | +| | types](../../candid-guide/candid-types.xml). | +| | You can use `raw` as the argument type if you | +| | want to pass raw bytes to a canister. | ++---------------------+------------------------------------------------+ + +## Examples {#_examples} + +You can use the `dfx canister call` command to invoke specific +methods---with or without arguments---after you have deployed the +canister on the network using the `dfx canister install` command. For +example, to invoke the `get` method for a canister with a +`canister_name` of `counter`, you can run the following command: + +``` bash +dfx canister call counter get --async +``` + +In this example, the command includes the `--async` option to indicate +that you want to make a separate `request-status` call rather than +waiting to poll the replica for the result. The `--async` option is +useful when processing an operation might take some time to complete. +The option enables you to continue performing other operations then +check for the result using a separate `dfx canister request-status` +command. The returned result will be displayed as the IDL textual +format. + +### Using the IDL syntax {#_using_the_idl_syntax} + +You can explicitly specify that you are passing arguments using the IDL +syntax by running commands similar to the following for a Text data +type: + +``` bash +dfx canister call hello greet --type idl '("Lisa")' +("Hello, Lisa!") + +dfx canister call hello greet '("Lisa")' --type idl +("Hello, Lisa!") +``` + +You can also implicitly use the IDL by running a command similar to the +following: + +``` bash +dfx canister call hello greet '("Lisa")' +("Hello, Lisa!") +``` + +To specify multiple arguments using the IDL syntax, use commas between +the arguments. For example: + +``` bash +dfx canister call contacts insert '("Amy Lu","01 916-335-2042")' + +dfx canister call hotel guestroom '("Deluxe Suite",42,true)' +``` + +You can pass raw data in bytes by running a command similar to the +following: + +``` bash +dfx canister call hello greet --type raw '4449444c00017103e29883' +``` + +This example uses the raw data type to pass a hexadecimal to the `greet` +function of the `hello` canister. + +# dfx canister create {#_dfx_canister_create} + +Use the `dfx canister create` command to register one or more canister +identifiers without compiled code on the {IC} network. You must be +connected to an {IC} network running locally or on a sub-network that +you can access to run this command. + +Note that you can only run this command from within the project +directory structure. For example, if your project name is `hello_world`, +your current working directory must be the `hello_world` top-level +project directory or one of its subdirectories. + +The first time you run the `dfx canister create` command to register an +identifier, your public/private key pair credentials are used to create +a `default` user identity. The credentials for the `default` user are +migrated from `$HOME/.dfinity/identity/creds.pem` to +`$HOME/.config/dfx/identity/default/identity.pem`. + +## Basic usage {#_basic_usage_2} + +``` bash +dfx canister create [option] [flag] [--all | canister_name] +``` + +## Flags {#_flags_2} + +You can use the following optional flags with the `dfx canister create` +command. + ++---------------------+------------------------------------------------+ +| Flag | Description | ++=====================+================================================+ +| `-h`, `--help` | Displays usage information. | ++---------------------+------------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++---------------------+------------------------------------------------+ + +## Options {#_options_2} + +You can use the following options with the `dfx canister create` +command. + ++---------------------+------------------------------------------------+ +| Option | Description | ++=====================+================================================+ +| `--with-cycles | Enables you to specify the initial number of | +| ` | cycles in a canister when it is created by | +| | your wallet. | ++---------------------+------------------------------------------------+ + +## Arguments {#_arguments_2} + +You can use the following argument with the `dfx canister create` +command. + ++---------------------+------------------------------------------------+ +| Argument | Description | ++=====================+================================================+ +| `--all` | Enables you to create multiple canister | +| | identifiers at once if you have a project | +| | `dfx.json` file that defines multiple | +| | canisters. Note that you must specify `--all` | +| | or an individual canister name. | ++---------------------+------------------------------------------------+ +| `canister_name` | Specifies the name of the canister for which | +| | you want to register an identifier. If you are | +| | not using the `--all` option, the canister | +| | name is a required argument and must match at | +| | least one name that you have configured in the | +| | `canisters` section of the `dfx.json` | +| | configuration file for your project. | ++---------------------+------------------------------------------------+ + +## Examples {#_examples_2} + +You can use the `dfx canister create` command to register canister +identifiers without first compiling any code. For example, if you want +to create the canister identifier for the project `my_counter` before +writing the program, you can run the following command: + +``` bash +dfx canister create my_counter +``` + +You can use the `dfx canister create` command with the `--with-cycles` +option to specify the initial balance upon the creation of one canister +or all canisters in a project. For example, to specify an initial +balance of 8000000000000 cycles for all canisters, run the following +command: + +``` bash +dfx canister create --with-cycles 8000000000000 --all +``` + +# dfx canister delete {#_dfx_canister_delete} + +Use the `dfx canister delete` command to delete a stopped canister from +the local Internet Computer network or on a remote Internet Computer +network. + +Note that you can only run this command from within the project +directory structure. For example, if your project name is `hello_world`, +your current working directory must be the `hello_world` top-level +project directory or one of its subdirectories. + +## Basic usage {#_basic_usage_3} + +``` bash +dfx canister delete [flag] [--all | canister_name] +``` + +## Flags {#_flags_3} + +You can use the following optional flags with the `dfx canister delete` +command. + ++---------------------+------------------------------------------------+ +| Flag | Description | ++=====================+================================================+ +| `-h`, `--help` | Displays usage information. | ++---------------------+------------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++---------------------+------------------------------------------------+ + +## Arguments {#_arguments_3} + +You can use the following arguments with the `dfx canister delete` +command. + ++---------------------+------------------------------------------------+ +| Argument | Description | ++=====================+================================================+ +| `--all` | Deletes all of the canisters configured in the | +| | `dfx.json` file. Note that you must specify | +| | `--all` or an individual canister name. | ++---------------------+------------------------------------------------+ +| `canister_name` | Specifies the name of the canister you want to | +| | delete. Note that you must specify either a | +| | canister name or the `--all` option. | ++---------------------+------------------------------------------------+ + +## Examples {#_examples_3} + +You can use the `dfx canister delete` command to delete a specific +canister or all canisters. + +To delete the `hello_world` canister, you can run the following command: + +``` bash +dfx canister delete hello_world +``` + +To delete all of the canisters you have deployed on the `ic` Internet +Computer network, you can run the following command: + +``` bash +dfx canister --network=ic delete --all +``` + +# dfx canister id {#_dfx_canister_id} + +Use the `dfx canister id` command to output the canister identifier for +a specific canister name. + +Note that you can only run this command from within the project +directory structure. For example, if your project name is `hello_world`, +your current working directory must be the `hello_world` top-level +project directory or one of its subdirectories. + +## Basic usage {#_basic_usage_4} + +``` bash +dfx canister id [flag] canister_name +``` + +## Flags {#_flags_4} + +You can use the following optional flags with the `dfx canister id` +command. + ++---------------------+------------------------------------------------+ +| Flag | Description | ++=====================+================================================+ +| `-h`, `--help` | Displays usage information. | ++---------------------+------------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++---------------------+------------------------------------------------+ + +## Arguments {#_arguments_4} + +You can use the following argument with the `dfx canister id` command. + ++---------------------+------------------------------------------------+ +| Argument | Description | ++=====================+================================================+ +| `canister_name` | Specifies the name of the canister for which | +| | you want to display an identifier. | ++---------------------+------------------------------------------------+ + +## Examples {#_examples_4} + +You can use the `dfx canister id` command to display the canister +identifier for a specific canister name. + +To display the canister identifier for the `hello_world` canister, you +can run the following command: + +``` bash +dfx canister id hello_world +``` + +The command displays output similar to the following: + +``` bash +75hes-oqbaa-aaaaa-aaaaa-aaaaa-aaaaa-aaaaa-q +``` + +# dfx canister install {#_dfx_canister_install} + +Use the `dfx canister install` command to install compiled code as a +canister on the {IC} network running locally or on a sub-network that +you can access. + +## Basic usage {#_basic_usage_5} + +``` bash +dfx canister install [flag] [option] [--all | canister_name] +``` + +## Flags {#_flags_5} + +You can use the following optional flags with the `dfx canister install` +command. + ++---------------------+------------------------------------------------+ +| Flag | Description | ++=====================+================================================+ +| `--async` | Enables you to continue without waiting for | +| | the result of the installation to be returned | +| | by polling the replica. | ++---------------------+------------------------------------------------+ +| `-h`, `--help` | Displays usage information. | ++---------------------+------------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++---------------------+------------------------------------------------+ + +## Options {#_options_3} + +You can use the following options with the `dfx canister install` +command. + ++---------------------+------------------------------------------------+ +| Option | Description | ++=====================+================================================+ +| `--a | Specifies an argument to pass to the canister | +| rgument ` | during installation. | ++---------------------+------------------------------------------------+ +| `--argument-ty | Specifies the data format for the argument | +| pe ` | when you install using the `--argument` | +| | option. The valid values are `idl` and `raw`. | +| | By default, you can specify arguments using | +| | the | +| | [Candid](../../candid-guide/candid-intro.xml) | +| | (`idl`) syntax for data values. For | +| | information about using Candid and its | +| | supported types, see [Interact with a service | +| | in a | +| | terminal](. | +| | ./../candid-guide/candid-howto.xml#idl-syntax) | +| | and [Supported | +| | types](../../candid-guide/candid-types.xml). | +| | You can use `raw` as the argument type if you | +| | want to pass raw bytes to a canister. | ++---------------------+------------------------------------------------+ +| `-c`, | Defines a compute allocation---essentially the | +| `--co | equivalent of setting a CPU allocation---for | +| mpute-allocation ` | a percentage in the range of 0 to 100. | ++---------------------+------------------------------------------------+ +| `-- | Specifies how much memory the canister is | +| memory-allocation < | allowed to use in total. You can set this | +| memory-allocation>` | value in the range of 0 to 8MB. | ++---------------------+------------------------------------------------+ +| `-m`, | Specifies whether you want to `install`, | +| `--mode ` | `reinstall`, or `upgrade` canisters. For more | +| | information about installation modes and | +| | canister management, see [Managing | +| | canisters](../working-with-canisters.xml). | ++---------------------+------------------------------------------------+ + +## Arguments {#_arguments_5} + +You can use the following arguments with the `dfx canister install` +command. + ++---------------------+------------------------------------------------+ +| Argument | Description | ++=====================+================================================+ +| `--all` | Enables you to install multiple canisters at | +| | once if you have a project `dfx.json` file | +| | that includes multiple canisters. Note that | +| | you must specify `--all` or an individual | +| | canister name. | ++---------------------+------------------------------------------------+ +| `canister_name` | Specifies the name of the canister to deploy. | +| | If you are not using the `--all` option, the | +| | canister name is a required argument and | +| | should match the name you have configured for | +| | a project in the `canisters` section of the | +| | `dfx.json` configuration file. | ++---------------------+------------------------------------------------+ + +## Examples {#_examples_5} + +You can use the `dfx canister install` command to deploy WebAssembly you +have compiled using the `dfx build` command as a canister on the +network. The most common use case is to install all of the canisters by +running the following command: + +``` bash +dfx canister install --all +``` + +### Installing a specific canister {#_installing_a_specific_canister} + +You can also use the `dfx canister install` command to deploy a specific +canister instead of all of the canisters in your project. For example, +if you have a project with a `hello_world` canister and a +`hello_world_assets` canister but only want to deploy the `hello_world` +canister, you can deploy just that the canister by running the following +command: + +``` bash +dfx canister install hello_world +``` + +### Sending an asynchronous request {#_sending_an_asynchronous_request} + +If you want to submit a request to install the canister and return a +request identifier to check on the status of your request later instead +of waiting for the command to complete, you can run a command similar to +the following: + +``` bash +dfx canister install hello_world --async +``` + +This command submits a request to install the canister and returns a +request identifier similar to the following: + +``` bash +0x58d08e785445dcab4ff090463b9e8b12565a67bf436251d13e308b32b5058608 +``` + +You can then use the request identifier to check the status of the +request at a later time, much like a tracking number if you were +shipping a package. + +### Overriding the default network provider {#_overriding_the_default_network_provider} + +If you want to deploy a canister on a specific {IC} network without +changing the settings in your `dfx.json` configuration file, you can +explicitly specify the network you want to connect to by using the +`+--network` option. + +For example, you can specify a remote network URL by running a command +similar to the following: + +``` bash +dfx canister --network \http://192.168.3.1:5678 install --all +``` + +Note that you must specify the network parameter before the canister +operation (`install`) and before the canister name or `--all` flag. + +### Allocating message processing {#_allocating_message_processing} + +The `--compute-allocation` options allows you to allocate computing +resources as a percentage in the range of 0 to 100 to indicate how often +your canister should be scheduled for execution. + +For example, assume you run the following command: + +``` bash +dfx canister install --all --compute-allocation 50 +``` + +With this setting, all of the canisters in the current projects are +assigned a 50% allocation. When canisters in the project receive input +messages to process, the messages are scheduled for execution. Over 100 +execution cycles, each canister's messages will be scheduled for +processing at least 50 times. + +The default value for this option is 0---indicating that no specific +allocation or scheduling is in effect. If all of your canisters use the +default setting, processing occurs in a round-robin fashion. + +# dfx canister request-status {#_dfx_canister_request_status} + +Use the `dfx canister request-status` command to request the status of a +specified call to a canister. This command requires you to specify the +request identifier you received after invoking a method on the canister. +The request identifier is an hexadecimal string starting with `0x`. + +## Basic usage {#_basic_usage_6} + +``` bash +dfx canister request-status request_id +``` + +## Flags {#_flags_6} + +You can use the following optional flags with the +`dfx canister request-status` command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +## Arguments {#_arguments_6} + +You can specify the following argument for the +`dfx canister request-status` command. + ++----------------------+-----------------------------------------------+ +| Argument | Description | ++======================+===============================================+ +| `request_id` | Specifies the hexadecimal string returned in | +| | response to a `dfx canister call` or | +| | `dfx canister install` command. This | +| | identifier is an hexadecimal string starting | +| | with 0x. | ++----------------------+-----------------------------------------------+ + +## Examples {#_examples_6} + +You can use the `dfx canister request-status` command to check on the +status of a canister state change or to verify that a call was not +rejected by running a command similar to the following: + +``` bash +dfx canister request-status 0x58d08e785445dcab4ff090463b9e8b12565a67bf436251d13e308b32b5058608 +``` + +This command displays an error message if the request identifier is +invalid or refused by the canister. + +# dfx canister set-controller {#_dfx_canister_set_controller} + +Use the `dfx canister set-controller` command to specify the identity +name or principal to use as the new **controller** for a specified +canister on the Internet Computer network. A controller identity has +special rights to manage the canister it controls. For example, only a +controlling identity can be used to install, upgrade, or delete the +canister under its control. + +Note that you can specify either a user identity or a canister as a +controller. You can also specify the controller identity by using its +name or its principal. + +## Basic usage {#_basic_usage_7} + +``` bash +dfx canister set-controller [flag] canister new-controller +``` + +## Flags {#_flags_7} + +You can use the following optional flags with the +`dfx canister set-controller` command. + ++---------------------+------------------------------------------------+ +| Flag | Description | ++=====================+================================================+ +| `-h`, `--help` | Displays usage information. | ++---------------------+------------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++---------------------+------------------------------------------------+ + +## Arguments {#_arguments_7} + +You must use the following arguments with the +`dfx canister set-controller` command. + ++---------------------+------------------------------------------------+ +| Argument | Description | ++=====================+================================================+ +| `` | Specifies the canister name or canister | +| | identifier to be controlled by the identity | +| | you specify using the *new_controller* | +| | argument. | ++---------------------+------------------------------------------------+ +| `` | Specifies the identity name or principal of | +| | the controller. | ++---------------------+------------------------------------------------+ + +## Examples {#_examples_7} + +You can use the `dfx canister set-controller` command to specify a user +or canister as the controlling identity for a specific canister. + +For example, you might create a new identity called `pubsadmin` then run +the `dfx canister set-controller` to specify that you want the +`pubsadmin` identity to be the controller of the `hello_world` canister +by running the following commands: + + dfx identity new pubsadmin + dfx canister set-controller hello_world pubsadmin + +To set the controlling identity using the textual representation of the +identity principal, you might run a command similar to the following: + + dfx canister set-controller hello_world wcp5u-pietp-k5jz4-sdaaz-g3x4l-zjzxa-lxnly-fp2mk-j3j77-25qat-pqe + +Although specifying a user identity name or principal is one potential +use case, a more common scenario is to specify the wallet canister that +you want to use to send cycles to the canister. The following steps +illustrate this scenario when you are doing local development. For this +example, assume you have created a project called `open_sf` with two +canisters deployed on the {IC} running locally. + +1. Create an identity---for example, `sf-controller`---to act as the + controller. + + dfx identity new sf-controller + + Creating identity: "sf-controller". + Created identity: "sf-controller". + +2. Make the new identity the active identity. + + dfx identity use sf-controller + + Using identity: "sf-controller". + +3. Generate a wallet canister identifier for the new identity. + + dfx identity get-wallet + + Creating a wallet canister on the local network. + r7inp-6aaaa-aaaaa-aaabq-cai + The wallet canister on the "local" network for user "sf-controller" is "r7inp-6aaaa-aaaaa-aaabq-cai" + +4. Switch the active identity to the current controller of the + canister. For example, if the default identity was used to create + the canister, you would run the following command: + + dfx identity use default + + Using identity: "default". + +5. Set the controller for a specified canister to use the wallet + associated wit the sf-controller identity. + + dfx canister set-controller open_sf_assets r7inp-6aaaa-aaaaa-aaabq-cai + + Set "r7inp-6aaaa-aaaaa-aaabq-cai" as controller of "open_sf_assets". + + You can now use the wallet canister `r7inp-6aaaa-aaaaa-aaabq-cai` to + send cycles or add custodians to the `open_sf_assets` canister. + +# dfx canister send {#_dfx_canister_send} + +Use the `dfx canister send` command after signing a message with the +`dfx canister sign` command when you want to separate these steps, +rather than using the single `dfx canister call` command. Using separate +calls can add security to the transaction. + +For example, when creating your neuron stake, you might want to use the +`dfx canister sign` command to create a signed `message.json` file using +an air-gapped computer, then use the `dfx canister send` command to +deliver the signed message. + +## Basic usage {#_basic_usage_8} + +``` bash +dfx canister send file_name +``` + +## Flags {#_flags_8} + +You can use the following optional flags with the +`dfx canister request-status` command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +## Arguments {#_arguments_8} + +You can specify the following argument for the `dfx canister send` +command. + ++----------------------+-----------------------------------------------+ +| Argument | Description | ++======================+===============================================+ +| `file_name` | Specifies the file name of the message. | ++----------------------+-----------------------------------------------+ + +## Examples {#_examples_8} + +Use the `dfx canister send` command to send a signed message created +using the `dfx canister sign` command to the genesis token canister +(GTC) to create a neuron on your behalf by running the following +command: + +`dfx canister send message.json` + +# dfx canister sign {#_dfx_canister_sign} + +Use the `dfx canister sign` command before sending a message with the +`dfx canister send` command when you want to separate these steps, +rather than using the single `dfx canister call` command. Using separate +calls can add security to the transaction. For example, when creating +your neuron stake, you might want to use the `dfx canister sign` command +to create a signed `message.json` file using an air-gapped computer, +then use the `dfx canister send` command to deliver the signed message +from a computer connected to the network. + +## Basic usage {#_basic_usage_9} + +``` bash +dfx canister sign [flag] [option] canister-name method-name [argument] +``` + +## Flags {#_flags_9} + +You can use the following optional flags with the `dfx canister sign` +command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `--query` | Sends a query request to a canister. | ++----------------------+-----------------------------------------------+ +| `--update` | Sends an update request to the canister. This | +| | is the default method if the `--query` method | +| | is not used. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +## Options {#_options_4} + +You can specify the following options for the `dfx canister sign` +command. + ++----------------------+-----------------------------------------------+ +| Option | Description | ++======================+===============================================+ +| `--expire-a | Specifies how long will will be valid before | +| fter ` | it expires and cannot be sent. Specify in | +| | seconds. If not defined, the default is 300s | +| | (5m) | ++----------------------+-----------------------------------------------+ +| `--file ` | Specifies the output file name. The default | +| | is `message.json`. | ++----------------------+-----------------------------------------------+ +| `--random ` | Specifies the configuration for generating | +| | random arguments. | ++----------------------+-----------------------------------------------+ +| `--type ` | Specifies the data type for the argument when | +| | making a call using an argument. | +| | | +| | By default, you can specify arguments using | +| | the | +| | [Candid](../../candid-guide/candid-intro.xml) | +| | (`idl`) syntax for data values. For | +| | information about using Candid and its | +| | supported types, see [Interact with a service | +| | in a | +| | terminal](.. | +| | /../candid-guide/candid-howto.xml#idl-syntax) | +| | and [Supported | +| | types](../../candid-guide/candid-types.xml). | +| | You can use `raw` as the argument type if you | +| | want to pass raw bytes. | ++----------------------+-----------------------------------------------+ + +## Arguments {#_arguments_9} + +You can specify the following arguments for the `dfx canister sign` +command. + ++----------------------+-----------------------------------------------+ +| Argument | Description | ++======================+===============================================+ +| `canister_name` | Specifies the name of the canister to call. | +| | The canister name is a required argument and | +| | should match the name you have configured for | +| | a project in the `canisters` section of the | +| | `dfx.json` configuration file. | ++----------------------+-----------------------------------------------+ +| `method_name` | Specifies the method name to call on the | +| | canister. The canister method is a required | +| | argument. | ++----------------------+-----------------------------------------------+ +| `argument` | Specifies the argument to pass to the method. | +| | Depending on your program logic, the argument | +| | can be a required or optional argument. You | +| | can specify a data format type using the | +| | `--type` option if you pass an argument to | +| | the canister. By default, you can specify | +| | arguments using the | +| | [Candid](../../candid-guide/candid-intro.xml) | +| | (`idl`) syntax for data values. For | +| | information about using Candid and its | +| | supported types, see [Interact with a service | +| | in a | +| | terminal](.. | +| | /../candid-guide/candid-howto.xml#idl-syntax) | +| | and [Supported | +| | types](../../candid-guide/candid-types.xml). | +| | You can use `raw` as the argument type if you | +| | want to pass raw bytes. | ++----------------------+-----------------------------------------------+ + +## Examples {#_examples_9} + +Use the `dfx canister sign` command to create a signed `message.json` +file using the principal associated with the identity you created using +the Privacy Enhanced Mail (PEM) file by running a command similar to the +following: + +`dfx canister --no-wallet --network=ic sign --expire-after=1h rno2w-sqaaa-aaaaa-aaacq-cai create_neurons ‘(“PUBLIC_KEY”)’` + +Currently, the `--no-wallet` command must be used to execute the command +using the user identity instead of the cycles wallet canister +identifier. + +This command illustrates how to creates a `message.json` file to create +neurons on the network stpecified by the `ic` alias, that is signed +using your principal identifier as the message sender and with an +expiration window that ends in one hour. + +Note that the time allotted to send a signed message is a fixed 5-minute +window. The `--expire-after` option enables you to specify the point in +time when the 5-minute window for sending the signed message should end. +For example, if you set the `--expire-after` option to one hour (`1h`), +you must wait at least 55 minutes before you send the generated message +and the signature for the message is only valid during the 5-minute +window ending in the 60th minute. + +In this example, therefore, you would need to send the message after 55 +minutes and before 60 minutes for the message to be recognized as valid. + +If you don't specify the `--expire-after` option, the default expiration +is five minutes. + +Send the signed message to the genesis token canister (GTC) to create a +neuron on your behalf by running the following command: + +`dfx canister send message.json` + +# dfx canister start {#_dfx_canister_start} + +Use the `dfx canister start` command to restart a stopped canister on +the local Internet Computer network or on a remote Internet Computer +network. + +In most cases, you run this command after you have stopped a canister to +properly terminate any pending requests as a prerequisite to upgrading +the canister. + +Note that you can only run this command from within the project +directory structure. For example, if your project name is `hello_world`, +your current working directory must be the `hello_world` top-level +project directory or one of its subdirectories. + +## Basic usage {#_basic_usage_10} + +``` bash +dfx canister start [flag] [--all | canister_name] +``` + +## Flags {#_flags_10} + +You can use the following optional flags with the `dfx canister start` +command. + ++---------------------+------------------------------------------------+ +| Flag | Description | ++=====================+================================================+ +| `-h`, `--help` | Displays usage information. | ++---------------------+------------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++---------------------+------------------------------------------------+ + +## Arguments {#_arguments_10} + +You can use the following arguments with the `dfx canister start` +command. + ++---------------------+------------------------------------------------+ +| Argument | Description | ++=====================+================================================+ +| `--all` | Starts all of the canisters configured in the | +| | `dfx.json` file. Note that you must specify | +| | `--all` or an individual canister name. | ++---------------------+------------------------------------------------+ +| `canister_name` | Specifies the name of the canister you want to | +| | start. Note that you must specify either a | +| | canister name or the `--all` option. | ++---------------------+------------------------------------------------+ + +## Examples {#_examples_10} + +You can use the `dfx canister start` command to start a specific +canister or all canisters. + +To start the `hello_world` canister, you can run the following command: + +``` bash +dfx canister start hello_world +``` + +To start all of the canisters you have deployed on the `ic` Internet +Computer network, you can run the following command: + +``` bash +dfx canister --network=ic start --all +``` + +# dfx canister status {#_dfx_canister_status} + +Use the `dfx canister status` command to check whether a canister is +currently running, in the process of stopping, or currently stopped on +the local Internet Computer network or on a remote Internet Computer +network. + +Note that you can only run this command from within the project +directory structure. For example, if your project name is `hello_world`, +your current working directory must be the `hello_world` top-level +project directory or one of its subdirectories. + +## Basic usage {#_basic_usage_11} + +``` bash +dfx canister status [flag] [--all | canister_name] +``` + +## Flags {#_flags_11} + +You can use the following optional flags with the `dfx canister status` +command. + ++---------------------+------------------------------------------------+ +| Flag | Description | ++=====================+================================================+ +| `-h`, `--help` | Displays usage information. | ++---------------------+------------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++---------------------+------------------------------------------------+ + +## Arguments {#_arguments_11} + +You can use the following arguments with the `dfx canister status` +command. + ++---------------------+------------------------------------------------+ +| Argument | Description | ++=====================+================================================+ +| `--all` | Returns status information for all of the | +| | canisters configured in the `dfx.json` file. | +| | Note that you must specify `--all` or an | +| | individual canister name. | ++---------------------+------------------------------------------------+ +| `canister_name` | Specifies the name of the canister you want to | +| | return information for. Note that you must | +| | specify either a canister name or the `--all` | +| | option. | ++---------------------+------------------------------------------------+ + +## Examples {#_examples_11} + +You can use the `dfx canister status` command to check the status of a +specific canister or all canisters. + +To check the status of the `hello_world` canister, you can run the +following command: + +``` bash +dfx canister status hello_world +``` + +To check the status for all of the canisters you have deployed on the +`ic` Internet Computer network, you can run the following command: + +``` bash +dfx canister --network=ic status --all +``` + +# dfx canister stop {#_dfx_canister_stop} + +Use the `dfx canister stop` command to stop a canister that is currently +running on the local Internet Computer network or on a remote Internet +Computer network. + +In most cases, you run this command to properly terminate any pending +requests as a prerequisite to upgrading the canister. + +Note that you can only run this command from within the project +directory structure. For example, if your project name is `hello_world`, +your current working directory must be the `hello_world` top-level +project directory or one of its subdirectories. + +## Basic usage {#_basic_usage_12} + +``` bash +dfx canister stop [flag] [--all | canister_name] +``` + +## Flags {#_flags_12} + +You can use the following optional flags with the `dfx canister stop` +command. + ++---------------------+------------------------------------------------+ +| Flag | Description | ++=====================+================================================+ +| `-h`, `--help` | Displays usage information. | ++---------------------+------------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++---------------------+------------------------------------------------+ + +## Arguments {#_arguments_12} + +You can use the following arguments with the `dfx canister stop` +command. + ++---------------------+------------------------------------------------+ +| Argument | Description | ++=====================+================================================+ +| `--all` | Stops all of the canisters configured in the | +| | `dfx.json` file. Note that you must specify | +| | `--all` or an individual canister name. | ++---------------------+------------------------------------------------+ +| `canister_name` | Specifies the name of the canister you want to | +| | stop. Note that you must specify either a | +| | canister name or the `--all` option. | ++---------------------+------------------------------------------------+ + +## Examples {#_examples_12} + +You can use the `dfx canister stop` command to start a specific canister +or all canisters. + +To stop the `hello_world` canister, you can run the following command: + +``` bash +dfx canister stop hello_world +``` + +To stop all of the canisters you have deployed on the `ic` Internet +Computer network, you can run the following command: + +``` bash +dfx canister --network=ic stop --all +``` diff --git a/modules/developers-guide/pages/cli-reference/dfx-config.text b/modules/developers-guide/pages/cli-reference/dfx-config.text new file mode 100644 index 000000000..3ee80f675 --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-config.text @@ -0,0 +1,103 @@ +--- +date: 2021-08-05 +title: dfx config +--- + +Use the `dfx config` command to view or configure settings in the +configuration file for a current project. Note that you can only run +this command from within the project directory structure. For example, +if your project name is `hello_world`, your current working directory +must be the `hello_world` top-level project directory or one of its +subdirectories. + +# Basic usage {#_basic_usage} + +``` bash +dfx config [config_path] [value] [flag] +``` + +# Flags {#_flags} + +You can use the following optional flags with the `dfx config` command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +# Options {#_options} + +You can use the following option with the `dfx config` command. + ++----------------------+-----------------------------------------------+ +| Option | Description | ++======================+===============================================+ +| `--format` | Specifies the format of the configuration | +| | file output. By default, the file is | +| | displayed using JSON format. The valid values | +| | are `json` and `text`. | ++----------------------+-----------------------------------------------+ + +# Arguments {#_arguments} + +You can specify the following arguments for the `dfx config` command. + ++-----------------------+----------------------------------------------+ +| Argument | Description | ++=======================+==============================================+ +| `config_path` | Specifies the name of the configuration | +| | option that you want to set or read. You | +| | must specify the configuration file option | +| | using its period-delineated path to set or | +| | read the specific option you want to change | +| | or view. If you don't specify the path to a | +| | specific configuration option, the command | +| | displays the full configuration file. | ++-----------------------+----------------------------------------------+ +| `value` | Specifies the new value for the option you | +| | are changing. If you don't specify a value, | +| | the command returns the current value for | +| | the option from the configuration file. | ++-----------------------+----------------------------------------------+ + +# Examples {#_examples} + +You can use the `dfx config` command to change configuration settings +such as the location of the default output directory or the name of your +main program file. + +For example, to change the default build output directory from +`canisters` to `staging`, you can run the following command: + +``` bash +dfx config defaults.build.output "staging/" +``` + +To view the current value for a configuration setting, you can specify +the path to the setting in the configuration file without specifying a +value. For example: + +``` bash +dfx config defaults.build.output +``` + +The command returns the current value for the configuration option: + +``` bash +"staging/" +``` + +Similarly, you can change the name of the main source file or the port +number for the local network replica by running commands similar to the +following: + +``` bash +dfx config canisters.hello.main "src/hello_world/hello-main.mo" +dfx config networks.local.bind 127.0.0.1:5050 +``` + +You can also verify your configuration changes by viewing the `dfx.json` +configuration file after running the `dfx config` command. diff --git a/modules/developers-guide/pages/cli-reference/dfx-deploy.text b/modules/developers-guide/pages/cli-reference/dfx-deploy.text new file mode 100644 index 000000000..6158fd441 --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-deploy.text @@ -0,0 +1,116 @@ +--- +date: 2021-08-05 +title: dfx deploy +--- + +Use the `dfx deploy` command to register, build, and deploy an +application locally or on a specified network. By default, all canisters +defined in the project `dfx.json` configuration file are deployed. + +This command simplifies the developer workflow by enabling you to run +one command instead of running the following commands as separate steps: + + dfx canister create --all + dfx build + dfx canister install --all + +Note that you can only run this command from within the project +directory structure. For example, if your project name is `hello_world`, +your current working directory must be the `hello_world` top-level +project directory or one of its subdirectories. + +# Basic usage {#_basic_usage} + +``` bash +dfx deploy [flag] [option] [canister_name] +``` + +# Flags {#_flags} + +You can use the following optional flags with the `dfx deploy` command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +# Options {#_options} + +You can use the following options with the `dfx deploy` command. + ++----------------------+-----------------------------------------------+ +| Option | Description | ++======================+===============================================+ +| ` | Overrides the network to connect to. By | +| --network ` | default, the local network is used. | ++----------------------+-----------------------------------------------+ +| `-- | Specifies an argument using Candid syntax to | +| argument ` | pass to the canister during deployment. Note | +| | that this option requires you to define an | +| | actor class in the {proglang} program. | ++----------------------+-----------------------------------------------+ +| `--with-cycles | Enables you to specify the initial number of | +| ` | cycles for a canister in a project. | ++----------------------+-----------------------------------------------+ + +## Arguments {#_arguments} + +You can specify the following arguments for the `dfx deploy` command. + ++------------------------+---------------------------------------------+ +| Argument | Description | ++========================+=============================================+ +| `canister_name` | Specifies the name of the canister you want | +| | to register, build, and deploy. Note that | +| | the canister name you specify must match at | +| | least one name in the `canisters` section | +| | of the `dfx.json` configuration file for | +| | the project. If you don't specify a | +| | canister name, `dfx deploy` will deploy all | +| | canisters defined in the `dfx.json` file. | ++------------------------+---------------------------------------------+ + +# Examples {#_examples} + +You can use the `dfx deploy` command to deploy all or specific canisters +locally or on a specified network. + +For example, to deploy the `hello` project on the `ic-pubs` network +provider configured in the `dfx.json` configuration file, you can run +the following command: + +``` bash +dfx deploy hello --network ic-pubs +``` + +To deploy a project locally and pass a single argument to the +installation step, you can run a command similar to the following: + +``` bash +dfx deploy hello_actor_class --argument '("from DFINITY")' +``` + +Note that currently you must use an actor class in your {proglang} +program. In this example, the `dfx deploy` command specifies an argument +to pass to the `hello_actor_class` canister. The main program for the +`hello_actor_class` canister looks like this: + + actor class Greet(name: Text) { + public query func greet() : async Text { + return "Hello, " # name # "!"; + }; + }; + +You can use the `dfx deploy` command with the `--with-cycles` option to +specify the initial balance of a canister created by your wallet. If you +don't specify a canister, the number of cycles you specify will be added +to all canisters by default. To avoid this, specify a specific canister +by name. For example, to add an initial balance of 8000000000000 cycles +to a canister called \"hello-assets\", run the following command: + +``` bash +dfx deploy --with-cycles 8000000000000 hello-assets +``` diff --git a/modules/developers-guide/pages/cli-reference/dfx-envars.text b/modules/developers-guide/pages/cli-reference/dfx-envars.text new file mode 100644 index 000000000..9bc7ce93a --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-envars.text @@ -0,0 +1,89 @@ +--- +date: 2021-08-05 +title: Environment variables +--- + +You can configure certain properties for your {sdk-short-name} execution +environment using environment variables. + +This section lists the environment variables that are currently +supported with examples of how to use them. In most cases, you can set +environment variables for a session by executing an command in the +terminal or by adding a line similar to the following to your `.profile` +file: + + export DFX_TELEMETRY_DISABLED=1 + +# CANISTER_CANDID_PATH\_{canister.name} {#_canister_candid_path_canister_name} + +Use environment variables with the `CANISTER_CANDID_PATH` prefix to +reference the path to the Candid description file for the canisters that +are listed as dependencies in the `dfx.json` file for your project. + +For example, if you have a `whoami_assets` canister that lists `whoami` +under the `dependencies` key, you could use the +`CANISTER_CANDID_PATH_whoami_assets` environment variable to refer to +the location of the `whoami.did` file, which for local development might +be: + + $PROJECT_ROOT/.dfx/local/canisters/whoami/whoami.did + +# CANISTER_ID\_{canister.name} {#_canister_id_canister_name} + +Use environment variables with the `CANISTER_ID` prefix to reference the +canister identifier for each canister in the `dfx.json` file for your +project. + +For example, if you have a `linkedup` project that consists of the +`linkedup` and `connectd` canisters, you could use the +`CANISTER_ID_linkedup` and `CANISTER_ID_connectd` environment variables +to refer to the canister identifiers---for example +`ryjl3-tyaaa-aaaaa-aaaba-cai` and +`rrkah-fqaaa-aaaaa-aaaaq-cai`---created for your project. + +# DFX_CONFIG_ROOT {#_dfx_config_root} + +Use the `DFX_CONFIG_ROOT` environment variable to specify a different +location for storing the `.cache` and `.config` subdirectories for +`dfx`. + +By default, the `.cache` and `.config` directories are located in the +home directory for your development environment. For example, on macOS +the default location is in the `/Users/` directory. Use +the `DFX_CONFIG_ROOT` environment variable to specify a different +location for these directories. + + DFX_CONFIG_ROOT=~/ic-root + +# DFX_INSTALLATION_ROOT {#_dfx_installation_root} + +Use the `DFX_INSTALLATION_ROOT` environment variable to specify a +different location for the `dfx` binary if you are not using the default +location for your operating system. + +The `.cache/dfinity/uninstall.sh` script uses this environment variable +to identify the root directory for your {sdk-short-name} installation. + +# DFX_TELEMETRY_DISABLED {#_dfx_telemetry_disabled} + +Use the `DFX_TELEMETRY_DISABLED` environment variable to opt-out of +having data collected about `dfx` usage. + +By default, `dfx` is configured to collect anonymous---that is, no +identifying information such as IP addresses or user information---data +about `dfx` command activity and errors. Collecting anonymous data is +enabled by default in an effort to improve the developer experience +based on usage patterns and behavior. + +If you want to prevent the collection of data about `dfx` usage, +however, you can explicitly opt-out by setting the +`DFX_TELEMETRY_DISABLED` environment variable to one. + + DFX_TELEMETRY_DISABLED=1 + +# DFX_VERSION {#_dfx_version} + +Use the `DFX_VERSION` environment variable to identify a specific +version of the {sdk-short-name} that you want to install. + + DFX_VERSION=0.8.0 sh -ci "$(curl -fsSL https://sdk.dfinity.org/install.sh)" diff --git a/modules/developers-guide/pages/cli-reference/dfx-help.text b/modules/developers-guide/pages/cli-reference/dfx-help.text new file mode 100644 index 000000000..67290166b --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-help.text @@ -0,0 +1,40 @@ +--- +date: 2021-08-05 +title: dfx help +--- + +Use this command to view usage information for the `dfx` parent command +or for any specified subcommand. + +# Basic usage {#_basic_usage} + +``` bash +dfx help [subcommand] +``` + +# Arguments {#_arguments} + +You can specify any `dfx` subcommand as an argument to view usage +information for that subcommand using the `dfx help` command. + ++-----------------------+----------------------------------------------+ +| Argument | Description | ++=======================+==============================================+ +| `subcommand` | Specifies the subcommand usage information | +| | you want to display. | ++-----------------------+----------------------------------------------+ + +# Examples {#_examples} + +To display the usage information for `dfx`, run the following command: + +``` bash +dfx help +``` + +To display the usage information for `dfx bew`, run the following +command: + +``` bash +dfx help new +``` diff --git a/modules/developers-guide/pages/cli-reference/dfx-identity.text b/modules/developers-guide/pages/cli-reference/dfx-identity.text new file mode 100644 index 000000000..b2f60d3fb --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-identity.text @@ -0,0 +1,583 @@ +--- +date: 2021-08-05 +title: dfx identity +--- + +Use the `dfx identity` command with subcommands and flags to manage the +identities used to execute commands and communicate with the Internet +Computer network. Creating multiple user identities enables you to test +user-based access controls. + +The basic syntax for running `dfx identity` commands is: + +``` bash +dfx identity [subcommand] [flag] +``` + +Depending on the `dfx identity` subcommand you specify, additional +arguments, options, and flags might apply or be required. To view usage +information for a specific `dfx identity` subcommand, specify the +subcommand and the `--help` flag. For example, to see usage information +for `dfx identity new`, you can run the following command: + +``` bash +dfx identity new --help +``` + +For reference information and examples that illustrate using +`dfx identity` commands, select an appropriate command. + ++----------------------+-----------------------------------------------+ +| Command | Description | ++======================+===============================================+ +| [`get-p | Shows the textual representation of the | +| rincipal`](#_dfx_ide | principal associated with the current | +| ntity_get_principal) | identity. | ++----------------------+-----------------------------------------------+ +| [ | Shows the canister identifier for the wallet | +| `get-wallet`](#_dfx_ | associated with your current identity | +| identity_get_wallet) | principal on a network. | ++----------------------+-----------------------------------------------+ +| `help` | Displays this usage message or the help of | +| | the given subcommand(s). | ++----------------------+-----------------------------------------------+ +| [`import`](#_ | Creates a new identity by importing a PEM | +| dfx_identity_import) | file that contains the key information or | +| | security certificate for a principal. | ++----------------------+-----------------------------------------------+ +| [`list`]( | Lists existing identities. | +| #_dfx_identity_list) | | ++----------------------+-----------------------------------------------+ +| [`new`] | Creates a new identity. | +| (#_dfx_identity_new) | | ++----------------------+-----------------------------------------------+ +| [`remove`](#_ | Removes an existing identity. | +| dfx_identity_remove) | | ++----------------------+-----------------------------------------------+ +| [`rename`](#_ | Renames an existing identity. | +| dfx_identity_rename) | | ++----------------------+-----------------------------------------------+ +| [ | Sets the wallet canister identifier to use | +| `set-wallet`](#_dfx_ | for your current identity principal on a | +| identity_set_wallet) | network. | ++----------------------+-----------------------------------------------+ +| [`use`] | Specifies the identity to use. | +| (#_dfx_identity_use) | | ++----------------------+-----------------------------------------------+ +| [`whoami`](#_ | Displays the name of the current identity | +| dfx_identity_whoami) | user context. | ++----------------------+-----------------------------------------------+ + +# Creating a default identity {#_creating_a_default_identity} + +The first time you run the `dfx canister create` command to register an +identifier, your public/private key pair credentials are used to create +a `default` user identity. The credentials for the `default` user are +migrated from `$HOME/.dfinity/identity/creds.pem` to +`$HOME/.config/dfx/identity/default/identity.pem`. + +You can then use `dfx identity new` to create new user identities and +store credentials for those identities in +`$HOME/.config/dfx/identity//identity.pem` files. For +example, you can create an identity named `ic_admin` by running the +following command: + + dfx identity new ic_admin + +This command adds a private key for the `ic_admin` user identity in the +`~/.config/dfx/identity/ic_admin/identity.pem` file. + +# dfx identity get-principal {#_dfx_identity_get_principal} + +Use the `dfx identity get-principal` command to display the textual +representation of a principal associated with the current user identity +context. + +If you haven't created any user identities, you can use this command to +display the principal for the `default` user. The textual representation +of a principal can be useful for establishing and testing role-based +authorization scenarios. + +## Basic usage {#_basic_usage} + +``` bash +dfx identity get-principal [flag] +``` + +## Flags {#_flags} + +You can use the following optional flags with the +`dfx identity get-principal` command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +## Example {#_example} + +If you want to display the textual representation of a principal +associated with a specific user identity context, you can run commands +similar to the following: + +``` bash +dfx identity use ic_admin +dfx identity get-principal +``` + +In this example, the first command sets the user context to use the +`ic_admin` identity. The second command then returns the principal +associated with the `ic_admin` identity. + +# dfx identity get-wallet {#_dfx_identity_get_wallet} + +Use the `dfx identity get-wallet` command to display the canister +identifier for the wallet associated with your current identity +principal on a network. + +Note that you must be connected to the {IC} network or running the +network locally to run this command. In addition, you must be in a +project directory to run the command. For example, if your project name +is `hello_world`, your current working directory must be the +`hello_world` top-level project directory or one of its subdirectories +to run the `dfx identity get-wallet` command. + +## Basic usage {#_basic_usage_2} + +``` bash +dfx identity get-wallet [flag] +``` + +## Flags {#_flags_2} + +You can use the following optional flags with the +`dfx identity get-wallet` command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +## Example {#_example_2} + +If you want to display the canister identifier for the wallet canister +associated with your identity, you can run the following command: + +``` bash +dfx identity get-wallet +``` + +To display the canister identifier for the wallet canister associated +with your identity on a specific network, you might run a command +similar to the following: + +``` bash +dfx identity --network=https://192.168.74.4 get-wallet +``` + +# dfx identity import {#_dfx_identity_import} + +Use the `dfx identity import` command to create a user identity by +importing the user's key information or security certificate from a PEM +file. + +## Basic usage {#_basic_usage_3} + +``` bash +dfx identity import [flag] identity-name pem_file-name +``` + +## Flags {#_flags_3} + +You can use the following optional flags with the `dfx identity import` +command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +## Examples {#_examples} + +You can use the `dfx identity import` command to import a PEM file that +contains the security certificate to use for an identity. For example, +you can run the following command to import the `generated-id.pem` file +to create the user identity `alice`: + +``` bash +dfx identity import alice generated-id.pem +``` + +The command adds the `generated-id.pem` file to the +`~/.config/dfx/identity/alice` directory. + +# dfx identity list {#_dfx_identity_list} + +Use the `dfx identity list` command to display the list of user +identities available. When you run this command, the list displays an +asterisk (\*) to indicate the currently active user context. You should +note that identities are global. They are not confined to a specific +project context. Therefore, you can use any identity listed by the +`dfx identity list` command in any project. + +## Basic usage {#_basic_usage_4} + +``` bash +dfx identity list [flag] +``` + +## Flags {#_flags_4} + +You can use the following optional flags with the `dfx identity list` +command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +## Examples {#_examples_2} + +You can use the `dfx identity list` command to list all of the +identities you have currently available and to determine which identity +is being used as the currently-active user context for running `dfx` +commands. For example, you can run the following command to list the +identities available: + +``` bash +dfx identity list +``` + +This command displays the list of identities found similar to the +following: + +``` bash +alice_auth +bob_standard * +default +ic_admin +``` + +In this example, the `bob_standard` identity is the currently-active +user context. After you run this command to determine the active user, +you know that any additional `dfx` commands you run are executed using +the principal associated with the `bob_standard` identity. + +# dfx identity new {#_dfx_identity_new} + +Use the `dfx identity new` command to add new user identities. You +should note that the identities you add are global. They are not +confined to a specific project context. Therefore, you can use any +identity you add using the `dfx identity new` command in any project. + +## Basic usage {#_basic_usage_5} + +``` bash +dfx identity new [flag] _identity-name_ +``` + +## Flags {#_flags_5} + +You can use the following optional flags with the `dfx identity new` +command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +## Arguments {#_arguments} + +You must specify the following argument for the `dfx identity new` +command. + ++----------------------+-----------------------------------------------+ +| Argument | Description | ++======================+===============================================+ +| `` | Specifies the name of the identity to create. | +| | This argument is required. | ++----------------------+-----------------------------------------------+ + +## Examples {#_examples_3} + +You can then use `dfx identity new` to create new user identities and +store credentials for those identities in +`$HOME/.config/dfx/identity//identity.pem` files. For +example, you can create an identity named `ic_admin` by running the +following command: + + dfx identity new ic_admin + +This command adds a private key for the `ic_admin` user identity in the +`~/.config/dfx/identity/ic_admin/identity.pem` file. + +After adding the private key for the new identity, the command displays +confirmation that the identity has been created: + + Creating identity: "ic_admin". + Created identity: "ic_admin". + +# dfx identity remove {#_dfx_identity_remove} + +Use the `dfx identity remove` command to remove an existing user +identity. You should note that the identities you add are global. They +are not confined to a specific project context. Therefore, any identity +you remove using the `dfx identity remove` command will no longer be +available in any project. + +## Basic usage {#_basic_usage_6} + +``` bash +dfx identity remove [flag] _identity-name_ +``` + +## Flags {#_flags_6} + +You can use the following optional flags with the `dfx identity remove` +command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +## Arguments {#_arguments_2} + +You must specify the following argument for the `dfx identity remove` +command. + ++----------------------+-----------------------------------------------+ +| Argument | Description | ++======================+===============================================+ +| `` | Specifies the name of the identity to remove. | +| | This argument is required. | ++----------------------+-----------------------------------------------+ + +## Examples {#_examples_4} + +You can use the `dfx identity remove` command to remove any +previously-created identity, including the `default` user identity. For +example, if you have added named user identities and want to remove the +`default` user identity, you can run the following command: + + dfx identity remove default + +The command displays confirmation that the identity has been removed: + + Removing identity "default". + Removed identity "default". + +Although you can delete the `default` identity if you have created other +identities to replace it, you must always have at least one identity +available. If you attempt to remove the last remaining user context, the +`dfx identity remove` command displays an error similar to the +following: + + Identity error: + Cannot delete the default identity + +# dfx identity rename {#_dfx_identity_rename} + +Use the `dfx identity rename` command to rename an existing user +identity. You should note that the identities you add are global. They +are not confined to a specific project context. Therefore, any identity +you rename using the `dfx identity rename` command is available using +the new name in any project. + +## Basic usage {#_basic_usage_7} + +``` bash +dfx identity rename [flag] _from_identity-name_ _to_identity-name_ +``` + +## Flags {#_flags_7} + +You can use the following optional flags with the `dfx identity rename` +command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +## Arguments {#_arguments_3} + +You must specify the following arguments for the `dfx identity rename` +command. + ++----------------------+-----------------------------------------------+ +| Argument | Description | ++======================+===============================================+ +| `< | Specifies the current name of the identity | +| from_identity_name>` | you want to rename. This argument is | +| | required. | ++----------------------+-----------------------------------------------+ +| `` | Specifies the new name of the identity you | +| | want to rename. This argument is required. | ++----------------------+-----------------------------------------------+ + +## Example {#_example_3} + +You can rename the `default` user or any identity you have previously +created using the `dfx identity rename` command. For example, if you +want to rename a `test_admin` identity that you previously created, you +would specify the current identity name you want to change **from** and +the new name you want to change **to** by running a command similar to +the following: + + dfx identity rename test_admin devops + +# dfx identity set-wallet {#_dfx_identity_set_wallet} + +Use the `dfx identity set-wallet` command to specify the wallet canister +identifier to use for your identity on a network. + +## Basic usage {#_basic_usage_8} + +``` bash +dfx identity set-wallet [flag] [--canister-name canister-name] +``` + +## Flags {#_flags_8} + +You can use the following optional flags with the +`dfx identity set-wallet` command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `force` | Skips verification that the canister you | +| | specify is a valid wallet canister. This | +| | option is only useful if you are connecting | +| | to the {IC} running locally. | ++----------------------+-----------------------------------------------+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +## Example {#_example_4} + +If you have access to more than one {IC} network or use more than one +principal for your identity, you might have access to more than one +wallet canister identifier. You can use the `dfx identity set-wallet` +command to specify the wallet canister identifier to use for a given +identity on a given network. + +For example, you might store the wallet canister identifier in an +environment variable, then invoke the `dfx identity set-wallet` command +to use that wallet canister for additional operations by running the +following: + + export WALLET_CANISTER_ID=$(dfx identity get-wallet) + dfx identity --network=https://192.168.74.4 set-wallet --canister-name ${WALLET_CANISTER_ID} + +# dfx identity use {#_dfx_identity_use} + +Use the `dfx identity use` command to specify the user identity you want +to active. You should note that the identities you have available to use +are global. They are not confined to a specific project context. +Therefore, you can use any identity you have previously created in any +project. + +## Basic usage {#_basic_usage_9} + +``` bash +dfx identity use [flag] _identity-name_ +``` + +## Flags {#_flags_9} + +You can use the following optional flags with the `dfx identity use` +command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +## Arguments {#_arguments_4} + +You must specify the following argument for the `dfx identity use` +command. + ++----------------------+-----------------------------------------------+ +| Argument | Description | ++======================+===============================================+ +| `` | Specifies the name of the identity you want | +| | to make active for subsequent commands. This | +| | argument is required. | ++----------------------+-----------------------------------------------+ + +## Examples {#_examples_5} + +If you want to run multiple commands with the same user identity +context, you can run a command similar to the following: + + dfx identity use ops + +After running this command, subsequent commands use the credentials and +access controls associated with the `ops` user. + +# dfx identity whoami {#_dfx_identity_whoami} + +Use the `dfx identity whoami` command to display the name of the +currently-active user identity context. + +## Basic usage {#_basic_usage_10} + +``` bash +dfx identity whoami [flag] +``` + +## Flags {#_flags_10} + +You can use the following optional flags with the `dfx identity whoami` +command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +## Example {#_example_5} + +If you want to display the name of the currently-active user identity, +you can run the following command: + +``` bash +dfx identity whoami +``` + +The command displays the name of the user identity. For example, you had +previously run the command `dfx identity use bob_standard`, the command +would display: + + bob_standard diff --git a/modules/developers-guide/pages/cli-reference/dfx-ledger.text b/modules/developers-guide/pages/cli-reference/dfx-ledger.text new file mode 100644 index 000000000..8225fb7b7 --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-ledger.text @@ -0,0 +1,496 @@ +--- +date: 2021-08-05 +title: dfx ledger +--- + +Use the `dfx ledger` command to interact with the ledger canister. + +This command can be used to make ICP utlity token transactions from one +to another, or top up canisters with cycles from ICP. + +The basic syntax for running `dfx ledger` commands is: + +``` bash +dfx ledger [options] [subcommand] +``` + +Depending on the `dfx ledger` subcommand you specify, additional +arguments, options, and flags might apply. For reference information and +examples that illustrate using `dfx ledger` commands, select an +appropriate command. + ++----------------------+-----------------------------------------------+ +| Command | Description | ++======================+===============================================+ +| [`accou | Prints the selected identity's Account | +| nt-id`](#account-id) | Identifier. | ++----------------------+-----------------------------------------------+ +| [ | Prints the account balance of the user. | +| `balance`](#balance) | | ++----------------------+-----------------------------------------------+ +| [`create-canister | Creates a canister from ICP. | +| `](#create-canister) | | ++----------------------+-----------------------------------------------+ +| `help` | Displays usage information message for a | +| | specified subcommand. | ++----------------------+-----------------------------------------------+ +| [`notify`](#notify) | Notifies the ledger when there is a send | +| | transaction to the cycles minting canister. | ++----------------------+-----------------------------------------------+ +| [`top-up`](#top-up) | Tops up a canister with cycles minted from | +| | ICP. | ++----------------------+-----------------------------------------------+ +| [`t | Transfers ICP from the user to the | +| ransfer`](#transfer) | destination Account Identifier. | ++----------------------+-----------------------------------------------+ + +To view usage information for a specific subcommand, specify the +subcommand and the `--help` flag. For example, to see usage information +for `dfx ledger transfer`, you can run the following command: + +`dfx ledger transfer --help` + +# dfx ledger account-id {#account-id} + +Use the `dfx ledger account-id` command to display the account +identifier associated with the currently-active identity. Like the +textual representation of your developer identity principal, the account +identifier is derived from your private key and used to represent your +identity in the ledger canister. + +## Basic usage {#_basic_usage} + +``` bash +dfx ledger account-id [flag] +``` + +## Flags {#_flags} + +You can use the following optional flags with the +`dfx ledger account-id` command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +## Examples {#_examples} + +If you have created more than one identity, check the identity you are +currently using by running the `dfx identity whoami` command or the +`dfx identity get-principal` command. You can then check the account +identifier for your currently-selected developer identity by running the +following command: + +``` bash +dfx ledger account-id +``` + +The command displays output similar to the following: + + 03e3d86f29a069c6f2c5c48e01bc084e4ea18ad02b0eec8fccadf4487183c223 + +# dfx ledger balance {#balance} + +Use the `dfx ledger balance` command to print your account balance or +that of another user. + +## Basic usage {#_basic_usage_2} + +``` bash +dfx ledger --network ic balance [of] [flag] +``` + +## Flags {#_flags_2} + +You can use the following optional flags with the `dfx ledger balance` +command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +## Arguments {#_arguments} + +You can specify the following argument for the `dfx ledger balance` +command. + ++----------------------+-----------------------------------------------+ +| Argument | Description | ++======================+===============================================+ +| `` | Specify an Account Identifier to get the | +| | balance. If this command is not specified, | +| | the command returns the balance of ICP tokens | +| | for the currently-selected user identity. | ++----------------------+-----------------------------------------------+ + +## Examples {#_examples_2} + +You can use the `dfx ledger balance` command to check the balance of +another user. For example, you can run the following command to see the +ICP utlity tokens associated with a known Account Identifier: + +``` bash +dfx ledger --network ic balance 03e3d86f29a069c6f2c5c48e01bc084e4ea18ad02b0eec8fccadf4487183c223 +``` + +This command displays an ICP amount similar to the following: + + 2.49798000 ICP + +# dfx ledger create-canister {#create-canister} + +Use the `dfx ledger create-canister` command to convert ICP tokens to +cycles and to register a new canister identifier on the {IC}. + +## Basic usage {#_basic_usage_3} + +``` bash +dfx ledger --network ic create-canister controller [options] [flag] +``` + +## Flags {#_flags_3} + +You can use the following optional flags with the +`dfx ledger create-canister` command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +## Arguments {#_arguments_2} + +You can specify the following argument for the +`dfx ledger create-canister` command. + ++----------------------+-----------------------------------------------+ +| Argument | Description | ++======================+===============================================+ +| `` | Specifies the principal identifier to set as | +| | the controller of the new canister. | ++----------------------+-----------------------------------------------+ + +## Options {#_options} + +You can specify the following argument for the +`dfx ledger create-canister` command. + ++----------------------+-----------------------------------------------+ +| Option | Description | ++======================+===============================================+ +| `--amount ` | Specify the number of ICP tokens to mint into | +| | cycles and deposit into destination canister. | +| | You can specify an amount as a number with up | +| | to eight (8) decimal places. | ++----------------------+-----------------------------------------------+ +| `--e8s ` | Specify ICP token fractional units---called | +| | e8s---as a whole number, where one e8 is | +| | smallest partition of an ICP token. For | +| | example, 1.05000000 is 1 ICP and 5000000 e8s. | +| | You can use this option on its own or in | +| | conjunction with the `--icp` option. | ++----------------------+-----------------------------------------------+ +| `--fee ` | Specify a transaction fee. The default is | +| | 10000 e8s. | ++----------------------+-----------------------------------------------+ +| `--icp ` | Specify ICP tokens as a whole number. You can | +| | use this option on its own or in conjunction | +| | with `--e8s`. | ++----------------------+-----------------------------------------------+ +| ` | Specify a maximum transaction fee. The | +| --max-fee ` | default is 10000 e8s. | ++----------------------+-----------------------------------------------+ + +## Examples {#_examples_3} + +To create a new canister with cycles, transfer ICP tokens from your +ledger account by running a command similar to the following: + +``` bash +dfx ledger --network ic create-canister tsqwz-udeik-5migd-ehrev-pvoqv-szx2g-akh5s-fkyqc-zy6q7-snav6-uqe --amount 1.25 +``` + +This command converts the number of ICP tokens you specify for the +`--amount` argument into cycles, and associates the cycles with a new +canister identifier controlled by the principal you specify. + +In this example, the command converts 1.25 ICP tokens into cycles and +specifies the principal identifier for the default identity as the +controller of the new canister. + +If the transaction is successful, the ledger records the event and you +should see output similar to the following: + + Transfer sent at BlockHeight: 20 + Canister created with id: "53zcu-tiaaa-aaaaa-qaaba-cai" + +You can create a new canister by specifying separate values for ICP +tokens and e8s by running a command similar to the following: + +``` bash +dfx ledger --network ic create-canister tsqwz-udeik-5migd-ehrev-pvoqv-szx2g-akh5s-fkyqc-zy6q7-snav6-uqe --icp 3 --e8s 5000 +``` + +# dfx ledger notify {#notify} + +Use the `dfx ledger notify` command to notify the ledger about a send +transaction to the cycles minting canister. This command should only be +used if `dfx ledger create-canister` or `dfx ledger top-up` successfully +sent a message to the ledger, and a transaction was recorded at some +block height, but for some reason the subsequent notify failed. + +## Basic usage {#_basic_usage_4} + +``` bash +dfx ledger notify [options] _block-height_ _destination-principal_ +``` + +## Flags {#_flags_4} + +You can use the following optional flags with the `dfx ledger notify` +command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +## Arguments {#_arguments_3} + +You can specify the following argument for the `dfx ledger notify` +command. + ++----------------------+-----------------------------------------------+ +| Argument | Description | ++======================+===============================================+ +| `` | Specifies the block height at which the send | +| | transaction was recorded. | ++----------------------+-----------------------------------------------+ +| `` | either a canister identifier or the textual | +| | representation of a user principal. If the | +| | send transaction was for the | +| | `create-canister` command, specify the | +| | `controller` principal. If the send | +| | transaction was for the `top-up` command, | +| | specify the `canister ID`. | ++----------------------+-----------------------------------------------+ + +## Examples {#_examples_4} + +The following example illustrates sending a `notify` message to the +ledger in response to a `_send+` transaction that was recorded at the +block height `75948`. + +``` bash +dfx ledger --network ic notify 75948 tsqwz-udeik-5migd-ehrev-pvoqv-szx2g-akh5s-fkyqc-zy6q7-snav6-uqe +``` + +# dfx ledger top-up {#top-up} + +Use the `dfx ledger top-up` command to top up a canister with cycles +minted from ICP tokens. + +## Basic usage {#_basic_usage_5} + +``` bash +dfx ledger --network ic top-up [options] canister [flag] +``` + +## Flags {#_flags_5} + +You can use the following optional flags with the `dfx ledger top-up` +command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +## Arguments {#_arguments_4} + +You can specify the following argument for the `dfx ledger top-up` +command. + ++----------------------+-----------------------------------------------+ +| Argument | Description | ++======================+===============================================+ +| `canister` | Specifies the canister identifier that you | +| | would like to top up. | ++----------------------+-----------------------------------------------+ + +## Options {#_options_2} + +You can specify the following options for the `dfx ledger top-up` +command. + ++----------------------+-----------------------------------------------+ +| Option | Description | ++======================+===============================================+ +| `--amount ` | Specifies the number of ICP tokens to mint | +| | into cycles and deposit into the destination | +| | canister. You can specify the amount as a | +| | number with up to eight (8) decimal places. | ++----------------------+-----------------------------------------------+ +| `--e8s ` | Specifies fractional units of an ICP | +| | token---called e8s---as a whole number, where | +| | one e8 is the smallest unit of an ICP token. | +| | For example, 1.05000000 is 1 ICP and 5000000 | +| | e8s. You can use this option on its own or in | +| | conjunction with the `--icp` option. | ++----------------------+-----------------------------------------------+ +| `--fee ` | Specifies the transaction fee for the | +| | operation. The default is 10000 e8s. | ++----------------------+-----------------------------------------------+ +| `--icp ` | Specifies ICP tokens as a whole number. You | +| | can use this option on its own or in | +| | conjunction with `--e8s`. | ++----------------------+-----------------------------------------------+ +| ` | Specifies a maximum transaction fee. The | +| --max-fee ` | default is 10000 e8s. | ++----------------------+-----------------------------------------------+ + +## Examples {#_examples_5} + +You can use the `dfx ledger top-up` command to top up the cycles of a +specific canister from the balance of ICP tokens you control. The +canister identifier must be associated with a cycles wallet canister +that is able to receive cycles. Alternatively, you can modify a +non-cycles wallet canister to implement a method to receive cycles using +system APIs described in the [Internet Computer Interface +Specification](../../interface-spec/index.xml). + +For example, you can run the following command to top-up a cycles wallet +canister deployed on the Internet Computer with 1 ICP worth of cycles: + +``` bash +dfx ledger --network ic top-up --icp 1 5a46r-jqaaa-aaaaa-qaadq-cai +``` + +This command displays output similar to the following: + + Transfer sent at BlockHeight: 59482 + Canister was topped up! + +# dfx ledger transfer {#transfer} + +Use the `dfx ledger transfer` command to transfer ICP tokens from your +account address in the ledger canister to a destination address. + +## Basic usage {#_basic_usage_6} + +``` bash +dfx ledger transfer [options] to --memo memo +``` + +## Flags {#_flags_6} + +You can use the following optional flags with the `dfx ledger transfer` +command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +## Arguments {#_arguments_5} + +You can specify the following argument for the `dfx ledger transfer` +command. + ++----------------------+-----------------------------------------------+ +| Argument | Description | ++======================+===============================================+ +| `` | Specify the Account Identifier or address to | +| | which you want to transfer ICP tokens. | ++----------------------+-----------------------------------------------+ + +## Options {#_options_3} + +You can specify the following argument for the `dfx ledger transfer` +command. + ++----------------------+-----------------------------------------------+ +| Option | Description | ++======================+===============================================+ +| `--amount ` | Specifies the number of ICP tokens to | +| | transfer. Can be specified as a number with | +| | up to eight (8) decimal places. | ++----------------------+-----------------------------------------------+ +| `--e8s ` | Specifies e8s as a whole number, where one e8 | +| | is smallest partition of an ICP token. For | +| | example, 1.05000000 is 1 ICP and 5000000 e8s. | +| | You can use this option alone or in | +| | conjunction with the `--icp` option. | ++----------------------+-----------------------------------------------+ +| `--fee ` | Specifies a transaction fee. The default is | +| | 10000 e8s. | ++----------------------+-----------------------------------------------+ +| `--icp ` | Specifies ICP as a whole number. You can use | +| | this option alone or in conjunction with | +| | `--e8s`. | ++----------------------+-----------------------------------------------+ +| `--memo ` | Specifies a numeric memo for this | +| | transaction. | ++----------------------+-----------------------------------------------+ + +## Examples {#_examples_6} + +You can use the `dfx ledger transfer` command to send ICP to the Account +Identifier of the destination. + +For example, you can run the following command to check the account +identifier associated with the principal you are currently using: + +``` bash +dfx ledger account-id +``` + +This command displays output similar to the following: + + 30e596fd6c5ff5ad7b7d70bbbda1187c833e646c6251464da7f82bc217bba397 + +You can check the balance of this account by running the following +command: + +``` bash +dfx ledger --network ic balance +``` + +This command displays output similar to the following: + + 64.89580000 ICP + +Use the `dfx ledger transfer` command to send some of your ICP balance +to another known destination using the following command: + +``` bash +dfx ledger --network ic transfer dfx ledger --network ic transfer dd81336dbfef5c5870e84b48405c7b229c07ad999fdcacb85b9b9850bd60766f --memo 12345 --icp 1 +``` + +This command displays output similar to the following: + + Transfer sent at BlockHeight: 59513 + +You can then use the `dfx ledger --network ic balance` command to check +that your account balance reflects the transaction you just made. diff --git a/modules/developers-guide/pages/cli-reference/dfx-new.text b/modules/developers-guide/pages/cli-reference/dfx-new.text new file mode 100644 index 000000000..e18a19746 --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-new.text @@ -0,0 +1,76 @@ +--- +date: 2021-08-05 +title: dfx new +--- + +Use the `dfx new` command to create a new project for the {platform}. +This command creates a default project structure with template files +that you can modify to suit your application. You must specify the name +of the project to you want to create. + +You can use the `--dry-run` option to preview the directories and files +to be created without adding them to the file system. + +# Basic usage {#_basic_usage} + +``` bash +dfx new _project_name_ [flag] +``` + +# Flags {#_flags} + +You can use the following optional flags with the `dfx new` command: + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `--dry-run` | Generates a preview the directories and files | +| | to be created for a new project without | +| | adding them to the file system. | ++----------------------+-----------------------------------------------+ +| `--frontend` | Installs the template frontend code for the | +| | default project canister. The default value | +| | for the flag is `true` if `node.js` is | +| | currently installed on your local computer. | +| | If `node.js` is not currently installed, you | +| | can set this flag to `true` to attempt to | +| | install `node.js` and the template file when | +| | creating the project or you can set the flag | +| | to `false` to skip the installation of | +| | template frontend code entirely. | ++----------------------+-----------------------------------------------+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +# Arguments {#_arguments} + +You must specify the following argument for the `dfx new` command. + ++----------------------+-----------------------------------------------+ +| Argument | Description | ++======================+===============================================+ +| `project_name` | Specifies the name of the project to create. | +| | This argument is required. | ++----------------------+-----------------------------------------------+ + +# Examples {#_examples} + +You can use `dfx new` to create a new project named `my_social_network` +by running the following command: + +``` bash +dfx new my_social_network +``` + +The command creates a new project, including a default project directory +structure under the new project name and a Git repository for your +project. + +If you want to preview the directories and files to be created without +adding them to the file system, you can run the following command: + +``` bash +dfx new my_social_network --dry-run +``` diff --git a/modules/developers-guide/pages/cli-reference/dfx-parent.text b/modules/developers-guide/pages/cli-reference/dfx-parent.text new file mode 100644 index 000000000..8ec1bc143 --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-parent.text @@ -0,0 +1,195 @@ +--- +date: 2021-08-05 +title: dfx +--- + +The DFINITY command-line execution environment (`dfx`) is the primary +tool for creating, deploying, and managing the applications you develop +for the {platform}. + +Use the `dfx` parent command with flags and subcommands to specify the +operations you want to perform with or without optional arguments. + +# Basic usage {#_basic_usage} + +``` bash +dfx [option] [subcommand] [flag] +``` + +# Flags {#_flags} + +You can use the following optional flags with the `dfx` parent command +or with any of the `dfx` subcommands. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `` -q` ``, `--quiet` | Suppresses informational messages. | ++----------------------+-----------------------------------------------+ +| `-v`, `--verbose` | Displays detailed information about | +| | operations. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +# Options {#_options} + +You can use the following options with the `dfx` command. + ++----------------------+-----------------------------------------------+ +| Option | Description | ++======================+===============================================+ +| `-- | Specifies the user identity to use when | +| identity ` | running a command. | ++----------------------+-----------------------------------------------+ +| ` | Writes log file messages to the specified log | +| --logfile ` | file name if you use the `--log file` logging | +| | option. | ++----------------------+-----------------------------------------------+ +| `--log ` | Specifies the logging mode to use. + You can | +| | set the log mode to one of the following: | +| | | +| | \- `stderr` to log messages to the standard | +| | error facility. | +| | | +| | \- `tee` to write messages to both standard | +| | output and to a specified file name. | +| | | +| | \- `file` to write messages to a specified | +| | file name. | +| | | +| | The default logging mode is `stderr`. | ++----------------------+-----------------------------------------------+ + +# Subcommands {#_subcommands} + +Use the following subcommands to specify the operation you want to +perform or to view usage information for a specific command. + +For reference information and examples, select an appropriate +subcommand. + ++----------------------+-----------------------------------------------+ +| Command | Description | ++======================+===============================================+ +| [`bootstrap` | Starts the bootstrap server you want to use | +| ](dfx-bootstrap.xml) | to serve front-end assets for your project. | ++----------------------+-----------------------------------------------+ +| [`bu | Builds canister output from the source code | +| ild`](dfx-build.xml) | in your project. | ++----------------------+-----------------------------------------------+ +| [`ca | Manages the `dfx` cache on the local | +| che`](dfx-cache.xml) | computer. | ++----------------------+-----------------------------------------------+ +| [`canister | Manages canisters deployed on a network | +| `](dfx-canister.xml) | replica. | ++----------------------+-----------------------------------------------+ +| [`conf | Sets or changes configuration options for | +| ig`](dfx-config.xml) | your current project. | ++----------------------+-----------------------------------------------+ +| [`depl | Deploys all or a specific canister from the | +| oy`](dfx-deploy.xml) | code in your project. By default, all | +| | canisters are deployed. | ++----------------------+-----------------------------------------------+ +| [` | Displays usage information for a specified | +| help`](dfx-help.xml) | subcommand. | ++----------------------+-----------------------------------------------+ +| [`identity | Enables you to create and manage the | +| `](dfx-identity.xml) | identities used to communicate with the | +| | Internet Computer network. | ++----------------------+-----------------------------------------------+ +| [`ledg | Enables you to interact with accounts in the | +| er`](dfx-ledger.xml) | ledger canister running on the Internet | +| | Computer. | ++----------------------+-----------------------------------------------+ +| [`new`](dfx-new.xml) | Creates a new project. | ++----------------------+-----------------------------------------------+ +| [` | Sends a response request to a specified | +| ping`](dfx-ping.xml) | Internet Computer network to determine | +| | network connectivity. If the connection is | +| | successful, the Internet Computer replies | +| | with its status. | ++----------------------+-----------------------------------------------+ +| [`replic | Starts a local network replica process. | +| a`](dfx-replica.xml) | | ++----------------------+-----------------------------------------------+ +| [`st | Starts the local network replica and a web | +| art`](dfx-start.xml) | server for the current project. | ++----------------------+-----------------------------------------------+ +| [` | Stops the local network replica. | +| stop`](dfx-stop.xml) | | ++----------------------+-----------------------------------------------+ +| [`upgrad | Upgrades the version of `dfx` installed on | +| e`](dfx-upgrade.xml) | the local computer to the latest version | +| | available. | ++----------------------+-----------------------------------------------+ +| [`dfx wall | Enables you to manage cycles, controllers, | +| et`](dfx-wallet.xml) | custodians, and addresses for the default | +| | cycles wallet associated with the | +| | currently-selected identity. | ++----------------------+-----------------------------------------------+ + +# Examples {#_examples} + +You can use the `dfx` parent command to display usage information or +version information. For example, to display information about the +version of `dfx` you currently have installed, you can run the following +command: + +``` bash +dfx --version +``` + +To view usage information for a specific subcommand, specify the +subcommand and the `--help` flag. For example, to see usage information +for `dfx build`, you can run the following command: + +``` bash +dfx build --help +``` + +## Using logging options {#_using_logging_options} + +You can use the `--verbose` and `--quiet` flags to increment or +decrement the logging level. If you don't specify any logging level, +CRITICAL, ERROR, WARNING, and INFO messages are logged by default. +Specifying one verbose flag (`-v`) increases the log level to include +DEBUG messages. Specifying two verbose flags (`-vv`)increases the +logging level to include both DEBUG and TRACE messages. + +Adding a `--quiet` flag decreases the logging level. For example, to +remove all messages, you can run a command similar the following: + +``` bash +dfx -qqqq build +``` + +Keep in mind that using TRACE level logging (`--vv`) generates a lot of +log messages that can affect performance and should only be used when +required for troubleshooting or analysis. + +To output log messages to a file named `newlog.txt` and display the +messages on your terminal when creating a new project, you can run a +command similar to the following: + +``` bash +dfx --log tee --logfile newlog.txt new hello_world +``` + +## Specifying a user identity {#_specifying_a_user_identity} + +If you create user identities with the `dfx identity new` command, you +can then use the `--identity` comment-line option to change the user +context when running other `dfx` commands. + +In the most common use case, you use the `--identity` option to call +specific canister functions to test access controls for specific +operations. + +For example, you might want to test whether the `devops` user identity +can call the `modify_profile` function for the `accounts` canister by +running the following command: + + dfx --identity devops canister call accounts modify_profile '("Kris Smith")' diff --git a/modules/developers-guide/pages/cli-reference/dfx-ping.text b/modules/developers-guide/pages/cli-reference/dfx-ping.text new file mode 100644 index 000000000..4df7a7819 --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-ping.text @@ -0,0 +1,60 @@ +--- +date: 2021-08-05 +title: dfx ping +--- + +Use the `dfx ping` command to check connectivity between a local +computer and an {IC} network provider. This command enables you to +verify that you can connect to a specific {IC} network and that the +remote network services are running. + +Note that you can only run this command from within the project +directory structure. For example, if your project name is `hello_world`, +your current working directory must be the `hello_world` top-level +project directory or one of its subdirectories. + +# Basic usage {#_basic_usage} + +``` bash +dfx ping [provider] [flag] +``` + +# Flags {#_flags} + +You can use the following optional flags with the `dfx ping` command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +# Arguments {#_arguments} + +You can specify the following argument for the `dfx ping` command. + ++----------------------+-----------------------------------------------+ +| Argument | Description | ++======================+===============================================+ +| provider | Specifies the network provider URL that you | +| | want to use. | ++----------------------+-----------------------------------------------+ + +# Examples {#_examples} + +You can use the `dfx ping` command to check whether the {IC} is +currently available at a specific network address by running a command +similar to the following: + +``` bash +dfx ping https://testgw.dfinity.network +``` + +If the {IC} is running on the specified network provider address, the +command returns output similar to the following: + + { + "ic_api_version": "0.8" + } diff --git a/modules/developers-guide/pages/cli-reference/dfx-replica.text b/modules/developers-guide/pages/cli-reference/dfx-replica.text new file mode 100644 index 000000000..9c82083ea --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-replica.text @@ -0,0 +1,51 @@ +--- +date: 2021-08-05 +title: dfx replica +--- + +Use the `dfx replica` command to start a {IC} replica process (without a +web server) locally. This command enables you to deploy canisters +locally to simulate network deployment and to test your programs during +development. + +Note that you can only run this command from within the project +directory structure. For example, if your project name is `hello_world`, +your current working directory must be the `hello_world` top-level +project directory or one of its subdirectories. + +# Basic usage {#_basic_usage} + +``` bash +dfx replica [option] [flag] +``` + +# Flags {#_flags} + +You can use the following optional flags with the `dfx replica` command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +# Options {#_options} + +You can use the following option with the `dfx replica` command. + ++----------------------+-----------------------------------------------+ +| Option | Description | ++======================+===============================================+ +| `--port port` | Specifies the port the local replica should | +| | listen to. | ++----------------------+-----------------------------------------------+ + +# Examples {#_examples} + +You can start the {IC} replica by running the following command: + +``` bash +dfx replica +``` diff --git a/modules/developers-guide/pages/cli-reference/dfx-start.text b/modules/developers-guide/pages/cli-reference/dfx-start.text new file mode 100644 index 000000000..894ff9404 --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-start.text @@ -0,0 +1,86 @@ +--- +date: 2021-08-05 +title: dfx start +--- + +Use the `dfx start` command to start a local {IC} replica process and +web server processes for the current project. This command enables you +to deploy canisters to the local {IC} network to test your programs +during development. + +Note that you can only run this command from within the project +directory structure. For example, if your project name is `hello_world`, +your current working directory must be the `hello_world` top-level +project directory or one of its subdirectories. + +# Basic usage {#_basic_usage} + +``` bash +dfx start [option] [flag] +``` + +# Flags {#_flags} + +You can use the following optional flags with the `dfx start` command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `--background` | Starts the {IC} replica and web server | +| | processes in the background and waits for a | +| | reply before returning to the shell. | ++----------------------+-----------------------------------------------+ +| `--clean` | Starts the {IC} replica and web server | +| | processes in a clean state by removing | +| | checkpoints from your project cache. You can | +| | use this flag to set your project cache to a | +| | new state when troubleshooting or debugging. | ++----------------------+-----------------------------------------------+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +# Options {#_options} + +You can use the following option with the `dfx start` command. + ++----------------------+-----------------------------------------------+ +| Option | Description | ++======================+===============================================+ +| `--host host` | Specifies the host interface IP address and | +| | port number to bind the frontend to. The | +| | default is `127.0.0.1:8000`. | ++----------------------+-----------------------------------------------+ + +# Examples {#_examples} + +You can start the {IC} replica and web server processes in the current +shell by running the following command: + +``` bash +dfx start +``` + +If you start the {IC} in the current shell, you need to open a new +terminal shell to run additional commands. Alternatively, you can start +the {IC} in the background by running the following command: + +``` bash +dfx start --background +``` + +If you run the {IC} in the background, however, be sure to stop the +network before uninstalling or reinstalling the `dfx` execution +environment by running the following command: + +``` bash +dfx stop +``` + +You can view the current process identifier (`pid`) for the {IC} process +started by `dfx` by running the following command: + +``` bash +more .dfx/pid +``` diff --git a/modules/developers-guide/pages/cli-reference/dfx-stop.text b/modules/developers-guide/pages/cli-reference/dfx-stop.text new file mode 100644 index 000000000..14c2e9ca9 --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-stop.text @@ -0,0 +1,63 @@ +--- +date: 2021-08-05 +title: dfx stop +--- + +Use the `dfx stop` command to stop the {IC} processes that you currently +have running on your local computer. In most cases, you run the {IC} +locally so that you can deploy canisters and test your programs during +development. To simulate an external {IC} connection, these processes +run continuously either in a terminal shell where you started them or +the in the background until you stop or kill them. + +Note that you can only run this command from within the project +directory structure. For example, if your project name is `hello_world`, +your current working directory must be the `hello_world` top-level +project directory or one of its subdirectories. + +# Basic usage {#_basic_usage} + +``` bash +dfx stop [flag] +``` + +# Flags {#_flags} + +You can use the following optional flags with the `dfx stop` command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +# Examples {#_examples} + +You can stop the {IC} network processes that are running in the +background by changing to a project directory then running the following +command: + +``` bash +dfx stop +``` + +If the local {IC} network is running in a current shell rather than in +the background, open a new terminal shell, change to a project +directory, then run the `dfx stop` command. + +The current process identifier (`pid`) for the {IC} process started by +`dfx` is recorded in the `.dfx/pid` file. You can view the process +identifier before running the `dfx stop` command by running the +following command: + +``` bash +more .dfx/pid +``` + +This command displays a process identifier similar to the following: + +``` bash +1896 +``` diff --git a/modules/developers-guide/pages/cli-reference/dfx-upgrade.text b/modules/developers-guide/pages/cli-reference/dfx-upgrade.text new file mode 100644 index 000000000..50e4792f9 --- /dev/null +++ b/modules/developers-guide/pages/cli-reference/dfx-upgrade.text @@ -0,0 +1,65 @@ +--- +date: 2021-08-05 +title: dfx upgrade +--- + +Use the `dfx upgrade` command to upgrade the {sdk-short-name} components +running on your local computer. This command checks the version of the +{sdk-short-name} that you have currently installed against the latest +publicly-available version specified in the `manifest.json` file. If an +older version of the {sdk-short-name} is detected locally, the +`dfx upgrade` command automatically fetches the latest version from the +CDN. + +# Basic usage {#_basic_usage} + +``` bash +dfx upgrade [flag] [option] +``` + +# Flags {#_flags} + +You can use the following optional flags with the `dfx upgrade` command. + ++----------------------+-----------------------------------------------+ +| Flag | Description | ++======================+===============================================+ +| `-h`, `--help` | Displays usage information. | ++----------------------+-----------------------------------------------+ +| `-V`, `--version` | Displays version information. | ++----------------------+-----------------------------------------------+ + +# Options {#_options} + +You can use the following option with the `dfx upgrade` command. + ++----------------------+-----------------------------------------------+ +| Option | Description | ++======================+===============================================+ +| `--curren | Specifies the version you want to identify as | +| t-version ` | the current version. This option enables you | +| | to override the version of the software | +| | currently identified as the latest version | +| | with the version you pass on the | +| | command-line. | ++----------------------+-----------------------------------------------+ + +# Examples {#_examples} + +You can upgrade the version of the {sdk-short-name} that you have +currently installed by running the following command: + +``` bash +dfx upgrade +``` + +This command checks the version of `dfx` you have currently installed +and the latest version available published on the {sdk-short-name} +website in a manifest file. If a newer version of `dfx` is available, +the command automatically downloads and installs the latest version. + +``` bash +Current version: 0.6.8 +Fetching manifest \https://sdk.dfinity.org/manifest.json +Already up to date +``` diff --git a/modules/developers-guide/pages/computation-and-storage-costs.text b/modules/developers-guide/pages/computation-and-storage-costs.text new file mode 100644 index 000000000..fca145544 --- /dev/null +++ b/modules/developers-guide/pages/computation-and-storage-costs.text @@ -0,0 +1,135 @@ +--- +date: 2021-08-05 +title: Computation and Storage Costs +--- + +The Internet Computer requires computation operations and storage to be +supported by cycles. Cycles are generated from the conversion of +Internet Computer (ICP) utility tokens. + +# The Role of the Network Nervous System (NNS) in Defining Costs {#_the_role_of_the_network_nervous_system_nns_in_defining_costs} + +The Internet Computer is a decentralized public utility, controlled by +the NNS ---- the network's open, algorithmic governance system. The NNS +fundamentally controls how many cycles are required for low-level +computation actions for computation and storage. The number of cycles +needed for individual computations will vary based on a number of +factors considered by the NNS, including proposals from the community. + +# Details: Cost of Compute and Storage Transactions on the Internet Computer {#_details_cost_of_compute_and_storage_transactions_on_the_internet_computer} + +See below for details on the cost of compute and storage transactions on +the Internet Computer as of July 26, 2021. + ++----------------------+----------------------+-----------------------+ +| Transaction | Description | All Application | +| | | Subnets | ++======================+======================+=======================+ +| Canister Created | For creating | 100,000,000,000 | +| | canisters on a | | +| | subnet | | ++----------------------+----------------------+-----------------------+ +| Compute Percent | For each percent of | 100,000 | +| Allocated Per Second | the reserved compute | | +| | allocation (a scarce | | +| | resource). | | ++----------------------+----------------------+-----------------------+ +| Update Message | For every update | 590,000 | +| Execution | message executed | | ++----------------------+----------------------+-----------------------+ +| Ten Update | For every 10 | 4 | +| Instructions | instructions | | +| Execution | executed when | | +| | executing update | | +| | type messages | | ++----------------------+----------------------+-----------------------+ +| Xnet Call | For every | 260,000 | +| | inter-canister call | | +| | performed (includes | | +| | the cost for sending | | +| | the request and | | +| | receiving the | | +| | response) | | ++----------------------+----------------------+-----------------------+ +| Xnet Byte | For every byte sent | 1,000 | +| Transmission | in an inter-canister | | +| | call (for bytes sent | | +| | in the request and | | +| | response) | | ++----------------------+----------------------+-----------------------+ +| Ingress Message | For every ingress | 1,200,000 | +| Reception | message received | | ++----------------------+----------------------+-----------------------+ +| Ingress Byte | For every byte | 2,000 | +| Reception | received in an | | +| | ingress message | | ++----------------------+----------------------+-----------------------+ +| GB Storage Per | For storing a GB of | 127,000 | +| Second | data per second | | ++----------------------+----------------------+-----------------------+ + +: Cycles Cost per Transaction (as of July 26, 2021) + +The \$USD cost for transactions below is based on the above cycle costs. +1 XDR is equal to 1 Trillion cycles. As of July 26, 2021, the exchange +rate for 1 XDR = \$1.42. The exchange rate for USD \<\> XDR may vary and +it will impact the conversion rate. For XDR exchange rates please visit: + + +To derive the estimated GB Storage per month, we assume a 30 day month. + ++----------------------+----------------------+-----------------------+ +| Transaction | Description | All Application | +| | | Subnets | ++======================+======================+=======================+ +| Canister Created | For creating | \$0.142 | +| | canisters on a | | +| | subnet | | ++----------------------+----------------------+-----------------------+ +| Compute Percent | For each percent of | \$0.000000142 | +| Allocated Per Second | the reserved compute | | +| | allocation (a scarce | | +| | resource). | | ++----------------------+----------------------+-----------------------+ +| Update Message | For every update | \$0.0000008378 | +| Execution | message executed | | ++----------------------+----------------------+-----------------------+ +| Ten Update | For every 10 | \$0.00000000000568 | +| Instructions | instructions | | +| Execution | executed when | | +| | executing update | | +| | type messages | | ++----------------------+----------------------+-----------------------+ +| Xnet Call | For every | \$0.0000003692 | +| | inter-canister call | | +| | performed (includes | | +| | the cost for sending | | +| | the request and | | +| | receiving the | | +| | response) | | ++----------------------+----------------------+-----------------------+ +| Xnet Byte | For every byte sent | \$0.00000000142 | +| Transmission | in an inter-canister | | +| | call (for bytes sent | | +| | in the request and | | +| | response) | | ++----------------------+----------------------+-----------------------+ +| Ingress Message | For every ingress | \$0.000001704 | +| Reception | message received | | ++----------------------+----------------------+-----------------------+ +| Ingress Byte | For every byte | \$0.00000000284 | +| Reception | received in an | | +| | ingress message | | ++----------------------+----------------------+-----------------------+ +| GB Storage Per | For storing a GB of | \$0.00000018034 | +| Second | data per second | | ++----------------------+----------------------+-----------------------+ + +: Cost per Transaction in \$USD (as of July 26, 2021) + +Assuming a 30 day month ---  + ++----------------------+----------------------+-----------------------+ +| GB Storage Per Month | For storing a GB of | \$0.467 | +| | data per month | | ++----------------------+----------------------+-----------------------+ diff --git a/modules/developers-guide/pages/concepts/canisters-code.text b/modules/developers-guide/pages/concepts/canisters-code.text new file mode 100644 index 000000000..1585c9527 --- /dev/null +++ b/modules/developers-guide/pages/concepts/canisters-code.text @@ -0,0 +1,245 @@ +--- +date: 2021-08-05 +title: Canisters and code +--- + +One of the most important principles to keep in mind is that the +Internet Computer is primarily a distributed and decentralized platform +for running software. + +When you write source code for an application that runs on the Internet +Computer, you compile the source code into a **WebAssembly module**. +When you deploy the WebAssembly module that contains your program on an +Internet Computer replica, the program is executed inside of a +conceptual computational unit called a software **canister**. + +Once deployed, end-users can interact with the software canister by +accessing the entry point functions you have defined for that canister +through a front-end client such as a browser. + +# Canisters include both program and state {#canister-state} + +A software canister is similar to a container in that both are deployed +as a software unit that contains compiled code and dependencies for an +application or service. + +Containerization allows for applications to be decoupled from the +environment, allowing for easy and reliable deployment. The canister +differs from a container, however, in that it also stores information +about the current software **state** with a record of preceding events +and user interactions. + +While a containerized application might include information about the +state of the environment in which the application runs, a software +canister is able to persist a record of state changes that resulted from +an application's functions being used. + +# Query and update methods {#query-update} + +This concept of a canister consisting of both program and state is an +important one because when a canister function is invoked by sending a +message to one of its entry points, there are only two types of calls: +non-committing **query calls** and committing **update calls**. + ++----------+-----------------------------------------------------------+ +| Type | Key points to remember | ++==========+===========================================================+ +| Query | Allow the user to query the current state of a canister | +| calls | or call a function that operates on the canister's state | +| | **without changing it**. | +| | | +| | - Are synchronous and answered immediately. | +| | | +| | - Can be made to any node that holds the canister and | +| | do not require consensus to verify the result. There | +| | is an inherent tradeoff between security and | +| | performance because the reply from a single node | +| | might be untrustworthy or inaccurate. | +| | | +| | - Do not allow changes to the state of the canister to | +| | be persisted. Essentially, programs use query calls | +| | to perform read-only operations. | +| | | +| | - Do not allow the called canister to invoke functions | +| | exposed by other canisters as inter-canister calls. | +| | (Note that this restriction is temporary and that | +| | canisters will be able to invoke functions exposed by | +| | other canisters when processing query calls in the | +| | future.) | ++----------+-----------------------------------------------------------+ +| Update | Allow the user to change the state of the canister and | +| calls | have **changes persisted**. | +| | | +| | - Are answered asynchronously. | +| | | +| | - Must pass through consensus to return the result. | +| | Because consensus is required, changing the state of | +| | a canister can take time. Therefore, update calls use | +| | the actor-based programming model (with state | +| | isolation) to allow concurrent and asynchronous | +| | processing. There is an inherent tradeoff between | +| | security and performance because two-thirds of the | +| | replicas in a subnet must agree on the result. | +| | | +| | - The called canister can invoke functions exposed by | +| | other canisters | ++----------+-----------------------------------------------------------+ + +As a developer, it is important to recognize this relationship between +the calls that query the canister and the calls that change the canister +state. In particular, you should keep in mind the inherent tradeoff +between security and performance. + +# How to develop applications for the Internet Computer {#dev-motoko-intro} + +For programmers and software developers, the {platform} provides unique +capabilities and opportunities within a framework that simplifies how +you can design, build, and deploy applications. A key part of this +framework is a new, general purpose programming language, Motoko. Motoko +is a programming language that has been specifically designed to take +full advantage of the unique features that the Internet Computer +provides, including: + +- The ability to define programs directly using `actor` objects and + classes. + +- The use of `async` and `await` syntax to enable programming + asynchronous messaging as if it was synchronous processing. + +- Automatic support for message serialization and deserialization. + +- The ability to leverage orthogonal persistence using data structures + without external databases or storage volumes. + +As a modern, high-level programming language, Motoko provides some key +features of its own, including: + +- Support for big integer operations and overflow protection. + +- A sound type system that statically checks each program to ensure it + can execute without type errors on all possible inputs. + +- Support for function abstractions, user-defined type definitions, + and user-defined actors. + +For more detailed information about the Motoko programming language +itself, including syntactical conventions and supported features, see +the [*Motoko Programming Language +Guide*](../../language-guide/motoko.xml). + +The following diagram provides a simplified drill-down view of the +development environment as part of the Internet Computer ecosystem. + +![Your development environment as part of the Internet Computer +ecosystem](SDK-protocol-network.svg) + +# Canisters, actors, and the code you produce {#actor-intro} + +One of the most important principles to keep in mind when preparing to +write programs using the Motoko programming language is that Motoko uses +an *actor-based* programming model. + +An *actor* is a special kind of object that processes messages in an +isolated state, enabling messages to be handled remotely and +asynchronously. Many key features of the {platform} depend on this type +of secure and efficient asynchronous message handling. + +In general, each software canister includes the compiled code for one +actor object. Each canister also includes some additional information +such as interface descriptions or front-end assets. You can create +projects that include multiple canisters, but each canister can only +include one actor. + +# Why your code is compiled into WebAssembly {#wasm-intro} + +When you compile Motoko code, the result is a WebAssembly module. +WebAssembly is a low-level computer instruction format that is portable +and abstracts program execution cleanly over most modern computer +hardware. It is broadly supported for programs that run on the internet +and a natural fit for deploying applications that are intended to run on +the {platform}. + +With Motoko, developers can compile to portable WebAssembly while still +delivering secure applications using a simple and high-level language. + +The Motoko language offers many of the features that are common to other +higher-level modern languages---like type safety and pattern-matching. +In addition, Motoko provides built-in support for defining messaging +services using actors in a way that is especially well-suited to the +{platform} and is easy to learn whether you are a new or experienced +programmer. + +This guide provides an introduction to the basic features of the Motoko +programming language in the context of writing programs using the SDK. +For more detailed information about the Motoko programming language +itself, see the [*Motoko Programming Language +Guide*](../../language-guide/motoko.xml). + +# Identities and authentication {#auth-intro} + +One of the main differences between a user-initiated canister operation +and a canister-to-canister operation is that canisters have an +explicitly registered identity on the \[IC\]. + +There is no central registry for user principals. Instead, user +identifiers are associated specifically with the canisters each user +accesses through one or more public-private key pairs. The user's +private key is used to sign messages, which are sent along with their +public key to a canister. The \[IC\] authenticates the user and passes +the principal to the canister for the authorization of their operation. + +At a high level, first-time users generate an unsigned key pair and +derive their principal identifier from the public key during their first +interaction with the Internet Computer. Returning users are +authenticated using the private key (or keys) that have been stored +securely by the user agent. Users with access to multiple canisters can +manage the keys and devices used for authentication associated with each +canister. + +A single user can have multiple public-private key pairs for accessing +canisters from different devices---such as browsers running on different +computers, mobile phones, or tablets---but these derived keys all map to +a primary identifier. + +# Resource consumption and cycles {#resource-intro} + +In general, all canisters consume resources in the form of CPU cycles +for execution, bandwidth for routing messages, and memory for persisted +data. Canisters maintain an account balance of **cycles** to pay for the +cost of communication, computation, and storage that their applications +consume. + +Cycles are intended to reflect the real cost of operations including +physical hardware, rack space, energy, storage devices, and bandwidth in +a stable or deflationary way so that the cost of program execution +remains the same or decreases with operational efficiency. + +- Programs must be able to pay for complete execution (all or + nothing), but the cost associated with a unit of cycles will make + efficient programs cost-effective. + +- By setting limits on how many cycles a canister can consume, the + platform can prevent malicious code from draining resources. + +The relative stability of operational costs makes it easier to predict +the cycles required to process, for example, a million messages. + +The cycles available for program execution are held in a **wallet +canister**. For local deployment, wallet canisters are automatically +created and issued cycles. To deploy your application on the Internet +Computer running on external nodes and subnets, however, you'll need a +principal with a cycles wallet to manage canister operations. + +# Want to learn more? {#_want_to_learn_more} + +If you are looking for more information about canisters, check out the +following related resources: + +- [Introducing Canisters --- An Evolution of Smart Contracts + (video)](https://www.youtube.com/watch?v=LKpGuBOXxtQ) + +- [What is the DFINITY Canister SDK? + (video)](https://www.youtube.com/watch?v=60uHQfoA8Dk) + +- [Deploying your first application + (video)](https://www.youtube.com/watch?v=yqIoiyuGYNA) diff --git a/modules/developers-guide/pages/concepts/concepts-intro.text b/modules/developers-guide/pages/concepts/concepts-intro.text new file mode 100644 index 000000000..3740ed502 --- /dev/null +++ b/modules/developers-guide/pages/concepts/concepts-intro.text @@ -0,0 +1,37 @@ +--- +date: 2021-08-05 +title: Concepts +--- + +You don't need to know much about the inner workings of the {platform} +to write programs that run successfully on it. However, learning a few +key concepts will help you get the most out of the unique features that +the Internet Computer provides. + +Knowing a little about the design and architecture of the {platform} can +make it easier for you to realize the benefits that align with your +goals and inform the types of applications you develop. + +The topics in this section introduce key components and terminology to +help you understand the architecture and operation of the Internet +Computer. + +If you want to get right to developing code, though, you can skip this +introductory material---key concepts and terminology---and look them up +later when you need them either in this section or in the +[glossary](../glossary.xml). + +If you are looking for more introductory information, check out the +following related resources: + +- [Overview of the Internet Computer + (video)](https://www.youtube.com/watch?v=XgsOKP224Zw) + +- [Building on the Internet Computer: Fundamentals + (video)](https://www.youtube.com/watch?v=jduSMHxdYD8) + +- [Introducing Canisters --- An Evolution of Smart Contracts + (video)](https://www.youtube.com/watch?v=LKpGuBOXxtQ) + +- [Frequently Asked Questions (video and short + articles)](https://dfinity.org/faq/) diff --git a/modules/developers-guide/pages/concepts/data-centers.text b/modules/developers-guide/pages/concepts/data-centers.text new file mode 100644 index 000000000..de36dfb39 --- /dev/null +++ b/modules/developers-guide/pages/concepts/data-centers.text @@ -0,0 +1,71 @@ +--- +date: 2021-08-05 +title: Decentralized data centers +--- + +The Internet Computer is not physical hardware that exists in any +physical location. Instead, the Internet Computer combines computing +resources provided by independently-operated data centers around the +world. + +Unlike a public or private cloud, the Internet Computer is not owned and +operated by a single private company. Instead, the Internet Computer is +a public utility with updates and operations that are managed through an +algorithmic, decentralized governance system defined in the protocol. +Its architecture enables multiple computers to operate like one, very +powerful, virtual machine. + +The computers that make up the virtual machine are organized into +sub-networks of data centers around the globe. The distributed +architecture enables secure communication without firewalls or +technologies that are vulnerable to attack. Independent data centers +receive remuneration for contributing computing capacity and hosting +services to support applications running on the {platform}. + +# Subnets and data centers {#_subnets_and_data_centers} + +To provide a truly decentralized blockchain that can withstand potential +service disruptions, the physical nodes that make up any given subnet +are distributed across data centers in diverse locations. The nodes +themselves might be owned or provided by different parties in +partnership or unaffiliated with the data center location where they +operate. + +The following diagram provides a simplified view of a subnet with nodes +in four data centers. + +![data center simplified](data-center-simplified.svg) + +In this simplified scenario: + +- There are four geographically-independent data centers. + +- Each data center has hardware supplied by multiple node providers. + +- Any single node provider might have equipment in multiple data + centers. + +Although this example represents one subnet with nodes in multiple data +centers, any of the nodes could be moved out of this subnet to form a +new subnet, if needed. Changes to the network topology are managed +through the Internet Computer governance system called the **Network +Nervous System** (NNS). + +# Node providers and data center operators {#_node_providers_and_data_center_operators} + +In most cases, node providers---or the data center operators they +partner with---are responsible for monitoring and maintaining the +compute capacity of the equipment on which the Internet Computer runs. +For example, node providers or data center operators might need to +repair or replace equipment if there's a hardware failure or if a system +under-performs. Network operations and upgrades, however, are monitored +and managed through the decentralized governance system, the Network +Nervous System (NNS). + +# Want to learn more? {#_want_to_learn_more} + +If you are looking for more information about data center operations and +node providers, check out the following related resources: + +- [Internet Computer Help Center for Node Providers (FAQ and + articles)](https://internetcomputer.zendesk.com/hc/en-us/categories/360005114372-Node-Provider) diff --git a/modules/developers-guide/pages/concepts/governance.text b/modules/developers-guide/pages/concepts/governance.text new file mode 100644 index 000000000..8377f0374 --- /dev/null +++ b/modules/developers-guide/pages/concepts/governance.text @@ -0,0 +1,41 @@ +--- +date: 2021-08-05 +title: Neurons and governance +--- + +As a decentralized platform, all changes to the configuration and +behavior of the Internet Computer are controlled by a governance body +called the Network Nervous System (NNS). The NNS controls many aspects +of the Internet Computer platform including the following: + +- which data center providers participate in the network + +- the number, location, and ownership of the nodes accepted from a + data center provider + +- assignment of nodes to subnets + +- whether upgrades to smart contract canister software or management + services are allowed or not + +In addition, only members of the governance body can vote to approve or +deny requests to upgrade Internet Computer replicas or modify the +Internet Computer protocol. + +# Voting rights for stakeholders {#_voting_rights_for_stakeholders} + +Because tokens on the Internet Computer are generally liquid, they do +not represent a stable enough commitment on the part of their holders +for them to be used for governance purposes. To provide the stability +required for responsible governance, tokens can be converted to +**neurons**. A neuron represents a number of ICP tokens that cannot be +exchanged for a minimum period of time (the lock-up period). + +When a person or organization has some number of ICP tokens locked up in +a neuron, the neuron holder has the right to vote on governance issues, +and to be paid for voting in proportion to the number of ICP locked up +and the length of the lock-up period. + +The Internet Computer tracks the number of ICP tokens that are locked up +in neurons and provides the logic necessary for voting in conjunction +with managing ICP token account balances. diff --git a/modules/developers-guide/pages/concepts/nodes-subnets.text b/modules/developers-guide/pages/concepts/nodes-subnets.text new file mode 100644 index 000000000..e35ef1b03 --- /dev/null +++ b/modules/developers-guide/pages/concepts/nodes-subnets.text @@ -0,0 +1,51 @@ +--- +date: 2021-08-05 +title: Nodes and subnet blockchains +--- + +Internet Computer **subnet blockchains** provide physical hardware and +resources---like CPU and memory---for performing software operations. +Each subnet is a blockchain that consists of some number of individual +machines---connected peer computers called **nodes**---that run the +software components of the Internet Computer protocol. + +The Internet Computer software components that run on each node are +called a **replica** because they replicate state and computation across +all of the nodes in a subnet blockchain. + +The core components of a replica are organized into the following +logical layers: + +- A **peer-to-peer** (P2P) networking layer that collects and + advertises messages from users, from other nodes in its subnet + blockchain, and from other sub-networks. Messages received by the + peer-to-peer layer are replicated to all of the nodes in the subnet + to ensure the security, reliability, and resiliency of the platform. + +- A **consensus** layer that selects and sequences messages received + from users and from different subnets to create input blocks that + can be notarized and finalized before being delivered to the message + routing layer. + +- A **message routing** layer that routes user- and system-generated + messages between subnets, manages the input and output queues for + applications, and schedules messages for execution. + +- An **execution environment** that calculates the deterministic + computation involved in executing a program and processes the + messages it receives from the message routing layer. + +The following diagram provides a simplified overview of the Internet +Computer protocol components deployed as a local replica in a +development environment. + +![Internet Computer components in a developer's +environment](SDK-protocol-local-overview.svg) + +As a developer, it isn't necessary to know the details about how your +applications and user interactions with your applications are routed +through the Internet Computer architecture or replicated on the network. +However, a general understanding of the key components can be useful +because the development environment includes the replica components to +provide a local test network for deployment and a realistic sense of the +workflow for a production deployment. diff --git a/modules/developers-guide/pages/concepts/tokens-cycles.text b/modules/developers-guide/pages/concepts/tokens-cycles.text new file mode 100644 index 000000000..8fd823f07 --- /dev/null +++ b/modules/developers-guide/pages/concepts/tokens-cycles.text @@ -0,0 +1,139 @@ +--- +date: 2021-08-05 +title: Tokens and cycles +--- + +Within the Internet Computer ecosystem, Internet Computer Protocol +tokens (ICP tokens) are a native utility token with a value determined +on the open market. ICP tokens play a key role in both the governance +and economics of the Internet Computer. + +# How you can get ICP tokens {#get-cycles} + +As a utility token for the Internet Computer, there are a few different +ways you might acquire ICP tokens. For example, you might: + +- Purchase ICP tokens directly through an exchange that lists ICP + tokens available for trade. + +- Claim tokens as a result of your investment. + +- Receive a grant of tokens through the Internet Computer Association + (ICA) or the DFINITY Foundation. + +- Receive tokens as remuneration for providing computing capacity as a + node provider or data center. + +# How you can use ICP tokens {#using-cycles} + +If you have ICP tokens, but aren't sure how to use them, the following +diagram provides a simplified overview to illustrate the three most +common scenarios. + +![icp tokens how to use](icp-tokens-how-to-use.svg) + +As this diagram suggests, how you use ICP tokens depends primarily on +your goals in acquiring them. For example, if you are a developer or +entrepreneur, ICP tokens can be converted to **cycles**. Cycles can then +be used to build and deploy applications to deliver products and +services to the market. If you are a member of the community interested +in participating in governance and influencing the the direction of the +Internet Computer, you can lock up ICP tokens in a stake---called a +neuron---so that you can submit and vote on proposals. + +# How cycles work + +For developers, ICP tokens are important because they can be converted +to cycles that, in turn, are used to pay for computation and resource +consumption. + +As an example, imagine you have a house where propane is used for a +water heater, kitchen stove, dryer, and space heater. As you use these +appliances, you deplete the supply of gas you have on hand, so +periodically you contact a provider to refill your supply so you can +continue to use your appliances without interruption. This is similar to +smart contract canisters in that each canister must have an account with +cycles available to pay for the communication, computation, and storage +that the canister's application consumes. + +Internet Computer Protocol token holders can exchange tokens when they +need to replenish the cycles available in each canister's account. + +# Cost of computation {#cost-of-compute} + +- Cycles reflect the real costs of operations for applications hosted + in the Internet Computer platform including resources such physical + hardware, rack space, energy, storage devices, and bandwidth. + +- In simple terms, cycles represent the cost of executing each + application's WebAssembly instructions. + +- Programs must be able to pay for complete execution (all or + nothing), but the platform sets limits on how many cycles a canister + can hold and consume to prevent malicious code from draining + resources. + +- The relative stability of operational costs makes it easier to + predict the cycles required to process, for example, a million + messages. + +- The costs associated with communication, computation, and storage + are more likely to decrease than to increase over time---for + example, because disk space becomes cheaper or hardware more + efficient. + +- Although Internet Computer Protocol tokens can be used to add cycles + to canisters, cycles themselves are not currency and have no + liquidity or value as an asset. + +- Cycles cannot be converted back to value in the form of Internet + Computer Protocol tokens, but they can be transferred between + canisters to enable canisters to pay for operations. + +# Token value and volatility {#volatility} + +- Tokens reflect the value of the Internet Computer and can fluctuate. + To prevent the token value from affecting the number of messages a + canister can process, tokens are not used to pay for resources + directly. + +- Tokens can be exchanged between token holders or locked up in + **neurons** to secure voting rights as part of the platform + governance system. + +- Tokens are used to reward data centers for providing compute + capacity and platform stakeholders for participating in secure + operation of the Internet Computer by voting on proposals submitted + to the governance system. + +# Payment to data centers and node providers {#data-centers} + +With this model, the Internet Computer platform provides data center +providers with a predictable economic model for computing power capacity +to ensure resources are available when and where they are needed. Data +center providers receive compensation for both active and spare nodes so +that the Internet Computer has capacity to handle both normal traffic +and workload spikes. + +If the Internet Computer network requires additional capacity, it can +request bids from potential data center providers. If a bid is accepted, +a data center provider might be contracted to provide a given number of +servers with an acceptable level of service availability for a specific +period of time. For example, a data center provider might be contracted +to provide ten servers with 99% uptime for 30 days. Even if those nodes +do not host any canisters and are only used as spare nodes, the data +center provider receives compensation for availability as part of the +network. + +The Internet Computer economic model places much of the power and +responsibility of managing capacity on the governance system---the +Network Nervous System. Specific details about compensation and service +level requirements are outside the scope of this document. + +# Want to learn more? {#_want_to_learn_more} + +If you are looking for more information about tokens and cycles, check +out the following related resources: + +- [Overview of Token Economics + (video)](https://www.youtube.com/watch?v=H2p5q0PR2pc) diff --git a/modules/developers-guide/pages/concepts/what-is-IC.text b/modules/developers-guide/pages/concepts/what-is-IC.text new file mode 100644 index 000000000..98c59935a --- /dev/null +++ b/modules/developers-guide/pages/concepts/what-is-IC.text @@ -0,0 +1,78 @@ +--- +date: 2021-08-05 +title: What is the Internet Computer? +--- + +The **Internet Computer** is a blockchain that enables developers, +organizations, and entrepreneurs to build and deploy secure, autonomous, +and tamper-proof software programs. + +As an application developer, you might find it useful to think of the +Internet Computer as providing the following key elements: + +- An **open communication protocol** that enables general-purpose + computations to run transparently directly on the internet + +- A **network** that runs the protocol to provide computing + capacity---for example, the hardware, CPU, and memory required to + run programs---through **independent data centers**. + +- A **globally-accessible and scalable blockchain platform** for + running software applications. + +# Open blockchain platform {#_open_blockchain_platform} + +The Internet Computer is not physical hardware that exists in any +physical location. Instead, the Internet Computer combines computing +resources provided by independent data centers around the world to give +users and organizations secure access to applications and transaction +processing services. + +The {platform} enables multiple computers to operate like one, very +powerful, virtual machine. The computers that make up the virtual +machine are organized into sub-networks---subnet blockchains---with data +centers around the world. The distributed architecture enables secure +communication without firewalls or technologies that are vulnerable to +attack. Independent data centers receive remuneration for contributing +computing capacity and hosting services to support applications running +on the {platform}. + +# Building the next generation of software and services {#next-gen} + +The Internet Computer protocol reduces platform-based risks and paves +the way for innovation by re-imagining how software is built, deployed, +and accessed. + +For example, with the Internet Computer, developers can focus on writing +code using smart contracts without environment-related distractions such +as: + +- physical or virtual network configuration requirements + +- load balancing services + +- firewalls, network topology, or port management + +- database configuration and maintenance + +- storage volumes and devices + +By enabling developers to focus on building applications and delivering +value, the Internet Computer helps simplify the development process, +reduce time to market, and foster innovation. + +For end-users, the Internet Computer provides a secure environment for +accessing applications with fewer risks. Because of the inherent +security of the blockchain, programs running on the Internet Computer +cannot be hijacked by malicious code, which also reduces the total cost +of ownership for both application end-users or organizations. + +In addition, because software services can be \"autonomous\" and public, +developers can write services that communicate with each other and share +functions in ways that increase productivity and efficiency while +leaving room to innovate and improve projects with confidence. + +The Internet Computer also enables developers to use +cryptographically-secure identities to enforce access controls, reducing +the need to rely on user names and passwords or external identity +management plug-ins. diff --git a/modules/developers-guide/pages/customize-projects.text b/modules/developers-guide/pages/customize-projects.text new file mode 100644 index 000000000..567dd3695 --- /dev/null +++ b/modules/developers-guide/pages/customize-projects.text @@ -0,0 +1,98 @@ +--- +date: 2021-08-05 +title: Manage projects +--- + +You can modify some key settings for individual projects by modifying +each project's `dfx.json` configuration file. You can use the +`dfx config` command to change these settings programmatically or +manually edit the `dfx.json` file directly. + +# How to change your source directory {#_how_to_change_your_source_directory} + +Before you compile source code for your project using the `dfx build` +command, you might want to check the default location for storing the +source code for your program. By default, the name you use to create a +new project is the name used for one data smart contract canister +(`canister_name`) and one assets canister (`canister_name_assets`), and +program source code is expected to be in the `src/canister_name` +directory. Similarly, the default location for front-end source code is +in the `src/canister_name_assets/src` directory and front-end output is +located in the `dist/canister_name_assets` directory. + +Depending on your application's complexity and architecture, however, +you might want to modify the default location for the program source +code, the front-end source code, or front-end output. + +For example, for a simple program, you might want to eliminate one +directory level and place the source code in the `src` directory: + +``` text + "main": "src/main.mo", +``` + +For more complex applications, you might want to use a multi-tiered +directory structure: + +``` text +"canisters": { + "profiles": { + "main": "src/profiles/utils/main.mo" + }, + "events": { + "main": "src/events/calendar/main.mo" + }, + "media": { + "main": "src/events/reports/main.mo" + } +} +``` + +::: note +If you modify the default settings for a source code directory, be sure +that the settings in the `dfx.json` configuration file match the +directory location on the file system. +::: + +# How to change the main program file name {#_how_to_change_the_main_program_file_name} + +Before you compile source code for your project using the `dfx build` +command, you should verify the location and file name used for your +program's source code. + +For example, if you want to build a smart contract canister for the +`factorial` program and the source code for the program is located in +`src/math/factorial.mo`, you should be sure that you have the correct +path specified for the `main` setting in the `canisters` section of the +configuration file. + +For example: + +``` json +"main": "src/math/factorial.mo", +``` + +Keep in mind that changing the configuration setting for the program +file name only affects where the `dfx build` command looks for the +source code to compile. Making changes in the configuration file does +not rename any files or directories on the file system. If you change +the path to the main program file or the name of the file itself, be +sure to change the name and location within your project directory. + +# How to change the location for serving the application front-end {#_how_to_change_the_location_for_serving_the_application_front_end} + +You can change the default host name and port number for serving the +application front-end by modifying the local network settings in the +`dfx.json` configuration file. + +For example, you can change the IP address for the local network by +modifying the `bind` setting: + +``` json +"networks": { + "local": { + "bind": "192.168.47.1:8000", + "type": "ephemeral" + } +} +``` diff --git a/modules/developers-guide/pages/default-wallet.text b/modules/developers-guide/pages/default-wallet.text new file mode 100644 index 000000000..714b00fbb --- /dev/null +++ b/modules/developers-guide/pages/default-wallet.text @@ -0,0 +1,579 @@ +--- +date: 2021-08-05 +title: Use the default cycles wallet +--- + +As discussed in [Tokens and cycles](concepts/tokens-cycles.xml), ICP +tokens can be converted into **cycles** to power canister operations. +Cycles provide a largely stable value proposition and represent the +operational cost of communication, computation, and storage that +applications consume. For example, cycles reflect the actual cost of +physical hardware, rack space, energy, storage devices, and network +bandwidth required by applications running on the Internet Computer. + +Unlike ICP tokens, cycles are only associated with canisters and not +user or developer principals. Because only canisters require and consume +cycles---to perform operations and to pay for the resources they +use---users and developers manage the distribution and ownership of +cycles through a special type of canister called a **cycles wallet**. +Because the cycles wallet holds the cycles required to perform +operations such as creating new canisters, these operations are executed +by default using the canister identifier for the cycles wallet instead +of your user principal. + +For the purposes of local development, the {sdk-short-name} +automatically creates a default cycles wallet for you in every project +and most of the operations performed using the cycles wallet happen +behind the scenes. For example, the cycles wallet acts on your behalf to +register canister identifiers and deploy canisters on the local network. + +In a production environment, however, you often need to explicitly +register and transfer cycles to new canisters, specify the principals +that can act as custodians, and manage the principals with ownership +rights. You can perform some of these tasks using the default cycles +wallet application running in a web browser. Depending on the specific +action you want to take, you can also perform these cycle and canister +management tasks by running `dfx wallet` commands in a terminal or by +calling methods in the default cycles wallet canister directly. + +You should keep in mind, however, that calls to the cycles wallet +canister are executed using the cycles wallet identifier associated with +the currently-selected user identity. Depending on your +currently-selected identity and whether the principal associated with +that identity has been added as a controller or a custodian for a +wallet, you might see different results or be denied access to a +specific method. + +To check the identity you are currently using, run the following +command: + +``` bash +dfx identity whoami +``` + +# Controller and custodian roles {#_controller_and_custodian_roles} + +A user principal or canister identifier can be assigned to a +**controller** or **custodian** role. + +A **controller** is the most privileged role and a principal assigned to +the controller role can perform privileged tasks including the +following: + +- Add and remove other principals as controllers. + +- Authorize and de-authorize other principals as custodians. + +- Add entries to the cycles wallet address book. + +- Access the cycles wallet balance and all other wallet-related + information. + +- Send cycles to other canisters. + +- Receive cycles from other canisters. + +- Act as the \"message-caller\" principal in calls to other canisters. + +- Create canisters and additional cycles wallets. + +- Rename the cycles wallet. + +A principal assigned to the **custodian** role can only perform a subset +of cycles wallet management tasks, including the following: + +- Access the cycles wallet balance and all other wallet-related + information. + +- Send cycles to other canisters. + +- Receive cycles from other canisters. + +- Act as the \"message-caller\" principal in calls to other canisters. + +- Create canisters. + +::: note +Authorizing a principal as a custodian does not automatically grant the +principal access to a cycles wallet. The identity assigned to the +custodian role must also be assigned a cycles wallet canister +identifier. For example, if you authorize the identity `alice_custodian` +as a custodian of a cycles wallet (`rwlgt-iiaaa-aaaaa-aaaaa-cai`) in a +local project, that user would also need to be assigned to use that +wallet with the `dfx identity set-wallet rwlgt-iiaaa-aaaaa-aaaaa-cai` +command. +::: + +# Check the cycle balance {#wallet-check-balance} + +If you are doing local development, your cycles wallet is created when +you register a new canister identifier using `dfx canister create` or +when you register, build, and deploy a canister with `dfx deploy`. + +If you are deploying on the Internet Computer, you typically create your +cycles wallet by converting ICP tokens to cycles, transferring the +cycles to a new canister identifier, and updating the canister with the +default cycles wallet WebAssembly module (WASM). + +After you have a cycles wallet on the local or remote network, you can +use the `dfx wallet balance` command or the `wallet_balance` method to +check the current cycle balance. + +## Check you cycles balance when developing locally {#_check_you_cycles_balance_when_developing_locally} + +If you are doing local development, you can use the `dfx wallet balance` +command to check the current cycles balance on a project-by-project +basis. + +To check the cycles balance in a local project: + +1. Open a terminal and navigate to the root directory of the project. + +2. Start the Internet Computer locally by running the following + command: + + ``` bash + dfx start --background + ``` + +3. Display the cycles balance from the cycles wallet associated with + the currently-selected identity by running the following command: + + ``` bash + dfx wallet balance + ``` + + The command displays output similar to the following: + + 78000000000000 cycles. + +## Check the cycles balance on the Internet Computer {#_check_the_cycles_balance_on_the_internet_computer} + +If you have deployed a cycles wallet on the Internet Computer main +network, you can use the `dfx wallet balance` command to check the +current cycles balance on the network. + +To check the cycles balance on the Internet Computer: + +1. Open a terminal and navigate to a directory that contains a + `dfx.json` configuration file. + +2. Check your connection to the Internet Computer by running the + following command: + + ``` bash + dfx ping ic + ``` + +3. Display the cycle balance from the cycles wallet associated with the + currently-selected identity by running the following command: + + ``` bash + dfx wallet --network ic balance + ``` + + The command displays output similar to the following: + + 67991783875995 cycles. + +## Call the cycles wallet_balance method {#_call_the_cycles_wallet_balance_method} + +You can also check the cycles balance by calling the `wallet_balance` +method in the cycles wallet canister directly. For example, if your +principal is a controller for the `h5aet-waaaa-aaaab-qaamq-cai` cycles +wallet, you can check the current cycle balance by running the following +command: + + dfx canister --network ic call h5aet-waaaa-aaaab-qaamq-cai wallet_balance + +The command returns the balance using Candid format as a record with an +amount field (represented by the hash 3_573_748_184) and a balance of +6,895,656,625,450 cycles like this: + + (record { 3_573_748_184 = 6_895_656_625_450 }) + +# Add a controller {#wallet-add-controller} + +If you are the controller of a cycles wallet, you can add other +principals or canister identifiers to the controller role. Adding a +principal to the controller role also automatically adds the principal +to the custodian role. + +To add a controller to a cycles wallet in a local project: + +1. Open a terminal and navigate to the root directory of the project. + +2. Start the Internet Computer locally by running the following + command: + + ``` bash + dfx start --background + ``` + +3. Display the cycles balance from the cycles wallet associated with + the currently-selected identity by running a command similar to the + following: + + ``` bash + dfx wallet add-controller + ``` + + For example, you would run the following command to add the user + represented by the principal identifier + b5quc-npdph-l6qp4-kur4u-oxljq-7uddl-vfdo6-x2uo5-6y4a6-4pt6v-7qe as a + controller of the local cycles wallet: + + dfx wallet add-controller b5quc-npdph-l6qp4-kur4u-oxljq-7uddl-vfdo6-x2uo5-6y4a6-4pt6v-7qe + + The command displays output similar to the following: + + Added b5quc-npdph-l6qp4-kur4u-oxljq-7uddl-vfdo6-x2uo5-6y4a6-4pt6v-7qe as a controller. + +# List the current controllers {#wallet-get-controllers} + +You can use the `dfx wallet controllers` command or the +`get_controllers` method to list the principals that have full control +over a specified cycles wallet canister. + +To list the controllers for a cycles wallet in a local project: + +1. Open a terminal and navigate to the root directory of the project. + +2. Start the Internet Computer locally by running the following + command: + + ``` bash + dfx start --background + ``` + +3. List the principal identifiers that have full control over the + cycles wallet in the current project by running the following + command: + + ``` bash + dfx wallet controllers + ``` + + The command displays the textual representation of the principals + that have control over the cycles wallet with output similar to the + following: + + tsqwz-udeik-5migd-ehrev-pvoqv-szx2g-akh5s-fkyqc-zy6q7-snav6-uqe + b5quc-npdph-l6qp4-kur4u-oxljq-7uddl-vfdo6-x2uo5-6y4a6-4pt6v-7qe + +# Remove a controller {#wallet-remove-controller} + +You can use the `dfx wallet remove-controller` command or the +`remove_controller` method to remove a principal as a controller. + +To remove a controller for a cycles wallet in a local project: + +1. Open a terminal and navigate to the root directory of the project. + +2. Start the Internet Computer locally by running the following + command: + + ``` bash + dfx start --background + ``` + +3. Specify the principal identifier to remove from the controller role + in the current project by running a command similar to the + following: + + ``` bash + dfx wallet remove-controller b5quc-npdph-l6qp4-kur4u-oxljq-7uddl-vfdo6-x2uo5-6y4a6-4pt6v-7qe + ``` + + The command output similar to the following: + + Removed b5quc-npdph-l6qp4-kur4u-oxljq-7uddl-vfdo6-x2uo5-6y4a6-4pt6v-7qe as a controller. + +# Authorize a custodian {#wallet-authorize} + +You can use the `dfx wallet authorize` command or the `authorize` method +to authorize a principal as a custodian of a cycles wallet. + +To authorize a principal as a custodian for the cycles wallet in a local +project: + +1. Open a terminal and navigate to the root directory of the project. + +2. Start the Internet Computer locally by running the following + command: + + ``` bash + dfx start --background + ``` + +3. Specify the principal identifier to authorize as a custodian in the + current project and for the current identity by running a command + similar to the following: + + ``` bash + dfx wallet authorize b5quc-npdph-l6qp4-kur4u-oxljq-7uddl-vfdo6-x2uo5-6y4a6-4pt6v-7qe + ``` + + The command output similar to the following: + + Authorized b5quc-npdph-l6qp4-kur4u-oxljq-7uddl-vfdo6-x2uo5-6y4a6-4pt6v-7qe as a custodian. + +# List current custodians {#wallet-get-custodian} + +You can use the `dfx wallet custodians` command or the `get_custodians` +method to return the list of principals that are currently defined as +custodians for the cycles wallet. + +To list the custodians for a cycles wallet in a local project: + +1. Open a terminal and navigate to the root directory of the project. + +2. Start the Internet Computer locally by running the following + command: + + ``` bash + dfx start --background + ``` + +3. List the principal identifiers that have the custodian role for the + cycles wallet in the current project by running the following + command: + + ``` bash + dfx wallet custodians + ``` + + The command displays output similar to the following: + + tsqwz-udeik-5migd-ehrev-pvoqv-szx2g-akh5s-fkyqc-zy6q7-snav6-uqe + b5quc-npdph-l6qp4-kur4u-oxljq-7uddl-vfdo6-x2uo5-6y4a6-4pt6v-7qe + +# Remove authorization for a custodian {#wallet-deauthorize} + +You can use the `dfx wallet deauthorize` command or the `deauthorize` +method to remove a principal as a custodian for a cycles wallet. +De-authorizing a principal that was previously added as a controller +also automatically removes the principal from the controller role. + +To remove a custodian for a cycles wallet in a local project: + +1. Open a terminal and navigate to the root directory of the project. + +2. Start the Internet Computer locally by running the following + command: + + ``` bash + dfx start --background + ``` + +3. Specify the principal identifier to remove from the custodian role + in the current project by running a command similar to the + following: + + ``` bash + dfx wallet deauthorize b5quc-npdph-l6qp4-kur4u-oxljq-7uddl-vfdo6-x2uo5-6y4a6-4pt6v-7qe + ``` + + The command output similar to the following: + + Deauthorized b5quc-npdph-l6qp4-kur4u-oxljq-7uddl-vfdo6-x2uo5-6y4a6-4pt6v-7qe as a custodian. + +# Send cycles to a canister {#wallet-send} + +You can use `dfx wallet send` command of the `wallet_send` method to +send a specific number of cycles to a specific canister. Keep in mind +that the canister you specify must be a cycles wallet or have a +`wallet_receive` method to accept the cycles. + +If you have deployed a cycles wallet on the Internet Computer main +network, you can use the `dfx wallet send` command to send cycles +between canisters running on the network. + +To send cycles to another canister running on the Internet Computer: + +1. Open a terminal and navigate to a directory that contains a + `dfx.json` configuration file. + +2. Check your connection to the Internet Computer by running the + following command: + + ``` bash + dfx ping ic + ``` + +3. Get the canister identifier for the canister that you want to + receive the cycles. + + For example, run the following command to display the cycles wallet + identifier associated with the current user identity on the Internet + Computer: + + ``` bash + dfx identity --network ic get-wallet + ``` + + The command displays the cycles wallet canister identifier with + output similar to the following: + + gastn-uqaaa-aaaae-aaafq-cai + +4. Send cycles to the canister identifier by running a command similar + to the following: + + ``` bash + dfx wallet --network ic send + ``` + + For example: + + dfx wallet --network ic send gastn-uqaaa-aaaae-aaafq-cai 10000000000 + + If the transfer is successful, the command does not displays any + output. + + ::: note + The maximum number of cycles that can be stored in a cycles wallet + is two to the power of sixty-four (2^64^ or + 18,446,744,073,709,551,616 cycles). + ::: + +5. Check the cycles wallet balance to see the updated number of cycles + available by running the following command: + + ``` bash + dfx wallet --network ic balance + ``` + + For example: + + 67991699387090 cycles. + +# List address book entries {#_list_address_book_entries} + +You can use the `dfx wallet addresses` command or the `list_addresses` +method to list the principal identifiers and roles that have been +configured for the cycles wallet. + +To view address book entries for a cycles wallet running on the Internet +Computer: + +1. Open a terminal and navigate to a directory that contains a + `dfx.json` configuration file. + +2. Check your connection to the Internet Computer by running the + following command: + + ``` bash + dfx ping ic + ``` + +3. Get the address book entries for the cycles wallet by running the + following command : + + ``` bash + dfx wallet --network ic addresses + ``` + + The command displays the controllers and custodians for the cycles + wallet with output similar to the following: + + Id: tsqwz-udeik-5migd-ehrev-pvoqv-szx2g-akh5s-fkyqc-zy6q7-snav6-uqe, Kind: Unknown, Role: Controller, Name: No name set. + Id: ejta3-neil3-qek6c-i7rdw-sxreh-lypfe-v6hjg-6so7x-5ugze-3iohr-2qe, Kind: Unknown, Role: Custodian, Name: No name set. + Id: b5quc-npdph-l6qp4-kur4u-oxljq-7uddl-vfdo6-x2uo5-6y4a6-4pt6v-7qe, Kind: Unknown, Role: Controller, Name: No name set. + +# Additional methods in the default cycles wallet {#_additional_methods_in_the_default_cycles_wallet} + +The default cycles wallet canister includes additonal methods that are +not exposed as `dfx wallet` commands. The additional methods support +more advanced cycles management tasks such as creating new canisters and +managing events. + +## Create a new cycles wallet {#wallet-create-wallets} + +Use the `wallet_create_wallet` method to create a new cycles wallet +canister with an initial cycle balance and, optionally, with a specific +principal as its controller. If you don't specify a controlling +principal, the cycles wallet you use to create the new wallet will be +the new wallet's controller. + +For example, you can run a command similar to the following to create a +new wallet and assign a principal as a controller: + + dfx canister --network call f3yw6-7qaaa-aaaab-qaabq-cai wallet_create_wallet '(record { cycles = 5000000000000 : nat64; controller = principal "vpqee-nujda-46rtu-4noo7-qnxmb-zqs7g-5gvqf-4gy7t-vuprx-u2urx-gqe"})' + +The command returns the principal for the new wallet: + + (record { 1_313_628_723 = principal "dcxxq-jqaaa-aaaab-qaavq-cai" }) + +## Register a new canister identifier {#wallet-create-canister} + +Use the `wallet_create_canister` method to register a new canister +identifier on the Internet Computer. This method creates a new \"empty\" +canister placeholder with an initial cycle balance and, optionally, with +a specific principal as its controller. After you have registered the +canister identifier, you can install code for your application as a +separate step. + +For example, you can run a command similar to the following to create a +new wallet and assign a principal as a controller: + + dfx canister --network call f3yw6-7qaaa-aaaab-qaabq-cai wallet_create_canister '(record { cycles = 5000000000000 : nat64; controller = principal "vpqee-nujda-46rtu-4noo7-qnxmb-zqs7g-5gvqf-4gy7t-vuprx-u2urx-gqe"})' + +The command returns the principal for the new canister you created: + + (record { 1_313_628_723 = principal "dxqg5-iyaaa-aaaab-qaawa-cai" }) + +## Receive cycles from a canister {#wallet-receive} + +Use the `wallet_receive` method as an endpoint to receive cycles. + +## Forward calls from a wallet {#wallet-call} + +Use the `wallet_call` method to forward calls using the cycles wallet +identifier. + +## Manage addresses {#wallet-addresses} + +Use the following methods to manage address book entries: + +- `add_address`: (address: AddressEntry) → (); + +- `remove_address`: (address: principal) → (); + +## Manage events {#events} + +Use the following methods to retrieve event and chart information. + +- `get_events`: (opt record { from: opt nat32; to: opt nat32; }) → + (vec Event) query; + +- `get_chart`: (opt record { count: opt nat32; precision: opt nat64; } + ) → (vec record { nat64; nat64; }) query; + +For example, you can use the `get_events` method to return +`canister_create` and other events by running a command similar to the +following: + +``` bash +dfx canister call get_events '(record {from = null; to = null})' +``` + +If the cycles wallet (`gastn-uqaaa-aaaae-aaafq-cai`) is deployed on the +Internet Computer main network, you could run a command that looks like +this to return events: + + dfx canister --network ic call gastn-uqaaa-aaaae-aaafq-cai get_events '(record {from = null; to = null})' + +The output from the command is in Candid format similar to the +following: + + ( + vec { record { 23_515 = 0; 1_191_829_844 = variant { 4_271_600_268 = record { 23_515 = principal "tsqwz-udeik-5migd-ehrev-pvoqv-szx2g-akh5s-fkyqc-zy6q7-snav6-uqe"; 1_224_700_491 = null; 1_269_754_742 = variant { 4_218_395_836 };} }; 2_781_795_542 = 1_621_456_688_636_513_683;}; record { 23_515 = 1; 1_191_829_844 = variant { 4_271_600_268 = record { 23_515 = principal "ejta3-neil3-qek6c-i7rdw-sxreh-lypfe-v6hjg-6so7x-5ugze-3iohr-2qe"; 1_224_700_491 = null; 1_269_754_742 = variant { 2_494_206_670 };} }; 2_781_795_542 = 1_621_461_468_638_569_551;}; record { 23_515 = 2; 1_191_829_844 = variant { 1_205_528_161 = record { 2_190_693_645 = 11_000_000_000_000; 2_631_180_839 = principal "gvvca-vyaaa-aaaae-aaaga-cai";} }; 2_781_795_542 = 1_621_462_573_993_647_258;}; record { 23_515 = 3; 1_191_829_844 = variant { 1_205_528_161 = record { 2_190_693_645 = 11_000_000_000_000; 2_631_180_839 = principal "gsueu-yaaaa-aaaae-aaagq-cai";} }; 2_781_795_542 = 1_621_462_579_193_578_440;}; record { 23_515 = 4; 1_191_829_844 = variant { 1_955_698_212 = record { 2_190_693_645 = 0; 2_374_371_241 = "install_code"; 2_631_180_839 = principal "aaaaa-aa";} }; 2_781_795_542 = 1_621_462_593_047_590_026;}; record { 23_515 = 5; 1_191_829_844 = variant { 1_955_698_212 = record { 2_190_693_645 = 0; 2_374_371_241 = "install_code"; 2_631_180_839 = principal "aaaaa-aa";} }; 2_781_795_542 = 1_621_462_605_779_157_885;}; record { 23_515 = 6; 1_191_829_844 = variant { 1_955_698_212 = record { 2_190_693_645 = 0; 2_374_371_241 = "authorize"; 2_631_180_839 = principal "gsueu-yaaaa-aaaae-aaagq-cai";} }; 2_781_795_542 = 1_621_462_609_036_146_536;}; record { 23_515 = 7; 1_191_829_844 = variant { 1_955_698_212 = record { 2_190_693_645 = 0; 2_374_371_241 = "greet"; 2_631_180_839 = principal "gvvca-vyaaa-aaaae-aaaga-cai";} }; 2_781_795_542 = 1_621_463_144_066_333_270;}; record { 23_515 = 8; 1_191_829_844 = variant { 4_271_600_268 = record { 23_515 = principal "ejta3-neil3-qek6c-i7rdw-sxreh-lypfe-v6hjg-6so7x-5ugze-3iohr-2qe"; 1_224_700_491 = null; 1_269_754_742 = variant { 2_494_206_670 };} }; 2_781_795_542 = 1_621_463_212_828_477_570;}; record { 23_515 = 9; 1_191_829_844 = variant { 1_955_698_212 = record { 2_190_693_645 = 0; 2_374_371_241 = "wallet_balance"; 2_631_180_839 = principal "gastn-uqaaa-aaaae-aaafq-cai";} }; 2_781_795_542 = 1_621_878_637_071_884_946;}; record { 23_515 = 10; 1_191_829_844 = variant { 4_271_600_268 = record { 23_515 = principal "b5quc-npdph-l6qp4-kur4u-oxljq-7uddl-vfdo6-x2uo5-6y4a6-4pt6v-7qe"; 1_224_700_491 = null; 1_269_754_742 = variant { 4_218_395_836 };} }; 2_781_795_542 = 1_621_879_473_916_547_313;}; record { 23_515 = 11; 1_191_829_844 = variant { 313_999_214 = record { 1_136_829_802 = principal "gastn-uqaaa-aaaae-aaafq-cai"; 3_573_748_184 = 10_000_000_000;} }; 2_781_795_542 = 1_621_977_470_023_492_664;}; record { 23_515 = 12; 1_191_829_844 = variant { 2_171_739_429 = record { 25_979 = principal "gastn-uqaaa-aaaae-aaafq-cai"; 3_573_748_184 = 10_000_000_000; 4_293_698_680 = 0;} }; 2_781_795_542 = 1_621_977_470_858_839_320;};}, + ) + +In this example, there are twelve event records. The Role field +(represented by the hash `1_269_754_742`) specifies whether a principal +is a controller (represented by the hash `4_218_395_836`) or a custodian +(represented by the hash `2_494_206_670`). The events in this example +also illustrate an amount field (represented by the hash +`3_573_748_184`) with a transfer of 10,000,000,000 cycles. diff --git a/modules/developers-guide/pages/design-apps.text b/modules/developers-guide/pages/design-apps.text new file mode 100644 index 000000000..ac38f8439 --- /dev/null +++ b/modules/developers-guide/pages/design-apps.text @@ -0,0 +1,107 @@ +--- +date: 2021-08-05 +title: Design apps +--- + +As you come up with ideas for applications, you are going to make many +design decisions about how to structure and organize your project. Most +of these design decisions are independent of whether you deploy your app +on a traditional cloud service or on the Internet Computer. However, if +you are going to deploy on the Internet Computer, there are a few design +decisions that you should pay particular attention to as you plan the +implementation for your app. + +::: caution +This section is work-in-progress and incomplete. As best practices and +design patterns evolve for building applications that run on the +Internet Computer, the information included here will also evolve and +change accordingly. +::: + +# Single or multiple canister architecture {#_single_or_multiple_canister_architecture} + +One of the first decisions you might want to consider when designing +your application is whether it should be encapsulated in a single +canister or consist of multiple canisters. + +For example, if you are writing a simple service with no front-end, you +might want to use a single canister to simplify project management and +maintenance and focus on adding features. If your application has both +front-end assets and back-end business logic, your project is likely to +consist of at least two canisters, with one canister for managing user +interface components and another canister for the backend services the +application provides. + +In planning, you might also consider placing some common reusable +services in their own canister so that they can be imported and called +from other more-specialized canisters or made available for other +developers to use. The [LinkedUp](https://github.com/dfinity/linkedup) +sample application illustrates this approach by splitting the +professional service application into two canisters. In the LinkedUp +example, the functions that establish social connections are defined in +the `connectd` canister and separate from the functions used to set up +professional profiles that are defined in the `linkedup` canister. It is +easy to imagine extending the application with a third canister, for +example to schedule events based on profile attributes or shared +connections. + +# Segregating actors from types and utilities {#_segregating_actors_from_types_and_utilities} + +In planning the architecture for your project, one common practice is to +place the code for the main actor in one file with separate additional +files for defining the types you program uses and utility functions that +don't require an actor. + +For example, you might set up the back-end logic for your application to +consist of the following files: + +- `Main.mo` or `main.rs` with the functions that require an actor to + send query and update calls. + +- `Util.mo` or `util.rs` with helper functions that can be imported + for the actor to use. + +- `Types.mo` or `types.rs` with all of the data type definitions for + your application. + +# Using query calls {#_using_query_calls} + +As discussed in [Query and update +methods](../developers-guide/concepts/canisters-code.xml#query-update), +queries return results faster than update calls. Therefore,explicitly +marking a function as a `query` is an effective strategy for improving +application performance. In the planning and design phase, you should +consider how best to use query calls instead of functions that can +perform queries or updates. + +That is a good general rule to follow and can be applied broadly to most +categories of applications. However, you should also consider the +security and performance trade-off that queries don't go through +consensus. For some applications, that trade-off might be appropriate. +For example, if you are developing a blogging platform, queries that +retrieve articles matching a tag probably don't warrant going through +consensus to ensure that a majority of nodes agree on the results. +However, if your application is retrieving sensitive information---like +financial data---you might want more assurance about your results than a +basic query provides. + +As an alternative to basic queries, the Internet Computer also supports +**certified queries**. Certified queries enable you to receive +**authenticated responses** that you can trust. Using certified queries +is an advanced technique that is not covered in the tutorials or other +developer-focused documentation, but you can learn about how the +authentication works and what you need to do to configure your program +to return certified data in response to queries in the [Interface +specification](../interface-spec/index.xml). + +# Data storage and retrieval {#_data_storage_and_retrieval} + +For many applications, databases are primarily used to provide long term +storage of records that can be retrieved efficiently using one or more +key fields. On the Internet Computer, this use case is usually addressed +through data structures like hash tables. Instead of a traditional +database, the Internet Computer enables you to use **stable memory** to +handle long-term data storage---often referred to as orthogonal +persistance---and to use **query calls** to retrieve your data. Although +this approach works for most applications and simple key value database +requests it doesn't fully emulate a relational database. diff --git a/modules/developers-guide/pages/glossary.text b/modules/developers-guide/pages/glossary.text new file mode 100644 index 000000000..84f9b6f19 --- /dev/null +++ b/modules/developers-guide/pages/glossary.text @@ -0,0 +1,141 @@ +--- +date: 2021-08-05 +title: Glossary +--- + +actor + +: An actor is a special kind of object in modern programming languages + that processes messages in an isolated state, enabling them to be + handled remotely and asynchronously. + +```{=html} + +``` + +canister + +: A canister is a conceptual object similar to a smart contract with a + universally-unique identifier and an owner that defines the + boundaries of a specific application, service, or micro-site. A + canister encapsulates all of the programming logic, public entry + methods, the interface description for the provided message types, + and state information for the application, service, or micro-service + it describes. + +```{=html} + +``` + +controller + +: A controller is an identity that has special rights to manage the + canister it controls. For example, only a controlling identity can + be used to install, upgrade, or delete the canister under its + control. You can specify the controller identity using the textual + representation of a principal---often referred to as the principal + identifier---associated with a user or with a canister. + +```{=html} + +``` + +ledger + +: The Internet Computer records all transactions involving ICP tokens + in a specialized management canister, called the **ledger + canister**.The ledger canister is a simplified parallel blockchain + that runs on the Internet Computer in a subnet with other network + management canisters. The ledger canister implements a smart + contract that holds **accounts** and **balances** and keeps a + history of the **transactions** that affect accounts and balances. + The transactions are recorded to track the following specific + events: + + - **Mint ICP tokens** for accounts. + + - **Transfer ICP tokens** from one account to another. + + - **Burn ICP tokens** to eliminate them from existence. + +```{=html} + +``` + +node + +: A physical computer that is a registered member of the {platform} + network and running the Internet Computer replica processes. + +```{=html} + +``` + +principal + +: The first time you use the {sdk-short-name}, the `dfx` command-line + tool creates a `default` developer identity for you with a + public/private key pair in a PEM file. This Internet Computer + developer identity is represented internally by a derived + **principal** data type and a textual representation of the + principal often referred to as your **principal identifier**. The + developer identity can also be used to derive an **account + identifier**---similar to a Bitcoin or Ethereum address---to hold + ICP tokens on your behalf in the Internet Computer ledger canister. + +```{=html} + +``` + +replica + +: In the context of the {platform}, a replica refers to the Internet + Computer processes (for example, the `replica`, `nodemanager`, and + other lower-level Internet Computer protocol processes) running on a + physical computer node in the network. For the {sdk-short-name}, you + use the `dfx start` and `dfx stop` commands to start and stop the + `replica` process locally to provide a local network for + development. + +```{=html} + +``` + +smart contract + +: A smart contract is software that enables trusted transactions and + agreements to be carried out across a distributed, decentralized + blockchain network without the need for any central authority or + legal system. With a smart contract, the terms of a transaction or + agreement are written directly into lines of code that are executed + on the blockchain network. The code controls the execution, and the + transactions are tamper-proof, traceable, and irreversible. On the + Internet Computer, smart contracts are deployed as + [canisters](#g-canister). + +```{=html} + +``` + +wallet + +: On the Internet Computer, a wallet is a specialized application that + allows you to store and retrieve your digital assets. The wallet + application is implemented as a canister that runs on the Internet + Computer. A wallet enables you to manage your ICP token balances, + convert ICP token into cycles, and distribute cycles to your own or + other users\' canisters as a means for accessing or providing + internet services. + +```{=html} + +``` + +WebAssembly + +: [WebAssembly](https://webassembly.org/) (`Wasm`) is a low-level + computer instruction format. Because WebAssembly defines a + portable,open-standard, binary format that abstracts cleanly over + most modern computer hardware, it is broadly supported for programs + that run on the internet. Programs written in Motoko are compiled to + WebAssembly code for execution on Internet Computer replicas. diff --git a/modules/developers-guide/pages/install-upgrade-remove.text b/modules/developers-guide/pages/install-upgrade-remove.text new file mode 100644 index 000000000..c26a8d8a8 --- /dev/null +++ b/modules/developers-guide/pages/install-upgrade-remove.text @@ -0,0 +1,140 @@ +--- +date: 2021-08-05 +title: Install, upgrade, or remove software +--- + +As described in the [Quick start](../quickstart/quickstart-intro.xml), +you can download and install the latest version of the {sdk-short-name} +package by running a command in a terminal shell. The topics in this +section provide additional information about installing, upgrading, and +removing the {sdk-short-name}. + +[ROOT:page\$download.adoc](ROOT:page$download.adoc) + +# Reviewing the license agreement {#_reviewing_the_license_agreement} + +The installation script prompts you to read and accept the [DFINITY +Canister SDK License +Agreement](https://sdk.dfinity.org/sdk-license-agreement.txt) before +installing the `dfx` command-line interface executable and its +dependencies on your local computer. You must type `y` and press Enter +to continue with the installation. + +After you accept the license agreement, the installation script displays +information about the components being installed on the local computer. + +# What gets installed {#_what_gets_installed} + +The {sdk-short-name} installation script installs several components in +default locations on your local computer. The following table describes +the development environment components that the installation script +installs: + ++-------------+--------------------------------------+-----------------+ +| Component | Description | Default | +| | | location | ++=============+======================================+=================+ +| dfx | DFINITY execution command-line | `/usr | +| | interface (CLI) | /local/bin/dfx` | ++-------------+--------------------------------------+-----------------+ +| moc | Motoko runtime compiler | `~/.cache/d | +| | | finity/versions | +| | | //moc` | ++-------------+--------------------------------------+-----------------+ +| replica | Internet Computer local network | `~/.cache/dfini | +| | binary | ty/versions//replica` | ++-------------+--------------------------------------+-----------------+ +| u | Script to remove the | `~/ | +| ninstall.sh | {sdk-short-name} and all of its | .cache/dfinity` | +| | components | | ++-------------+--------------------------------------+-----------------+ +| versions | Cache directory that contains a | `~/.cache/df | +| | subdirectory for each version of the | inity/versions` | +| | {sdk-short-name} you install. | | ++-------------+--------------------------------------+-----------------+ + +## Core components in a versioned directory {#_core_components_in_a_versioned_directory} + +The `~/.cache/dfinity/versions` directory stores one or more versioned +subdirectories of the {sdk-short-name}. Each versioned subdirectory +contains the all of the directories and files required for a specific +version of the {sdk-short-name}. For example, if you list the contents +of the `~/.cache/dfinity/versions/0.8.0` directory you would see the +following core components: + + total 349192 + drwxr-xr-x 17 pubs staff 544 Mar 15 11:55 . + drwxr-xr-x 4 pubs staff 128 Mar 25 14:36 .. + drwxr-xr-x 49 pubs staff 1568 Mar 15 11:55 base + drwxr-xr-x 20 pubs staff 640 Mar 15 11:55 bootstrap + -r-x------ 1 pubs staff 66253292 Mar 15 11:55 dfx + -r-x------ 1 pubs staff 10496256 Dec 31 1969 ic-ref + -r-x------ 1 pubs staff 5663644 Dec 31 1969 ic-starter + -r-x------ 1 pubs staff 9604 Dec 31 1969 libcharset.1.0.0.dylib + -r-x------ 1 pubs staff 38220 Dec 31 1969 libffi.7.dylib + -r-x------ 1 pubs staff 668300 Dec 31 1969 libgmp.10.dylib + -r-x------ 1 pubs staff 958248 Dec 31 1969 libiconv.2.4.0.dylib + -r-x------ 1 pubs staff 4200 Dec 31 1969 libiconv.dylib + -r-x------ 1 pubs staff 96900 Dec 31 1969 libz.1.2.11.dylib + -r-x------ 1 pubs staff 15417684 Dec 31 1969 mo-doc + -r-x------ 1 pubs staff 14634020 Dec 31 1969 mo-ide + -r-x------ 1 pubs staff 15111508 Dec 31 1969 moc + -r-x------ 1 pubs staff 49404128 Dec 31 1969 replica + +## Motoko base directory {#_motoko_base_directory} + +The `base` directory in the versioned subdirectory of the +{sdk-short-name} contains the Motoko base library modules that are +compatible with that version of the {sdk-short-name}. Because the Motoko +base library is evolving rapidly, you should only use the base modules +that are packaged with the version of the {sdk-short-name} that you have +installed. + +## Bootstrap directory {#_bootstrap_directory} + +The `bootstrap` directory contains web server code that is deprecated. +Beginning with version 0.7.0, agents can call an HTTP middleware server +instead of the `bootstrap` code. This change enables canisters to +respond to HTTP requests directly and operate more like traditional +web-based applications. + +# Upgrading to the latest version {#_upgrading_to_the_latest_version} + +If a new version of the {sdk-short-name} is available for download after +your initial installation, you should install the updated version at +your earliest convenience to get the latest fixes and enhancements as +soon as possible. You can use the `dfx upgrade` command to compare the +version you have currently installed against the latest version +available for download. If a newer version of `dfx` is available, the +`dfx upgrade` command automatically downloads and installs the latest +version. + +Note that you don't need to uninstall the software before installing the +new version. However, if you want to perform a clean installation rather +than an upgrade, you can first uninstall the software as described in +[Removing the software](#remove), then re-run the download and +installation command. + +For information about the features and fixes in the latest release, see +the [Release notes](release-notes:sdk-release-notes.xml). + +# Removing the software {#remove} + +When you install the {sdk-short-name}, the installation script puts the +required binary files in a local directory and creates a cache. You can +remove the SDK binaries and cache from your local computer by running +the `uninstall` script located in the `.cache` folder. + +For example: + +``` bash +~/.cache/dfinity/uninstall.sh +``` + +If you are uninstalling because you want to immediately reinstall a +clean version of `dfx`, you can run the following command: + +``` bash +~/.cache/dfinity/uninstall.sh && sh -ci "$(curl -sSL https://sdk.dfinity.org/install.sh)" +``` diff --git a/modules/developers-guide/pages/lang-service-ide.text b/modules/developers-guide/pages/lang-service-ide.text new file mode 100644 index 000000000..a9db39262 --- /dev/null +++ b/modules/developers-guide/pages/lang-service-ide.text @@ -0,0 +1,110 @@ +--- +author: December 2019 (Alpha 3) +date: 2021-08-05 +title: Language server and development client support +--- + +The [Language Server Protocol +(LSP)](https://microsoft.github.io/language-server-protocol)---originally +developed by Microsoft---provides a common language to add +broadly-useful features like automatic code complete, GoTo definition, +and hover-over tool tips to development tools. Using the Language Server +Protocol, a language server enables standardized inter-process +communication between a programming language and any editor, integrated +development environment (IDE), or client endpoint tool. + +Because the Language Server Protocol (LSP) standardizes the protocol for +how language-specific servers and development tools communicate, a +single language server can be re-used in multiple development tools with +minimal effort. + +# Adding a language server for Motoko {#_adding_a_language_server_for_motoko} + +With the {sdk-short-name}, you can add a language server for Motoko to +your editor or development environment client by invoking the +`dfx _language-service` programmatically when you open Motoko programs +in an editor or development environment configured to recognize the +language server. You can use any editor or integrated development +environment that supports the Language Server Protocol to invoke the +`dfx _language-service` programmatically. Once invoked, the language +server ensures that your development environment reports Motoko compiler +errors and provides code completion and refactoring tools. + +For example, if you use Visual Studio Code (VSCode) or Emacs as your +development environment, you can install a plugin extension that enables +those editors to automatically invoke the Motoko language server. + +::: note +Only the Visual Studio Code (VSCode) plugin extension is currently +available for Motoko. For information about installing the plugin, see +[Install the language editor +plug-in](../quickstart/local-quickstart.xml#install-vscode). +::: + +# Invoking the language service manually {#_invoking_the_language_service_manually} + +Although it is extremely rare that you would start the Motoko language +server directly in a terminal shell. it is possible to do so by running +the following command: + +``` bash +dfx _language-service --force-tty +``` + +Note that you can only run this command from within a project directory. +For example, if your project name is `hello_world`, your current working +directory must be the `hello_world` top-level project directory or one +of its subdirectories. + +## Basic usage {#_basic_usage} + +``` bash +dfx _language-service [canister_name] [flag] +``` + +## Flags {#_flags} + +You can use the following optional flags with the +`dfx _language-service` command. + ++-----------------------------------+-----------------------------------+ +| Flag | Description | ++===================================+===================================+ +| `--force-tty` | Starts the the Motoko language | +| | server directly in a terminal | +| | shell. | ++-----------------------------------+-----------------------------------+ +| `-h`, `--help` | Displays usage information. | ++-----------------------------------+-----------------------------------+ +| `-V`, `--version` | Displays version information. | ++-----------------------------------+-----------------------------------+ + +## Arguments {#_arguments} + +You can specify the following arguments for the `dfx _language-service` +command. + ++------------------------+---------------------------------------------+ +| Argument | Description | ++========================+=============================================+ +| `canister_name` | Specifies the name of the canister that the | +| | compiler should monitor. If you specify a | +| | canister name, the name should match a | +| | canister name you have configured in the | +| | `dfx.json` configuration file for your | +| | project. If you don't specify a canister | +| | name, the first canister specified in the | +| | `dfx.json` configuration file is used as | +| | the target. | ++------------------------+---------------------------------------------+ + +## Examples {#_examples} + +If you want to use an integrated development environment to develop code +for the canister `my-canister` you should have the development +environment invoke the language service using the following +`dfx _language-service` command: + +``` bash +dfx _language-service my-canister +``` diff --git a/modules/developers-guide/pages/sample-apps.text b/modules/developers-guide/pages/sample-apps.text new file mode 100644 index 000000000..00e1351a0 --- /dev/null +++ b/modules/developers-guide/pages/sample-apps.text @@ -0,0 +1,127 @@ +--- +author: May 2020 (Alpha) +date: 2021-08-05 +title: Sample code, applications, and microservices +--- + +Sample code, applications, and microservices that have been developed by +DFINITY or contributed by the community are available from the [DFINITY +public repository](https://github.com/dfinity/examples). + +By accessing the public repository, you can directly download, clone, +fork, or share sample projects. You will also be able to contribute by +suggesting updates or reporting issues for the published projects using +the standard GitHub work flow. + +Sample projects provide a way for you to experiment and collaborate with +other developers. The projects and sample code are not, however, +intended to be used as commercial applications and do not provide any +explicit or implied support or warranty of any kind. + +This section provides a preliminary look at some sample code for +applications and microservices that you can copy and modify to +jump-start your own projects. + +# C {#_c} + +For examples of projects written in the C programming language for the +Internet Computer, see [C++ sample +projects](https://github.com/dfinity/examples/tree/master/c). + +- [Adventure + game](https://github.com/dfinity/examples/tree/master/c/adventure) + +- [QR code + generator](https://github.com/dfinity/examples/tree/master/c/qr) + +- [Reverse + game](https://github.com/dfinity/examples/tree/master/c/reverse) + +# Motoko {#_motoko} + +For projects that use the Motoko programming language, see [Motoko +sample +projects](https://github.com/dfinity/examples/tree/master/motoko). + +- [Calculator - simple + functions](https://github.com/dfinity/examples/tree/master/motoko/calc) + +- [Counter](https://github.com/dfinity/examples/tree/master/motoko/counter) + +- [Echo](https://github.com/dfinity/examples/tree/master/motoko/echo) + +- [Factorial](https://github.com/dfinity/examples/tree/master/motoko/factorial) + +- [Hello, + world](https://github.com/dfinity/examples/tree/master/motoko/hello-world) + +- [Hello, + cycles](https://github.com/dfinity/examples/tree/master/motoko/hello_cycles) + +- [Game of Life - + upgrades](https://github.com/dfinity/examples/tree/master/motoko/life) + +- [Phone + book](https://github.com/dfinity/examples/tree/master/motoko/phone-book) + +- [Publish/subscribe](https://github.com/dfinity/examples/tree/master/motoko/pub-sub) + +- [Quicksort](https://github.com/dfinity/examples/tree/master/motoko/quicksort) + +- [Random maze - cryptographic + randomness](https://github.com/dfinity/examples/tree/master/motoko/random_maze) + +- [To-do + checklist](https://github.com/dfinity/examples/tree/master/motoko/simple-to-do) + +- [Superheroes + database](https://github.com/dfinity/examples/tree/master/motoko/superheroes) + +- [whoami](https://github.com/dfinity/examples/tree/master/motoko/whoami) + +# Additional sample applications {#_additional_sample_applications} + +This section includes sample code from projects that are not currently +available in the public repository. + +## Hex encoding and decoding {#_hex_encoding_and_decoding} + +The `mo-hex` project implements hexadecimal encoding and decoding +routines for the Motoko programming language. + +### Source code {#_source_code} + +The project includes the following [hex.mo](#hex) source code. + +#### hex.mo {#hex} + +``` motoko +Unresolved directive in sample-apps.adoc - include::example$hex/hex.mo[] +``` + +## Polynomial long-division in GF(256) {#_polynomial_long_division_in_gf256} + +This program performs polynomial long division for a Galois field +GF(256) element. + +### Source code {#_source_code_2} + +In addition to standard libraries, this project uses two main Motoko +source code files. + +- The [Galois.mo](#galois) file contains the core programming logic. + +- The [Nat.mo](#nat) file contains additional functions that are + imported for use in the `Galois.mo` file. + +#### Galois.mo {#galois} + +``` motoko +Unresolved directive in sample-apps.adoc - include::example$galois/Galois.mo[] +``` + +#### Nat.mo {#nat} + +``` motoko +Unresolved directive in sample-apps.adoc - include::example$galois/Nat.mo[] +``` diff --git a/modules/developers-guide/pages/sdk-guide.text b/modules/developers-guide/pages/sdk-guide.text new file mode 100644 index 000000000..eb240a341 --- /dev/null +++ b/modules/developers-guide/pages/sdk-guide.text @@ -0,0 +1,56 @@ +--- +date: 2021-08-05 +title: "{IC} SDK - Developer Tools" +--- + +The {platform} is poised to help you start a revolution with a new way +to design, build, and release software. + +# Developing open internet applications {#_developing_open_internet_applications} + +Conceptually, the Internet Computer is an extension of the existing +internet that enables a global network of computers to provide the +computing power for running application software. + +In much the same way that the adoption of the transport control protocol +(TCP) and Internet protocol (IP) provided rules for transferring data +between endpoints that helped to establish the "network of networks" +that we know as the internet of today, the Internet Computer relies on a +decentralization protocol called the Internet Computer protocol to +define the software components that enable a global network of computers +to combine their resources to read, replicate, modify, and return +application state. + +# Developer workflow at-a-glance {#_developer_workflow_at_a_glance} + +At a high-level, there are three possible workflows for building +applications that run on the Internet Computer. + +![Development paths](local-remote-path-workflow.svg) + +The first path is the most common: you connect to the Internet Computer +running locally, then write, compile, and deploy iteratively in a local +development environment. + +If you prefer to do all of your development work without connecting to a +local or remote network, you can follow the second path and only connect +to the network when you are ready to compile and deploy. With this +option, you only connect to the Internet Computer network and register +for a unique identifier after you have a program ready to deploy. + +In the third path, you connect to the Internet Computer running on a +remote network, then register for a unique identifier before you have a +program ready to compile. With this option, you can preregister with the +network to receive a unique identifier, then compile and deploy using a +known identifier when you are ready to move your application to the +network. + +Regardless of the development workflow you choose, keep in mind that you +must connect to the Internet Computer network running locally or on a +remote subnet to register your smart contract canister and that +registering your canister creates a unique, network-specific identifier +for the canister. For example, if you do all of your initial development +work locally using a local canister identifier and later want to deploy +your application on an Internet Computer network running remotely, you +will need to connect to the remote network and register an identifier on +that network before you can deploy the application. diff --git a/modules/developers-guide/pages/troubleshooting.text b/modules/developers-guide/pages/troubleshooting.text new file mode 100644 index 000000000..295e047f8 --- /dev/null +++ b/modules/developers-guide/pages/troubleshooting.text @@ -0,0 +1,203 @@ +--- +author: December 2019 (Alpha) +date: 2021-08-05 +title: Troubleshoot issues +--- + +This section provides information to help you troubleshoot and resolve +or work around common issues that are related to the following tasks: + +- downloading and installing the {sdk-short-name} + +- creating, building, or deploying canisters + +- using the `dfx` command-line interface + +- running the Internet Computer network locally in a development + environment + +[developers-guide:page\$webpack-config.adoc](developers-guide:page$webpack-config.adoc) + +# Migrating an existing project {#_migrating_an_existing_project} + +Currently, there is no automatic migration or backward compatibility for +any projects that you might have created using previous versions of the +`dfx` command-line interface. After upgrading to the latest version, you +might see error or failure messages if you attempt to build or install a +project created with a previous version of the `dfx` command-line +interface. + +In many cases, however, you can continue to work with projects from a +previous release by manually changing the dfx setting in the dfx.json +configuration file, then rebuilding the project to be compatible with +the version of the `dfx` command-line interface you have currently +installed. + +For example, if you have a project that was created with `dfx` version +`0.4.9`, open the `dfx.json` file in a text editor and change the `dfx` +setting to the latest version or remove the section entirely. + +# Restarting the local Internet Computer network {#_restarting_the_local_internet_computer_network} + +In some cases, starting the Internet Computer network locally fails +because of replicated state errors. If you encounter issues when running +`dfx start` to start the local Internet Computer network: + +1. In the terminal that displays network operations, press Control-C to + interrupt the local network process. + +2. Stop the Internet Computer network by running the following command: + + ``` bash + dfx stop + ``` + +3. Restart the Internet Computer in a clean state by running the + following command: + + ``` bash + dfx start --clean + ``` + + The `--clean` option removes checkpoints and stale state information + from your project's cache so that you can restart the Internet + Computer replica and web server processes in a clean state. + +Keep in mind, however, that if you reset the state information by +running `dfx start --clean`, your existing canisters are also removed. + +After running `dfx start --clean`, recreate your canisters by running +the following commands: + +``` bash +dfx canister create --all +dfx build +dfx canister install --all +``` + +# Removing the canisters directory {#_removing_the_canisters_directory} + +If you run into problems building or deploying canisters after +successfully connecting to the Internet Computer and registering +canister identifiers, you should remove the `canisters` directory before +attempting to rebuild or redeploy the canisters. + +You can remove the `canisters` directory for a project by running the +following command in the project's root directory: + +``` bash +rm -rf ./.dfx/* canisters/* +``` + +# Reinstalling dfx {#_reinstalling_dfx} + +Many of the bugs you might encounter can be addressed by uninstalling +and reinstalling the `dfx` command-line interface. Here are a few ways +to reinstall `dfx`. + +If you only have one version of `dfx` installed in your development +environment, you can usually run the following command to uninstall and +reinstall the latest version of `dfx`: + +``` bash +~/.cache/dfinity/uninstall.sh && sh -ci "$(curl -sSL https://sdk.dfinity.org/install.sh)" +``` + +If you have modified the location of the `dfx` binary, you might want +run the following command to uninstall the version of `dfx` that is in +your PATH, then reinstall the latest version of `dfx`: + +``` bash +rm -rf ~/.cache/dfinity && rm $(which dfx) && sh -ci "$(curl -sSL https://sdk.dfinity.org/install.sh)" +``` + +# Xcode prerequisite {#_xcode_prerequisite} + +Some versions of the {sdk-short-name} prompted you to install Xcode when +creating a new project on a macOS computer. The prompt has been removed +and the `dfx new` command does not require you to install any macOS +developer tools. However, you should have Developer Command Line Tools +installed if you want to create a Git repository for your project. + +You can check whether you have the developer tools installed by running +`xcode-select -p`. You can install the developer tools by running +`xcode-select --install`. + +# Failed build when using VMs {#_failed_build_when_using_vms} + +If you are running `dfx` using a virtual machine image on Ubuntu or +CentOS, you might see an error message that looks like this when you +attempt to run the `dfx build` command: + +``` bash +Building hello... +An error occurred: +Io( + Os { + code: 2, + kind: NotFound, + message: "No such file or directory", + }, +) +``` + +# Address in use error or orphan processes {#_address_in_use_error_or_orphan_processes} + +If you are developing projects locally, you often have a local version +of core Internet Computer processes---collectively referred to as the +`replica`---running either is a separate terminal or in the background. +If the running Internet Computer processes do not get properly +terminated, you might see operating system errors indicating that an +address is already in use or or be unable to stop processes normally +using the `dfx stop` command. + +There are several scenarios in which you might encounter this issue. For +example, if you run `dfx start` in a local project directory then change +to a different local project directory without first stopping Internet +Computer processes, you might see this issue. + +If you encounter an issue where you suspect or you receive a message +that an address is already in use or that a process is already running +in the background, perform the following steps: + +1. Run the following command to see which process is listening to the + 8000 port if you are using the default local network binding: + + ``` bash + lsof -i tcp:8000 + ``` + +2. Run the following command to terminate any orphan processes: + + ``` bash + killall dfx replica + ``` + +3. Close the current terminal and open a new terminal window. + +4. In the new terminal, run the following command to run the local + Internet Computer in a clean state: + + ``` bash + dfx start --clean --background + ``` + +# Memory leak {#_memory_leak} + +Fixing memory leaks is an ongoing process. If you encounter any error +messages related to memory leaks, you should do the following: + +1. Run `dfx stop` to stop currently running processes. + +2. Uninstall `dfx` to prevent further degradation. + +3. Re-install `dfx` + +4. Run `dfx start` to restart replica processes. + +Alternatively, you can remove the `.cache/dfinity` directory and +re-install the latest `dfx` binary. For example: + +``` bash +rm -rf ~/.cache/dfinity && sh -ci "$(curl -sSL https://sdk.dfinity.org/install.sh)" +``` diff --git a/modules/developers-guide/pages/tutorials-intro.text b/modules/developers-guide/pages/tutorials-intro.text new file mode 100644 index 000000000..29eb83c87 --- /dev/null +++ b/modules/developers-guide/pages/tutorials-intro.text @@ -0,0 +1,85 @@ +--- +date: 2021-08-05 +title: Tutorials +--- + +The [Quick start](../quickstart/quickstart-intro.xml) provided a +simplified introduction to the basic work flow for creating and +deploying a new project without exploring the contents of the project +directory or sample code. + +Next, we'll explore writing a few simple programs to give you hands-on +experience creating programs that run on the {IC}. + +::: note +Most of these tutorials illustrate how to write programs using the +{proglang} programming language. For additional examples of programs +written in other languages, see the {company-id} +[examples](https://github.com/dfinity/examples) repository. +::: + +The following tutorials introduce the basics for writing programs that +run on the {IC}: + +- [Explore the default project](tutorials/explore-templates.xml) takes + a closer look at the work flow for creating projects by exploring + the default files and folders that are added to your workspace when + you create a new project. + +- [Query using an actor](tutorials/define-an-actor.xml) highlights how + to replace the typical `print` function usually defined in a + \"Hello, World!\" program by defining an actor (object) with a + `hello` function. + +- [Pass text arguments](tutorials/hello-location.xml) introduces + different ways you can pass arguments to a function using the + command-line in a terminal shell. + +- [Increment a natural number](tutorials/counter-tutorial.xml) guides + you through the process of writing a program that creates an actor + with functions to increment and return the value of a counter. + +- [Use integers in calculator functions](tutorials/calculator.xml) + shows you how to write a simple calculator program for more practice + working with {proglang} and to learn more about how you can + customize your project environment. + +- [Import library modules](tutorials/phonebook.xml) illustrates how to + import and use a few basic {proglang} base library functions for + working with key-value pairs in a list. + +- [Use multiple actors](tutorials/multiple-actors.xml) describes how + to include multiple unrelated actors in a single project to + illustrate how you can compile multiple canisters for the same + project. + +- [Customize the front-end](tutorials/custom-frontend.xml) illustrates + using a simple React framework to create a new front-end for the + default sample program and guides you through some basic + modifications to customize the interface displayed. If you already + know how to use CSS, HTML, JavaScript, and React or other frameworks + to build your user interface, you can skip this tutorial. + +- [Add a stylesheet](tutorials/my-contacts.xml) illustrates how to add + a stylesheet when you use React to create a new front-end for your + project. If you already know how to add stylesheets to React, you + can skip this tutorial. + +- [Make inter-canister calls](tutorials/intercanister-calls.xml) + illustrates how to make simple calls to functions defined in one + canister from another canister in the same project. + +- [Create scalable apps](tutorials/scalability-cancan.xml) describes + using multiple canisters to create applications that scale. + +- [Add access control with identities](tutorials/access-control.xml) + describes how to create and switch between multiple user identities. + +- [Accept cycles from a wallet](tutorials/simple-cycles.xml) + illustrates how to accept cycles sent from the default wallet + canister. + +Additional tutorials covering more advanced programs and more detailed +examples of how to use the basic building blocks are available in the +[examples](https://github.com/dfinity/examples) repository and +[*{proglang} Programming Language Guide*](../language-guide/motoko.xml). diff --git a/modules/developers-guide/pages/tutorials/at-a-glance.text b/modules/developers-guide/pages/tutorials/at-a-glance.text new file mode 100644 index 000000000..5e654818d --- /dev/null +++ b/modules/developers-guide/pages/tutorials/at-a-glance.text @@ -0,0 +1,34 @@ +--- +date: 2021-08-05 +title: At a glance +--- + +The [Quick start](../../quickstart/quickstart-intro.xml) provides a fast +path to deploying a simple default application without stopping to +admire the scenery along the way. Individual +[tutorials](../tutorials-intro.xml) walk through specific scenarios, +pointing out details about what you're doing in each step. + +If the quick start and tutorials aren't quite your style, this +at-a-glance cheat sheet summarizes the steps to follow for quick +reference. + +After you install the {sdk-short-name}, here's all you need to know: + +1. Create a new project and change to the project directory. + + dfx new && cd > + +2. Edit the back-end that defines your service or application. + +3. Edit the HTML, JavaScript, and CSS that provides the front-end for + your service or application. + +4. Start the Internet Computer for local development or check your + connection to the Internet Computer for network deployment. + +5. Register, build, and deploy locally or on the network. + + dfx deploy --network + +6. View your service or application in a browser. diff --git a/modules/developers-guide/pages/tutorials/calculator.text b/modules/developers-guide/pages/tutorials/calculator.text new file mode 100644 index 000000000..0a6497c05 --- /dev/null +++ b/modules/developers-guide/pages/tutorials/calculator.text @@ -0,0 +1,305 @@ +--- +date: 2021-08-05 +title: Use integers in calculator functions +--- + +In this tutorial, you are going to write a simple calculator program +that creates a single actor with several public entry-point functions to +perform basic arithmetic operations. + +For this tutorial, the actor is named `Calc`. The program uses the +`cell` variable to contain an integer number that represents the current +result of a calculator operation. + +This program supports the following function calls: + +- The `add` function call accepts input and performs addition. + +- The `sub` function call accepts input and performs subtraction. + +- The `mul` function call accepts input and performs multiplication. + +- The `div` function call accepts input and performs division. + +- The `clearall` function clears the `cell` value stored as the result + of previous operations, resetting the `cell` value to zero. + +The `div` function also includes code to prevent the program from +attempting to divide by zero. + +# Before you begin {#_before_you_begin} + +Before starting the tutorial, verify the following: + +- You have downloaded and installed the {sdk-short-name} package as + described in [Download and + install](../../quickstart/local-quickstart.xml#download-and-install). + +- You have stopped any Internet Computer network processes running on + the local computer. + +This tutorial takes approximately 20 minutes to complete. + +# Create a new project {#_create_a_new_project} + +To create a new project for this tutorial: + +1. Open a terminal shell on your local computer, if you don't already + have one open. + +2. Change to the folder you are using for your Internet Computer + projects, if you are using one. + +3. Create a new project by running the following command: + + ``` bash + dfx new calc + ``` + +4. Change to your project directory by running the following command: + + ``` bash + cd calc + ``` + +# Modify the default configuration {#_modify_the_default_configuration} + +For this tutorial, let's modify the default `dfx.json` configuration +file to use a more specific name for its main program. + +To modify the default `dfx.json` configuration file: + +1. Open the `dfx.json` configuration file in a text editor. + +2. Change the `main` key setting from the default `main.mo` program + name to `calc_main.mo`. + + For example: + + ``` bash + "main": "src/calc/calc_main.mo", + ``` + + For this tutorial, changing the name of the source file from + `main.mo` to `calc_main.mo` simply illustrates how the setting in + the `dfx.json` configuration file determines the source file to be + compiled. + + In a more complex application, you might have multiple source files + instead of a single `main` program file. More complex applications + might also have specific dependencies between multiple source files + that you need to manage using settings in the `dfx.json` + configuration file. In a scenario like that---with multiple + canisters and programs defined in your `dfx.json` file---having + multiple files all named `main.mo` might make navigating your + workspace more difficult. The name you choose for each program isn't + significant, but it is important that the name you set in the + `dfx.json` file matches the name of your program in the file system. + +3. Save your changes and close the file to continue. + +# Modify the default program {#_modify_the_default_program} + +For this tutorial, you need to replace the default program with a +program that performs basic arithmetic operations. + +To replace the default program: + +1. Check that you are still in your project directory, if needed. + +2. Copy the template `main.mo` file to create a new file named + `calc_main.mo` by running the following command: + + ``` bash + cp src/calc/main.mo src/calc/calc_main.mo + ``` + +3. Open the `src/calc/calc_main.mo` file in a text editor and delete + the existing content. + +4. Copy and paste the following sample code into the `calc_main.mo` + file: + + ``` motoko + Unresolved directive in calculator.adoc - include::example$calc_main.mo[] + ``` + + You might notice that this sample code uses integer (`Int`) data + types, enabling you to use positive or negative numbers. If you + wanted to restrict the functions in this calculator code to only use + positive numbers, you could change the data type to only allow + natural (`Nat`) data. + +5. Save your changes and close the file to continue. + +# Start the local network {#_start_the_local_network} + +Before you can build the `calc` project, you need to connect to the +Internet Computer network either running locally in your development +environment or running remotely on a subnet that you can access. + +Starting the network locally requires a `dfx.json` file, so you should +be sure you are in your project's root directory. For this tutorial, you +should have two separate terminal shells, so that you can start and see +network operations in one terminal and manage your project in another. + +To start the network locally: + +1. Open a new terminal window or tab on your local computer. + +2. Navigate to the root directory for your project, if necessary. + + - You should now have **two terminals** open. + + - You should have the **project directory** as your **current + working directory**. + +3. Start the Internet Computer network on your local computer by + running the following command: + + ``` bash + dfx start + ``` + + After you start the local network, the terminal displays messages + about network operations. + +4. Leave the terminal that displays network operations open and switch + your focus to your original terminal where you created your new + project. + +# Register, build, and deploy the application {#_register_build_and_deploy_the_application} + +After you connect to the Internet Computer network running locally in +your development environment, you can register, build, and deploy your +application locally. + +To deploy the application locally: + +1. Check that you are still in the root directory for your project, if + needed. + +2. Register, build, and deploy your application by running the + following command: + + ``` bash + dfx deploy + ``` + + The `dfx deploy` command output displays information about the + operations it performs. + +# Verify calculator functions on the canister {#_verify_calculator_functions_on_the_canister} + +You now have a program deployed as a **canister** on your local Internet +Computer network. You can test the program by using `dfx canister call` +commands. + +To test the program you have deployed: + +1. Use the `dfx canister call` command to call the `calc` canister + `add` function and pass it the input argument `10` by running the + following command: + + ``` bash + dfx canister call calc add '(10)' + ``` + + When you pass an argument enclosed by the single quotation marks and + parentheses,the interface description language (IDL) parses the + argument type, so you don't need to specify the argument type + manually. + + Verify that the command returns the value expected for the `add` + function. For example, the program displays output similar to the + following: + + (10) + +2. Call the `mul` function and pass it the input argument `3` by + running the following command: + + ``` bash + dfx canister call calc mul '(3)' + ``` + + Verify that the command returns the value expected for the `mul` + function. For example, the program displays output similar to the + following: + + (30) + +3. Call the `sub` function and pass it the input argument `5` of type + `number` by running the following command: + + ``` bash + dfx canister call calc sub '(5)' + ``` + + Verify that the command returns the value expected for the `sub` + function. For example, the program displays output similar to the + following: + + (25) + +4. Call the `div` function and pass it the input argument `5` by + running the following command: + + ``` bash + dfx canister call calc div '(5)' + ``` + + Verify that the command returns the value expected for the `div` + function. For example, the program displays output similar to the + following: + + (opt 5) + + You might notice that the `div` function returns an optional result. + The program makes the result optional to enable the `div` function + to return `null` in the case of a division-by-zero error. + + Because the cell variable in this program is an integer, you can + also call its functions and specify negative input values. For + example, you might run the following command: + + ``` bash + dfx canister call calc mul '(-4)' + ``` + + which returns: + + (-20) + +5. Call the `clearall` function and verify it resets the `cell` value + to zero: + + ``` bash + dfx canister call calc clearall + ``` + + For example, the program displays output similar to the following: + + (0) + +Unresolved directive in calculator.adoc - +include::example\$candid-ui.adoc\[\] + +\+ ![Calculator functions](candid-calc.png) + +# Stop the local network {#_stop_the_local_network} + +After you finish experimenting with your program, you can stop the local +Internet Computer network so that it doesn't continue running in the +background. + +To stop the local network: + +1. In the terminal that displays network operations, press Control-C to + interrupt the local network process. + +2. Stop the Internet Computer network by running the following command: + + ``` bash + dfx stop + ``` diff --git a/modules/developers-guide/pages/tutorials/counter-tutorial.text b/modules/developers-guide/pages/tutorials/counter-tutorial.text new file mode 100644 index 000000000..4f32b4b70 --- /dev/null +++ b/modules/developers-guide/pages/tutorials/counter-tutorial.text @@ -0,0 +1,303 @@ +--- +date: 2021-08-05 +title: Increment a natural number +--- + +In this tutorial, you are going to write a program that creates a single +actor and provides a few basic functions to increment a counter and +illustrate persistence of a value. + +For this tutorial, the actor is named `Counter`. The program uses the +`currentValue` variable to contain a natural number that represents the +current value of the counter. This program supports the following +function calls: + +- The `increment` function call updates the current value, + incrementing by 1 (no return value). + +- The `get` function call queries and returns the current value. + +- The `set` function call updates the current value to an arbitrary + numeric value you specify as an argument. + +This tutorial provides a simple example of how you can increment a +counter by calling functions on a deployed canister. By calling the +function to increment a value multiple times, you can verify that the +variable state---that is, the value of the variable between +calls---persists. + +# Before you begin {#_before_you_begin} + +Before starting the tutorial, verify the following: + +- You have downloaded and installed the {sdk-short-name} package as + described in [Download and + install](../../quickstart/local-quickstart.xml#download-and-install). + +- You have stopped any Internet Computer network processes running on + the local computer. + +This tutorial takes approximately 20 minutes to complete. + +# Create a new project {#_create_a_new_project} + +To create a new project directory for this tutorial: + +1. Open a terminal shell on your local computer, if you don't already + have one open. + +2. Change to the folder you are using for your Internet Computer + projects, if you are using one. + +3. Create a new project by running the following command: + + ``` bash + dfx new my_counter + ``` + + The command creates a new `my_counter` project and Git repository + for your project. + +4. Change to your project directory by running the following command: + + ``` bash + cd my_counter + ``` + +# Modify the default configuration {#_modify_the_default_configuration} + +You have already seen that creating a new project adds a default +`dfx.json` configuration file to your project directory. In this +tutorial, you will modify the default settings to use a different name +for the main program in your project. + +To modify the default `dfx.json` configuration file: + +1. Open the `dfx.json` configuration file in a text editor and change + the default `main` setting from `main.mo` to `increment_counter.mo`. + + For example: + + ``` json + "main": "src/my_counter/increment_counter.mo", + ``` + + For this tutorial, changing the name of the source file from + `main.mo` to `increment_counter.mo` simply illustrates how the + setting in the `dfx.json` configuration file determines the source + file to be compiled. + + In a more complex application, you might have multiple source files + with dependencies that you need to manage using settings in the + `dfx.json` configuration file. In a scenario like that---with + multiple canisters and programs defined in your `dfx.json` + file---having multiple files all named `main.mo` might be confusing. + + You can leave the rest of the default settings as they are. + +2. Save your change and close the `dfx.json` file to continue. + +3. Change the name of the main program file in the source code + directory to match the name specified in the `dfx.json` + configuration file by running the following command + + ``` bash + mv src/my_counter/main.mo src/my_counter/increment_counter.mo + ``` + +# Modify the default program {#_modify_the_default_program} + +So far, you have only changed the name of the main program for your +project. The next step is to modify the code in the +`src/my_counter/increment_counter.mo` file to define an actor named +`Counter` and implement the `increment`, `get`, and `set` functions. + +To modify the default template source code: + +1. Check that you are still in your project directory, if needed. + +2. Open the `src/my_counter/increment_counter.mo` file in a text editor + and delete the existing content. + +3. Copy and paste the following sample code into the + `increment_counter.mo` file: + + ``` motoko + Unresolved directive in counter-tutorial.adoc - include::example$counter.mo[] + ``` + + Let's take a closer look at this sample program: + + - You can see that the `currentValue` variable declaration in this + example includes the `stable` keyword to indicate the + state---the value that can be set, incremented, and + retrieved---persists. + + This keyword ensures that the value for the variable is + unchanged when the program is upgraded. + + - The declaration for the `currentValue` variable also specifies + that its type is a natural (`Nat`) number. + + - The program includes two public update methods---the `increment` + and `set` functions---and one a query method, in this case, the + `get` function. + + For more information about stable and flexible variables, see + [Stable variables and upgrade + methods](../../language-guide/upgrades.xml) in the [*Motoko + Programming Language Guide*](../../language-guide/motoko.xml). + + For more information about the differences between a query and an + update, see [query + calls](../concepts/canisters-code.xml#query-calls) in [Canisters + include both program and + state](../concepts/canisters-code.xml#canister-state). + +4. Save your changes and close the file to continue. + +# Start the local network {#_start_the_local_network} + +Before you can build the `my_counter` project, you need to connect to +the Internet Computer network either running locally in your development +environment or running remotely on a subnet that you can access. + +Starting the network locally requires a `dfx.json` file, so you should +be sure you are in your project's root directory. For this tutorial, you +should have two separate terminal shells, so that you can start and see +network operations in one terminal and manage your project in another. + +To start the network locally: + +1. Open a new terminal window or tab on your local computer. + +2. Navigate to the root directory for your project, if necessary. + + - You should now have **two terminals** open. + + - You should have the **project directory** as your **current + working directory**. + +3. Start the Internet Computer network on your local computer by + running the following command: + + ``` bash + dfx start + ``` + + After you start the local network, the terminal displays messages + about network operations. + +4. Leave the terminal that displays network operations open and switch + your focus to your original terminal where you created your new + project. + +# Register, build, and deploy the application {#_register_build_and_deploy_the_application} + +After you connect to the Internet Computer network running locally in +your development environment, you can register, build, and deploy your +application locally. + +To deploy the application locally: + +1. Check that you are still in the root directory for your project, if + needed. + +2. Register, build, and deploy your application by running the + following command: + + ``` bash + dfx deploy + ``` + + The `dfx deploy` command output displays information about the + operations it performs. + +# Invoke methods on the deployed canister {#_invoke_methods_on_the_deployed_canister} + +After successfully deploying the canister, you can simulate an end-user +invoking the methods provided by the canister. For this tutorial, you +invoke a `get` method to query the value of a counter, an `increment` +method that increments the counter each time it is called, and a `set` +method to pass an argument to update the counter to an arbitrary value +you specify. + +To test invoking methods on the deployed canister: + +1. Run the following command to invoke the `get` function, which reads + the current value of the `currentValue` variable on the deployed + canister: + + ``` bash + dfx canister call my_counter get + ``` + + The command returns the current value of the `currentValue` variable + as zero: + + (0) + +2. Run the following command to invoke the `increment` function to + increment the value of the `currentValue` variable on the deployed + canister by one: + + ``` bash + dfx canister call my_counter increment + ``` + + This command increments the value of the variable---changing its + state---but does not return the result. + +3. Rerun the following command to get the current value of the + `currentValue` variable on the deployed canister: + + ``` bash + dfx canister call my_counter get + ``` + + The command returns the updated value of the `currentValue` variable + as one: + + (1) + +4. Run additional commands to experiment with invoking other methods + and using different values. + + For example, try commands similar to the following to set and return + the counter value: + + ``` bash + dfx canister call my_counter set '(987)' + dfx canister call my_counter get + ``` + + Returns the current value of 987. + + ``` bash + dfx canister call my_counter increment + dfx canister call my_counter get + ``` + + Returns the incremented value of 988. + +Unresolved directive in counter-tutorial.adoc - +include::example\$candid-ui.adoc\[\] + +\+ ![Counter functions](candid-counter.png) + +# Stop the local network {#_stop_the_local_network} + +After you finish experimenting with your program, you can stop the local +Internet Computer network so that it doesn't continue running in the +background. + +To stop the local network: + +1. In the terminal that displays network operations, press Control-C to + interrupt the local network process. + +2. Stop the Internet Computer network by running the following command: + + ``` bash + dfx stop + ``` diff --git a/modules/developers-guide/pages/tutorials/custom-frontend.text b/modules/developers-guide/pages/tutorials/custom-frontend.text new file mode 100644 index 000000000..93f6c7f06 --- /dev/null +++ b/modules/developers-guide/pages/tutorials/custom-frontend.text @@ -0,0 +1,438 @@ +--- +date: 2021-08-05 +title: Customize the front-end +--- + +Now that you have a basic understanding of how to create, build, and +deploy a simple program and are familiar with the default project files +and sample front-end, you might want to start experimenting with +different ways to customize the front-end user experience for your +project. + +This tutorial illustrates using a simple React framework to create a new +front-end for the default sample program and guides you through some +basic modifications to customize the interface displayed. Later +tutorials expand on the techniques introduced here, but if you already +know how to use CSS, HTML, JavaScript, and React or other frameworks to +build your user interface, you can skip this tutorial. + +::: note +This tutorial illustrates using the React framework to manage the +Document Object Model (DOM) for your canister. Because React has its own +custom DOM syntax, you need to modify the webpack configuration to +compile the front-end code, which is written in JSX. For more +information about learning to use React and JSX, see [Getting +started](https://reactjs.org/docs/getting-started.html) on the [React +website](https://reactjs.org/). +::: + +# Before you begin {#_before_you_begin} + +Before starting the tutorial, verify the following: + +- You have `node.js` installed for front-end development and can + install packages using `npm install` in your project. For + information about installing node for your local operating system + and package manager, see the [Node](https://nodejs.org/en/) website. + +- You have downloaded and installed the {sdk-short-name} package as + described in [Download and + install](../../quickstart/local-quickstart.xml#download-and-install). + +- You have installed the Visual Studio Code plugin for Motoko as + described in [Install the language editor + plug-in](../../quickstart/local-quickstart.xml#install-vscode) if + you are using Visual Studio Code as your IDE. + +- You have stopped any Internet Computer network processes running on + the local computer. + +::: note +Because of significant changes to the handling of HTTP requests and +front-end assets, this tutorial requires you to use the {sdk-short-name} +version `0.7.0` or later. For an overview of what's changed, see this +[article](../../http-middleware.xml). +::: + +This tutorial takes approximately 30 minutes to complete. + +# Create a new project {#_create_a_new_project} + +To create a new project directory for your custom front-end application: + +1. Open a terminal shell on your local computer, if you don't already + have one open. + +2. Change to the folder you are using for your Internet Computer + projects, if you are using one. + +3. Check that you have `node.js` installed locally by running the + following commands: + + ``` bash + which node + which npm + ``` + + If you don't have `node.js` installed, you should download and + install it before continuing to the next step. For information about + installing node for your local operating system and package manager, + see the [Node](https://nodejs.org/en/) website. + +4. Create a new project by running the following command: + + ``` bash + dfx new custom_greeting + ``` + + The `dfx new custom_greeting` command creates a new + `custom_greeting` project. + +5. Change to your project directory by running the following command: + + ``` bash + cd custom_greeting + ``` + +# Install the React framework {#_install_the_react_framework} + +If you've never used React before, you might want to explore the [Intro +to React](https://reactjs.org/tutorial/tutorial.html) tutorial or the +[React website](https://reactjs.org/) before editing the front-end code. + +To install required framework modules: + +1. Install the React module by running the following command: + + ``` bash + npm install --save react react-dom + ``` + +2. Install the required TypeScript language compiler loader by running + the following command: + + ``` bash + npm install --save-dev typescript ts-loader + ``` + + ::: note + As an alternative to installing these modules, you can edit the + default `package.json` file to add dependencies for your project. + ::: + + Unresolved directive in custom-frontend.adoc - include::example$custom-frontend-package.json[] + +# Review the default configuration {#_review_the_default_configuration} + +Before we make any changes to use React for this tutorial, let's review +the default front-end settings in the `dfx.json` configuration file for +your project. + +To review the default `dfx.json` configuration file: + +1. Open the `dfx.json` configuration file in a text editor. + +2. Notice that the `canisters` key includes settings for a + `custom_greeting_assets` canister. + + { + "canisters": { + ... + + "custom_greeting_assets": { + "dependencies": [ + "custom_greeting" + ], + "frontend": { + "entrypoint": "src/custom_greeting_assets/src/index.html" + }, + "source": [ + "src/custom_greeting_assets/assets", + "dist/custom_greeting_assets/" + ], + "type": "assets" + } + } + } + + Let's take a look at the settings in this section. + + - Front-end assets for your project are compiled into their own + canister, in this case, a canister named + `custom_greeting_assets`. + + - The assets canister has a default dependency on the main + canister for the project. + + - The `frontend.entrypoint` setting specifies the path to a + file---in this case, the `index.html` file---to use as your + application entry point. If you had a different starting + point---for example, a custom `first-page.html` file---you would + modify this setting. + + - The `source` settings specify the path to your `src` and `dist` + directories. The `src` setting specifies the directory to use + for static assets that will be included in your assets canister + when you build your project. If you have custom cascading + stylesheet (CSS) or JavaScript files, you would include them in + the folder specified by this path. After building the project, + the project assets are served from the directory specified by + the `dist` setting. + + - The `type` setting specifies that the `custom_greeting_assets` + is an asset canister rather than a program canister. + + For this tutorial, we are going to add React JavaScript in an + `index.jsx` file, but that won't require any changes to the default + settings in the `dfx.json` file. + +3. Close the `dfx.json` file to continue. + +# Review the default front-end files {#_review_the_default_front_end_files} + +For this tutorial, you are going to use the default `main.mo` program +and only manipulate the application by modifying the front-end. Before +you make any changes, though, let's take a look at what's in the default +front-end files for a project. + +To review the default front-end files: + +1. Open the `src/custom_greeting_assets/src/index.html` file in a text + editor. + + This template file is the default front-end entry point for the + application as specified by the `frontend.entrypoint` setting in the + `dfx.json` file. + + This file contains standard HTML with references to a CSS file and + an image that are located in the `src/custom_greeting_assets/assets` + directory. The default `index.html` file also includes standard HTML + syntax for displaying an input field for the `name` argument and a + clickable button. + + This is the same default front-end you saw in [Viewing the default + front-end](explore-templates.xml#default-frontend). + +2. Open the `src/custom_greeting_assets/src/index.js` file in a text + editor. + + import { custom_greeting } from "../../declarations/custom_greeting"; + + document.getElementById("clickMeBtn").addEventListener("click", async () => { + const name = document.getElementById("name").value.toString(); + // Interact with custom_greeting actor, calling the greet method + const greeting = await custom_greeting.greet(name); + + document.getElementById("greeting").innerText = greeting; + }); + + - The `import` statement points to an actor that will allow us to + make calls to our `custom_greeting` canister from + `"../declarations"` + + - The declarations haven't been created yet, but we will come back + to that. + +3. Close the `index.js` file to continue. + +# Modify the front-end files {#_modify_the_front_end_files} + +You are now ready to create a new front-end for the default program. + +To prepare the front-end files: + +1. Open the webpack configuration file (`webpack.config.js`) in a text + editor. + +2. Modify the front-end entry to replace the default `index.html` with + `index.jsx`. + + ``` js + entry: { + // The frontend.entrypoint points to the HTML file for this build, so we need + // to replace the extension to `.js`. + index: path.join(__dirname, asset_entry).replace(/\.html$/, ".jsx"), + }, + ``` + +3. Add the following `module` key above the `plugins` section: + + ``` json + module: { + rules: [ + { test: /\.(js|ts)x?$/, loader: "ts-loader" } + ] + }, + ``` + + This setting enables the program to use the `ts-loader` compiler for + a React JavaScript `index.jsx` file. Note that there's a commented + section in the default `webpack.config.js` file that you can modify + to add the `module` key. + +4. Create a new file named `tsconfig.json` in the root directory for + your project. + +5. Open the `tsconfig.json` file in a text editor, then copy and paste + the following into the file: + + ``` json + Unresolved directive in custom-frontend.adoc - include::example$sample-tsconfig.json[] + ``` + +6. Save your changes and close the `tsconfig.json` file to continue. + +7. Open the default `src/custom_greeting_assets/src/index.js` file in a + text editor and delete lines 2 to 9. + +8. Copy and paste the following sample code into the `index.js` file: + + ``` react + Unresolved directive in custom-frontend.adoc - include::example$react-index.jsx[] + ``` + +9. Rename the modified `index.js` file as `index.jsx` by running the + following command: + + ``` bash + mv src/custom_greeting_assets/src/index.js src/custom_greeting_assets/src/index.jsx + ``` + +10. Open the default `src/custom_greeting_assets/src/index.html` file in + a text editor, then replace the body contents with + `
`. + + For example: + + ``` html + + + + + + custom_greeting + + + + +
+ + + ``` + +# Start the local network {#_start_the_local_network} + +Before you can build the `custom_greeting` project, you need to connect +to the Internet Computer network either running locally in your +development environment or running remotely on a subnet that you can +access. + +To start the network locally: + +1. Open a new terminal window or tab on your local computer. + +2. Navigate to the root directory for your project, if necessary. + +3. Start the Internet Computer network on your local computer by + running the following command: + + ``` bash + dfx start --background + ``` + + After the local Internet Computer network completes its startup + operations, you can continue to the next step. + +# Register, build, and deploy the application {#_register_build_and_deploy_the_application} + +After you connect to the Internet Computer network running locally in +your development environment, you can register, build, and deploy your +application locally. + +To deploy the application locally: + +1. Check that you are still in the root directory for your project, if + needed. + +2. Register, build, and deploy your application by running the + following command: + + ``` bash + dfx deploy + ``` + + The `dfx deploy` command output displays information about the + operations it performs. + +# View the new front-end {#_view_the_new_front_end} + +You can now access the new front-end for the default program by entering +the canister identifier for the assets canister in a browser. + +To view the custom front-end: + +1. Open a new tab or window of your terminal and run + + ``` bash + npm start + ``` + +2. Open a browser and navigate to . + +3. Verify that you are prompted to type a greeting. + + For example: + + ![Sample front-end](react-greeting.png) + +4. Replace **Name** in the input field with the text you want to + display, then click **Get Greeting** to see the result. + + For example: + + ![Greeting result](greeting-response.png) + +# Revise the front-end and test your changes {#_revise_the_front_end_and_test_your_changes} + +After viewing the front-end, you might want to make some changes. + +To modify the front-end: + +1. Open the `index.jsx` file in a text editor and modify its style + settings. For example, you might want to change the font family and + use a placeholder for the input field by making changes similar to + the following: + + ``` react + Unresolved directive in custom-frontend.adoc - include::example$react-revised-index.jsx[] + ``` + +2. Save the file and view the updated page in your browser. + + For example: + + ![Modified styles on your entry page](revised-greeting.png) + +3. Type a new message and see your new greeting. For example: + + ![Modified greeting result](modified-result.png) + +# Stop the local network {#_stop_the_local_network} + +After you finish experimenting with the front-end for your program, you +can stop the local Internet Computer network so that it doesn't continue +running in the background. + +To stop the local network: + +1. In the terminal that displays the webpack development server, press + Control-C to interrupt the dev-server. + +2. In the terminal that displays network operations, press Control-C to + interrupt the local network process. + +3. Stop the Internet Computer network by running the following command: + + ``` bash + dfx stop + ``` diff --git a/modules/developers-guide/pages/tutorials/define-an-actor.text b/modules/developers-guide/pages/tutorials/define-an-actor.text new file mode 100644 index 000000000..6e4263feb --- /dev/null +++ b/modules/developers-guide/pages/tutorials/define-an-actor.text @@ -0,0 +1,316 @@ +--- +date: 2021-08-05 +title: Query using an actor +--- + +In the [Quick start](../../quickstart/quickstart-intro.xml), you had +your first look at a simple program for the Internet Computer involving +an actor object and asynchronous messaging. As the next step in learning +to write programs that take advantage of actor-based messaging, this +tutorial illustrates how to modify a traditional `Hello, World!` program +to define an actor, then deploy and test your program on a local +network. + +# Before you begin {#_before_you_begin} + +Before starting the tutorial, verify the following: + +- You have downloaded and installed the {sdk-short-name} package as + described in [Download and + install](../../quickstart/local-quickstart.xml#download-and-install). + +- You have stopped any Internet Computer network processes running on + the local computer. + +This tutorial takes approximately 20 minutes to complete. + +# Create a new project {#_create_a_new_project} + +To create a new project for this tutorial: + +1. Open a terminal shell on your local computer, if you don't already + have one open. + +2. Change to the folder you are using for your Internet Computer + projects, if you are using one. + +3. Create a new project by running the following command: + + ``` bash + dfx new actor_hello + ``` + +4. Change to your project directory by running the following command: + + ``` bash + cd actor_hello + ``` + +# Modify the default configuration {#_modify_the_default_configuration} + +In the [Exploring the default project](explore-templates.xml) tutorial, +you saw that creating a new project adds a default `dfx.json` +configuration file to your project directory. In this tutorial, you need +to modify a few of the default settings to reflect your project. + +To modify the `dfx.json` configuration file: + +1. Open the `dfx.json` configuration file in a text editor. + +2. Check the default settings for the `actor_hello` project. + +3. Notice that the names and paths to source and output files all use + the `actor_hello` project name. + + For example, the default canister name is `actor_hello` and the + default path to the main program file is `src/actor_hello/main.mo`. + + You can rename any of these files or directories. If you make any + changes, however, be sure that the names you use for your files and + directories on the file system match the names you specify in the + `dfx.json` configuration file. If you plan to use the default + directory and file names, no changes are necessary. + +4. Remove all of the `actor_hello_assets` configuration settings from + the file. + + The sample program for this tutorial doesn't use any front-end + assets, so you can remove those settings from the configuration + file. + + For example, the configuration file looks like this after you remove + the `actor_hello_assets` section: + + Unresolved directive in define-an-actor.adoc - include::example$define-actor-dfx.json[] + +5. Save your changes and close the file to continue. + +# Modify the default program {#_modify_the_default_program} + +In the [Exploring the default project](explore-templates.xml) tutorial, +you saw that creating a new project creates a default `src` directory +with a template `main.mo` file. In this tutorial, you modify the +template code to create a simple \"Hello, World!\" program that uses an +actor. + +To modify the default template source code: + +1. Change to the source code directory for your project by running the + following command: + + ``` bash + cd src/actor_hello + ``` + +2. Open the template `main.mo` file in a text editor and delete the + existing content. + + The next step is to write a program that prints a statement like the + traditional \"Hello, World!\" sample program. To compile the program + for the Internet Computer, however, your program must include an + `actor` object with a `public` function. + +3. Copy and paste the following sample code into the `main.mo` file: + + ``` motoko + Unresolved directive in define-an-actor.adoc - include::example$actor_hello.mo[] + ``` + + Let's take a closer look at this simple program: + + - The program imports a `Debug` module to provide the `print` + functionality. + + - The program uses the `public query func` to define a query + method because, in this case, the `actor_hello` program doesn't + make any changes to the state of the canister or perform any + operations that would update the data you are accessing. + + For more information about using a query call, see [query + calls](../concepts/canisters-code.xml#query-update) in [Canisters + include both program and + state](../concepts/canisters-code.xml#canister-state). + +4. Save your changes and close the `main.mo` file. + +# Build the program with a local identifier {#_build_the_program_with_a_local_identifier} + +You are probably only going to use this simple program for some local +testing. Therefore, there's no need to reserve a unique canister +identifier on the Internet Computer network to hold the compiled output +for the program. + +In this scenario, you can compile the program without connecting to an +Internet Computer network at all. Instead, the `dfx build` command +creates a local, hard-coded canister identifier for you to use. + +You can use this local identifier while you are testing your program or +any time you want to compile your program without starting the Internet +Computer replica process locally or connecting to a replica on a remote +subnet. + +To build the program executable: + +1. Navigate back to the root of your project directory. + +2. Build the program with a locally-defined identifier by running the + following command: + + ``` bash + dfx build --check + ``` + + The `--check` option enables you to build a project locally to + verify that it compiles and to inspect the files produced. Because + the `dfx build --check` command only generates a temporary + identifier, you should see output similar to the following: + + Building canisters to check they build ok. Canister IDs might be hard coded. + Building canisters... + + If the program compiles successfully, you can inspect the output in + the default `.dfx/local/canisters` directory and + `.dfx/local/canisters/actor_hello/` subdirectory. + + For example, you might use the `tree` command to review the files + created: + + ``` bash + tree .dfx/local/canisters + ``` + + The command displays output similar to the following + +```{=html} + +``` + .dfx/local/canisters + ├── actor_hello + │   ├── actor_hello.d.ts + │   ├── actor_hello.did + │   ├── actor_hello.did.js + │   ├── actor_hello.js + │   └── actor_hello.wasm + └── idl + + 2 directories, 5 files + +# Deploy the project {#_deploy_the_project} + +You cannot deploy the output from the `dfx build --check` command to any +Internet Computer network. If you wanted to deploy this project, you +would need to do the following: + +- Connect to the Internet Computer network. + +- Register a network-specific canister identifier. + +- Deploy the canister. + +Let's consider these steps in a bit more detail. Before you can deploy +this project, you must connect to the Internet Computer network either +running **locally** in your development environment or running +**remotely** on a subnet that you can access. After you connect to a +local or remote network, you must also generate a unique, +**network-specific** canister identifier to replace your locally-defined +identifier. To see the steps involved for yourself, let's deploy the +project locally. + +To deploy this project locally: + +1. Open a terminal and navigate to your project directory, if needed. + +2. Start the Internet Computer network on your local computer by + running the following command: + + ``` bash + dfx start --background + ``` + + For this tutorial, you can use the `--background` option to start + the Internet Computer network as background processes. With this + option, you can continue to the next step without opening another + terminal shell on your local computer. + +3. Generate a new canister identifier for your project on the local + Internet Computer network by running the following command: + + ``` bash + dfx canister create actor_hello + ``` + + You should see output similar to the following: + + Creating a wallet canister on the local network. + The wallet canister on the "local" network for user "pubs-id" is "rwlgt-iiaaa-aaaaa-aaaaa-cai" + Creating canister "actor_hello"... + "actor_hello" canister created with canister id: "rrkah-fqaaa-aaaaa-aaaaq-cai" + + The `dfx canister create` command also stores the network-specific + canister identifier in a `canister_ids.json` file in the + `.dfx/local` directory. + + For example: + + { + "actor_hello": { + "local": "rrkah-fqaaa-aaaaa-aaaaq-cai" + } + } + +4. Deploy your `actor_hello` project on the local network by running + the following command: + + ``` bash + dfx canister install actor_hello + ``` + + The command displays output similar to the following: + + Installing code for canister actor_hello, with canister_id rrkah-fqaaa-aaaaa-aaaaq-cai + +# Query the canister {#_query_the_canister} + +You now have a program deployed as a **canister** on your local Internet +Computer network and can test your program by using the +`dfx canister call` command. + +To test the program you have deployed on the local network: + +1. Use `dfx canister call` to call the `hello` function by running the + following command: + + ``` bash + dfx canister call actor_hello hello + ``` + +2. Verify that the command returns the text specified for the `hello` + function along with a checkpoint message in the terminal running the + local network process. + + For example, the program displays \"Hello, World from DFINITY\" in + output similar to the following: + + [Canister rrkah-fqaaa-aaaaa-aaaaq-cai] Hello, World from DFINITY + + Note that if you are running the Internet Computer network in a + separate terminal instead of in the background, the \"Hello, World + from DFINITY\" message is displayed in the terminal that displays + network activity. + +# Stop the local network {#_stop_the_local_network} + +After you finish experimenting with your program, you can stop the local +Internet Computer network so that it doesn't continue running in the +background. + +To stop the local network: + +1. In the terminal that displays network operations, press Control-C to + interrupt the local network process. + +2. Stop the Internet Computer network by running the following command: + + ``` bash + dfx stop + ``` diff --git a/modules/developers-guide/pages/tutorials/explore-templates.text b/modules/developers-guide/pages/tutorials/explore-templates.text new file mode 100644 index 000000000..bb65ac25c --- /dev/null +++ b/modules/developers-guide/pages/tutorials/explore-templates.text @@ -0,0 +1,553 @@ +--- +date: 2021-08-05 +title: Explore the default project +--- + +If you started your tour of the {sdk-long-name} with the [Quick +start](../../quickstart/quickstart-intro.xml), you have already seen the +basic work flow for creating applications that run on the Internet +Computer. Now, let's take a closer look at that work flow by exploring +the default files and folders that are added to your workspace when you +create a new project. + +As a preview, the following diagram illustrates the development work +flow when running the Internet Computer locally on you computer. + +![Development work flow](dev-workflow-explore.svg) + +# Before you begin {#_before_you_begin} + +Before you start this tutorial, verify the following: + +- You have an internet connection and access to a shell terminal on + your local macOS or Linux computer. + +- You have `node.js` installed if you want to include the default + template files for front-end development in your project. + +- You have downloaded and installed the {sdk-short-name} package as + described in [Download and + install](../../quickstart/local-quickstart.xml#download-and-install). + +- You have installed the Visual Studio Code plugin for Motoko as + described in [Install the language editor + plug-in](../../quickstart/local-quickstart.xml#install-vscode) if + you are using Visual Studio Code as your IDE. + +- You have stopped any Internet Computer network processes running on + the local computer. + +This tutorial takes approximately 20 minutes to complete. + +# Create a new project + +As discussed in the [Quick +start](../../quickstart/quickstart-intro.xml), applications for the +Internet Computer start as **projects** that you create. You can create +projects using the `dfx` executable command-line interface (CLI). + +To take a closer look at the files and folders that are included in a +project by default, let's create a new project to work with. + +To create a new project: + +1. Open a terminal shell on your local computer, if you don't already + have one open. + +2. Navigate to the folder you are using for your Internet Computer + projects, if you are using a separate working folder. + +3. Create a new project by running the following command: + + ``` bash + dfx new explore_hello + ``` + + The `dfx new explore_hello` command creates a new `explore_hello` + project, including a default project directory structure under the + new project name and a new Git repository for your project. If you + have `node.js` installed locally, creating a new project also adds + some template front-end code and dependencies. + + To ensure that project names are valid when used in JavaScript, + Motoko, and other contexts, you should only use alphanumeric + characters and underscores. You cannot include dashes or any special + characters. + +4. View the default directory structure by running the following + command: + + ``` bash + ls -l explore_hello + ``` + + By default, the project directory structure includes at least one + source subdirectory, a template `README.md` file, and a default + `dfx.json` configuration file. + + Depending on whether you have `node.js` installed, your project + directory might include some or all of the following files: + + explore_hello/ + ├── README.md # default project documentation + ├── dfx.json # project configuration file + ├── node_modules # libraries for front-end development + ├── package-lock.json + ├── package.json + ├── src # source files directory + │   ├── explore_hello + │   │   └── main.mo + │   └── explore_hello_assets + │   ├── assets + │   │   ├── logo.png + │   │   ├── main.css + │   │   └── sample-asset.txt + │   └── src + │   ├── index.html + │   └── index.js + └── webpack.config.js + + At a minimum, the default project directory includes the following + folders and files: + + - A default `README` file for documenting your project in the + repository. + + - A default `dfx.json` configuration file to set configurable + options for your project. + + - A default `src` directory for all of the source files required + by your application. + + The default `src` directory includes a template `main.mo` file that + you can modify or replace to include your core programming logic. + + Because this tutorial focuses on the basics of getting started, you + are only going to use the `main.mo` file. If you have `node.js` + installed, your project directory includes additional files and + directories that you can use to define the front-end interface for + your application. Front-end development and the template files in + the `assets` folder are discussed a little later. + +# Review the default configuration {#_review_the_default_configuration} + +By default, creating a new project adds some template files to your +project directory. You can edit these template files to customize the +configuration settings for your project and to include your own code to +speed up the development cycle. + +To review the default configuration file for your project: + +1. Open a terminal shell on your local computer, if you don't already + have one open. + +2. Change to your project directory by running the following command: + + ``` bash + cd explore_hello + ``` + +3. Open the `dfx.json` configuration file in a text editor to review + the default settings. + + For example: + + Unresolved directive in explore-templates.adoc - include::example$sample-explore-dfx.json[] + + Let's take a look at a few of the default settings. + + - The `canisters` section specifies the name of the WebAssembly + module for your `explore_hello` project is `explore_hello`. + + - The `canisters.explore_hello` key specifies that the main + program to be compiled is located in the path specified by the + `main` setting, in this case, `src/explore_hello/main.mo` and + the `type` setting indicates that this is a `motoko` program. + + - The `canisters.explore_hello_assets` key specifies configuration + details about front-end assets for this project. Let's skip + those for now. + + - The `dfx` setting is used to identify the version of the + software used to create the project. + + - The `networks` section specifies information about the networks + to which you connect. The default settings bind the local + Internet Computer network to the local host address `127.0.0.1` + and port `8000`. + + If you have access to other Internet Computer network providers, + the `networks` section can include network aliases and URLs for + connecting to those providers. + + You can leave the default settings as they are. + +4. Close the `dfx.json` file to continue. + +# Review the default program code {#_review_the_default_program_code} + +New projects always include a template `main.mo` source code file. You +can edit this file to include your own code to speed up the development +cycle. + +Let's take a look at the sample program in the default `main.mo` +template file as a starting point for creating simple program using the +Motoko programming language. + +To review the default sample program for your project: + +1. Check that you are still in your project directory by running the + following command: + + ``` bash + pwd + ``` + +2. Open the `src/explore_hello/main.mo` file in a text editor and + review the code in the template: + + actor { + public func greet(name : Text) : async Text { + return "Hello, " # name # "!"; + }; + }; + + Let's take a look at a few key elements of this program: + + - You might notice that this sample code defines an `actor` + instead of a `main` function, which some programming languages + require. For Motoko, the `main` function is implicit in the file + itself. + + - Although the traditional \"Hello, World!\" program illustrates + how you can print a string using a `print` or `println` + function, that traditional program would not represent a typical + use case for Motoko programs that run on the Internet Computer. + + - Instead of a print function, this sample program defines an + `actor` with a public `greet` function that takes a `name` + argument with a type of `Text`. + + - The program then uses the `async` keyword to indicate that the + program returns an asynchronous message consisting of a + concatenated text string constructed using `"Hello, "`, the `#` + operator, the `name` argument, and `"!"`. + + We'll explore code that uses `actor` objects and asynchronous + message handling more a little later. For now, you can continue to + the next section. + +3. Close the `main.mo` file to continue. + +# Start the local network + +Before you can build the default project, you need to connect to the +Internet Computer network either running **locally** in your development +environment or running **remotely** on a subnet that you can access. + +Starting the network locally requires a `dfx.json` file, so you should +be sure you are in your project's root directory. For this tutorial, you +should have two separate terminal shells, so that you can start and see +network operations in one terminal and manage your project in another. + +To start the network locally: + +1. Open a new terminal window or a new terminal tab on your local + computer. + +2. Navigate to the root directory for your project, if necessary. + + - You should now have **two terminals** open. + + - You should have the **project directory** as your **current + working directory**. + +3. Start the Internet Computer network on your local computer by + running the following command: + + ``` bash + dfx start + ``` + + Depending on your platform and local security settings, you might + see a warning displayed. If you are prompted to allow or deny + incoming network connections, click **Allow**. + + After you start the local network, you have one terminal that + displays messages about network operations and another for + performing project-related tasks. + +4. Leave the terminal that displays network operations open and switch + your focus to the terminal where you created your new project. + +# Register canister identifiers {#_register_canister_identifiers} + +After you connect to the Internet Computer network running locally in +your development environment, you can register with the network to +generate unique, network-specific **canister identifiers** for your +project. + +In the [Quick start](../../quickstart/quickstart-intro.xml) tutorial, +this step was performed as part of the `dfx deploy` command work flow. +This tutorial demonstrates how to perform each of the operations +independently. + +To register canister identifiers for the local network: + +1. Check that you are still in your project directory, if needed. + +2. Register unique canister identifiers for the canisters in the + project by running the following command: + + ``` bash + dfx canister create --all + ``` + + The command displays the network-specific canister identifiers for + the canisters defined in the `dfx.json` configuration file. + + Creating a wallet canister on the local network. + The wallet canister on the "local" network for user "pubs-id" is "rwlgt-iiaaa-aaaaa-aaaaa-cai" + Creating canister "explore_hello"... + "explore_hello" canister created with canister id: "rrkah-fqaaa-aaaaa-aaaaq-cai" + Creating canister "explore_hello_assets"... + "explore_hello_assets" canister created with canister id: "ryjl3-tyaaa-aaaaa-aaaba-cai" + + Because you are connected to the Internet Computer network running + locally, these canister identifiers are only valid locally and are + stored for the project in the `.dfx/local/canister_ids.json` file. + + For example: + + { + "explore_hello": { + "local": "rrkah-fqaaa-aaaaa-aaaaq-cai" + }, + "explore_hello_assets": { + "local": "ryjl3-tyaaa-aaaaa-aaaba-cai" + } + } + +# Build the program {#_build_the_program} + +Now that you have explored the default configuration settings and +program code and have started the Internet Computer network, let's +compile the default program into an executable WebAssembly module. + +To build the program executable: + +1. In the terminal shell on your local computer, navigate to your + `explore_hello` project directory. + + You must run the `dfx build` command from within the project + directory structure. + +2. Build the executable canister by running the following command: + + ``` bash + dfx build + ``` + + You should see output similar to the following: + + Building canisters... + Building frontend... + + Because you are connected to the Internet Computer network running + locally, the `dfx build` command adds the `canisters` directory + under the `.dfx/local/` directory for the project. + +3. Verify that the `.dfx/local/canisters/explore_hello` directory + created by the `dfx build` command contains the WebAssembly and + related application files by running the following command. + + ``` bash + ls -l .dfx/local/canisters/explore_hello/ + ``` + + For example, the command returns output similar to the following: + + -rw-r--r-- 1 pubs staff 178 Apr 6 14:25 explore_hello.d.ts + -rw-r--r-- 1 pubs staff 41 Apr 6 14:25 explore_hello.did + -rw-r--r-- 1 pubs staff 155 Apr 6 14:25 explore_hello.did.js + -rw-r--r-- 1 pubs staff 142 Apr 6 14:25 explore_hello.js + -rw-r--r-- 1 pubs staff 157613 Apr 6 14:25 explore_hello.wasm + + The `canisters/explore_hello` directory contains the following key + files: + + - The `explore_hello.did` file contains an interface description + for your main program. + + - The `explore_hello.did.js` file contains a JavaScript + representation of the canister interface for the functions in + your program. + + - The `explore_hello.js` file contains a JavaScript representation + of the canister interface for your program. + + - The `explore_hello.wasm` file contains the compiled WebAssembly + for the assets used in your project. + + The `canisters/explore_hello_assets` directory contains similar + files to describe the front-end assets associated with your project. + + In addition to the files in the `canisters/explore_hello` and the + `canisters/explore_hello_assets` directories, the `dfx build` + command creates an `idl` directory. + +4. Verify that a new folder has been created, `src/declarations`. + + This folder will include copies of the folders from `.dfx/local`, + except for the wasm. They do not contain any secrets, and we + recommend committing these files along with the rest of your source + code. + +# Deploy the project locally {#_deploy_the_project_locally} + +You've seen that the `dfx build` command creates several artifacts in a +`canisters` directory for your project. The WebAssembly modules and the +`canister_manifest.json` file are required for your program to be +deployed on the Internet Computer network. + +To deploy locally: + +1. In a terminal shell on your local computer, navigate to your + `explore_hello` project directory. + +2. Deploy your `explore_hello` project on the local network by running + the following command: + + ``` bash + dfx canister install --all + ``` + + The command displays output similar to the following: + + Installing code for canister explore_hello, with canister_id rrkah-fqaaa-aaaaa-aaaaq-cai + Installing code for canister explore_hello_assets, with canister_id ryjl3-tyaaa-aaaaa-aaaba-cai + Authorizing our identity (pubs-id) to the asset canister... + Uploading assets to asset canister... + /index.html 1/1 (480 bytes) + /index.js 1/1 (296836 bytes) + /main.css 1/1 (484 bytes) + /sample-asset.txt 1/1 (24 bytes) + /logo.png 1/1 (25397 bytes) + /index.js.map 1/1 (964679 bytes) + /index.js.LICENSE.txt 1/1 (499 bytes) + +3. Run the `dfx canister call` command and specify the program and + function to call by running the following command: + + ``` bash + dfx canister call explore_hello greet '("everyone": text)' + ``` + + This command specifies: + + - `explore_hello` as the name of the *canister* or application + service you want to call. + + - `greet` as the specific *method* or function you want to call. + + - `everyone` as the argument to pass to the `greet` function. + +4. Verify the command displays the return value of the `greet` + function. + + For example: + + ("Hello, everyone!") + +# View the default front-end {#default-frontend} + +If you have `node.js` installed in your development environment, your +project includes a simple front-end example that uses a template +`index.js` JavaScript file for accessing the `explore_hello` program in +a browser. + +To explore the default front-end template: + +1. Open a terminal shell on your local computer, if you don't already + have one open, and navigate to your `explore_hello` project + directory. + +2. Open the `src/explore_hello_assets/src/index.js` file in a text + editor and review the code in the template script: + + import { explore_hello } from "../../declarations/explore_hello"; + + document.getElementById("clickMeBtn").addEventListener("click", async () => { + const name = document.getElementById("name").value.toString(); + // Interact with explore_hello actor, calling the greet method + const greeting = await explore_hello.greet(name); + + document.getElementById("greeting").innerText = greeting; + }); + + The template `index.js` imports an `explore_hello` agent from our + newly created `declarations` directory. The agent is automatically + configured to interact with the interface we created in `Main.mo`, + and makes calls to our Canister using an `AnonymousIdentity` when + the user clicks the `greeting` button. + + This file works in conjunction with the template `index.html` file + to display an HTML page with an image asset, input field, and button + for the `greet` function. + +3. Close the `index.js` file to continue. + +4. View the front-end assets created for the project by running + following command: + + ``` bash + ls -l .dfx/local/canisters/explore_hello_assets/ + ``` + + The command displays output similar to the following: + + drwxr-xr-x 9 pubs staff 288 Apr 6 14:25 assets + -r--r--r-- 1 pubs staff 2931 Dec 31 1969 assetstorage.did + -r--r--r-- 1 pubs staff 265823 Dec 31 1969 assetstorage.wasm + -rw-r--r-- 1 pubs staff 3651 Apr 6 14:25 explore_hello_assets.d.ts + -rw-rw-rw- 1 pubs staff 2931 Dec 31 1969 explore_hello_assets.did + -rw-r--r-- 1 pubs staff 4236 Apr 6 14:25 explore_hello_assets.did.js + -rw-r--r-- 1 pubs staff 149 Apr 6 14:25 explore_hello_assets.js + -rw-rw-rw- 1 pubs staff 265823 Dec 31 1969 explore_hello_assets.wasm + + These files were generated automatically by the `dfx build` command + using node modules and the template `index.js` file. + +5. Start a development server with `npm start`. + +6. Open a browser and navigate to the `local` network address and port + number---`+127.0.0.1:8080` + +7. Verify that you see the HTML page for the sample application. + + For example: + + ![Sample HTML entry page](explore-hello.png) + +8. Type a greeting, then click **Click Me** to return the greeting. + + For example: + + ![Return the name argument](greeting.png) + +# Stop the local network {#_stop_the_local_network} + +After you finish experimenting with your program, you can stop the local +Internet Computer network so that it doesn't continue running in the +background. + +To stop the local network: + +1. In the terminal that displays network operations, press Control-C to + interrupt the local network process. + +2. Stop the Internet Computer network by running the following command: + + ``` bash + dfx stop + ``` diff --git a/modules/developers-guide/pages/tutorials/hello-location.text b/modules/developers-guide/pages/tutorials/hello-location.text new file mode 100644 index 000000000..ccaab69a5 --- /dev/null +++ b/modules/developers-guide/pages/tutorials/hello-location.text @@ -0,0 +1,330 @@ +--- +date: 2021-08-05 +title: Pass text arguments +--- + +This tutorial provides a simple variation on the default program that +lets you pass a single text argument to a single actor, compile the code +to create a canister, then retrieve the argument. + +This tutorial illustrates how to pass arguments on the command-line in a +terminal using the Candid interface description language (IDL) and how +to modify the program to allow it to accept more than one value for the +text argument. + +# Before you begin {#_before_you_begin} + +Before you start this tutorial, verify the following: + +- You have downloaded and installed the {sdk-short-name} package as + described in [Download and + install](../../quickstart/local-quickstart.xml#download-and-install). + +- You have stopped any Internet Computer network processes running on + the local computer. + +This tutorial takes approximately 20 minutes to complete. + +# Create a new project {#_create_a_new_project} + +To create a new project for this tutorial: + +1. Open a terminal shell on your local computer, if you don't already + have one open. + +2. Change to the folder you are using for your Internet Computer + projects, if you are using one. + +3. Create a new project by running the following command: + + ``` bash + dfx new location_hello + ``` + +4. Change to your project directory by running the following command: + + ``` bash + cd location_hello + ``` + +# Modify the default configuration {#_modify_the_default_configuration} + +In the [Explore the default project](explore-templates.xml) tutorial, +you saw that creating a new project adds a default `dfx.json` +configuration file to your project directory. You should always review +the default settings in the file to verify the information accurately +reflects the project settings you want to use. For this tutorial, you'll +modify the default configuration to remove settings that aren't used. + +To modify settings in the `dfx.json` configuration file: + +1. Open the `dfx.json` configuration file in a text editor. + +2. Check the default settings for the `location_hello` project. + +3. Remove all of the unnecessary configuration settings. + + Because this tutorial does not involve creating any front-end + assets, you can remove all of the `location_hello_assets` + configuration settings from the file. + +4. Save your changes and close the file to continue. + +# Modify the default program {#_modify_the_default_program} + +In the [Explore the default project](explore-templates.xml) tutorial, +you saw that creating a new project creates a default `src` directory +with a template `main.mo` file. + +To modify the default template source code: + +1. Open the `src/location_hello/main.mo` source code file in a text + editor. + +2. Modify the default source code to replace the `greet` function with + a `location` function and the `name` argument with a `city` + argument. + + For example: + + ``` motoko + Unresolved directive in hello-location.adoc - include::example$location_hello.mo[] + ``` + +3. Save your changes and close the file to continue. + +# Start the local network {#_start_the_local_network} + +Before you can build your project, you need to connect to the Internet +Computer network either running locally in your development environment +or running remotely on a subnet that you can access. + +Starting the network locally requires a `dfx.json` file, so you should +be sure you are in your project's root directory. For this tutorial, you +should have two separate terminal shells, so that you can start and see +network operations in one terminal and manage your project in another. + +To start the local network: + +1. Open a new terminal window or tab on your local computer. + +2. Navigate to the root directory for your project, if necessary. + + - You should now have **two terminals** open. + + - You should have the **project directory** as your **current + working directory**. + +3. Start the Internet Computer network on your local computer by + running the following command: + + ``` bash + dfx start + ``` + + If you are prompted to allow or deny incoming network connections, + click **Allow**. + +4. Leave the terminal that displays network operations open and switch + your focus to your original terminal where you created your project. + +# Register, build, and deploy the application {#_register_build_and_deploy_the_application} + +After you connect to the Internet Computer network running locally in +your development environment, you can register, build, and deploy your +application locally. + +To deploy the application locally: + +1. Check that you are still in the root directory for your project, if + needed. + +2. Register, build, and deploy your application by running the + following command: + + ``` bash + dfx deploy + ``` + + The `dfx deploy` command output displays information about the + operations it performs. + +# Pass a text argument {#_pass_a_text_argument} + +You now have a program deployed as a **canister** on your local Internet +Computer network and can test your program by using `dfx canister call` +commands. + +To test the program you have deployed locally: + +1. Call the `location` method in the program and pass your `city` + argument of type `text` by running the following command: + + ``` bash + dfx canister call location_hello location "San Francisco" + ``` + + Because the argument in this case includes a space between `San` and + `Francisco`, you need to enclose the argument in quotes. The command + displays output similar to the following: + + ("Hello, San Francisco!") + + If the argument did not contain a space that required enclosing the + text inside of quotation marks, you could allow the Candid interface + description language to infer the data type like this: + + ``` bash + dfx canister call location_hello location Paris + ``` + + Candid infers the data type as `Text` and returns the output from + your program as text like this: + + ("Hello, Paris!") + +2. Call the `location` method in the program and pass your `city` + argument explicitly using the Candid interface description language + syntax for Text arguments: + + ``` bash + dfx canister call location_hello location '("San Francisco and Paris")' + ``` + + The command displays output similar to the following: + + ("Hello, San Francisco and Paris!") + + Because your program only accepts a single text argument, specifying + multiple strings returns only the first argument. + + For example, if you try this command: + + ``` bash + dfx canister call location_hello location '("San Francisco","Paris","Rome")' + ``` + + Only the first argument---`("Hello, San Francisco!")`---is returned. + +# Revise the source code in your program {#_revise_the_source_code_in_your_program} + +To extend what you have learned in this tutorial, you might want to try +modifying the source code to return different results. For example, you +might want to modify the `location` function to return multiple city +names. + +To experiment with modifying the source code for this tutorial: + +1. Open the `dfx.json` configuration file in a text editor and change + the default `location_hello` settings to `favorite_cities`. + + For this step, you should modify both the canister name and the path + to the main program for the canister to use `favorite_cities`. + +2. Save your changes and close the `dfx.json` file to continue. + +3. Copy the `location_hello` source file directory to match the name + specified in the `dfx.json` configuration file by running the + following command: + + ``` bash + cp -r src/location_hello src/favorite_cities + ``` + +4. Open the `src/favorite_cities/main.mo` file in a text editor. + +5. Copy and paste the following code sample to replace the `location` + function with two new functions. + + For example: + + ``` motoko + Unresolved directive in hello-location.adoc - include::example$favorite_cities.mo[] + ``` + + You might notice that `Text` in this code example is enclosed by + square (`[ ]`) brackets. By itself, `Text` represents a collection + of UTF-8 characters. The square brackets around a type indicate that + it is an **array** of that type. In this context, therefore, + `[Text]` indicates an array of a collection of UTF-8 characters, + enabling the program to accept and return multiple text strings. + + The code sample also uses the basic format of an `apply` operation + for the array, which can be abstracted as: + + public func apply(fs : [A -> B], xs : [A]) : [B] { + var ys : [B] = []; + for (f in fs.vals()) { + ys := append(ys, map(f, xs)); + }; + ys; + }; + + For information about the functions that perform operations on + arrays, see the description of the Array module in the Motoko base + library or the *Motoko Programming Language Reference*. For another + example focused on the use of arrays, see + [Quicksort](https://github.com/dfinity/examples/tree/master/motoko/quicksort) + in the [examples](https://github.com/dfinity/examples/) repository. + +6. Register, build, and deploy the application by running the following + command: + + ``` bash + dfx deploy + ``` + +7. Call the `location` method in the program and pass your `city` + argument using the Candid interface description syntax by running + the following command: + + ``` bash + dfx canister call favorite_cities location '(vec {"San Francisco";"Paris";"Rome"})' + ``` + + The command uses the Candid interface description syntax + `(vec { val1; val2; val3; })` to return a vector of values. For more + information about the Candid interface description language, see the + [Candid](../../candid-guide/candid-intro.xml) language guide. + + This command displays output similar to the following: + + ("Hello, from ["San Francisco", "Paris", "Rome"]!") + +8. Call the `location_pretty` method in the program and pass your + `city` argument using the interface description syntax by running + the following command: + + ``` bash + dfx canister call favorite_cities location_pretty '(vec {"San Francisco";"Paris";"Rome"})' + ``` + + The command displays output similar to the following: + + ("Hello from San Francisco, Paris, Rome, bon voyage!") + +Unresolved directive in hello-location.adoc - +include::example\$candid-ui.adoc\[\] + +\+ In this example, each function accepts an array of text strings. +Therefore, you first select the length of the array, then set values for +each item before clicking **Call**. + +\+ ![Specifying an array](candid-favorite-cities-result.png) + +# Stop the local network {#_stop_the_local_network} + +After you finish experimenting with your program, you can stop the local +Internet Computer network so that it doesn't continue running in the +background. + +To stop the local network: + +1. In the terminal that displays network operations, press Control-C to + interrupt the local network process. + +2. Stop the Internet Computer network by running the following command: + + ``` bash + dfx stop + ``` diff --git a/modules/developers-guide/pages/tutorials/intercanister-calls.text b/modules/developers-guide/pages/tutorials/intercanister-calls.text new file mode 100644 index 000000000..12ef3c593 --- /dev/null +++ b/modules/developers-guide/pages/tutorials/intercanister-calls.text @@ -0,0 +1,481 @@ +--- +date: 2021-08-05 +title: Make inter-canister calls +--- + +One of the most important features of the Internet Computer for +developers is the ability to build, deploy, and call shared functions in +one canister from a program in another canister. This capability to make +calls between canisters---also sometimes referred to as **inter-canister +calls**---enables you to reuse and share functionality in multiple +applications. + +For example, you might want to create an application for professional +networking, organizing community events, or hosting fundraising +activities. Each of these applications might have a social component +that enables users to identify social relationships based on some +criteria or shared interest, such as friends and family or current and +former colleagues. + +To address this social component, you might want to create a single +canister for storing user relationships then write your professional +networking, community organizing, or fundraising application to import +and call functions that are defined in the canister for social +connections. You could then build additional applications to use the +social connections canister or extend the features provided by the +social connections canister to make it useful to an even broader +community of other developers. + +The Motoko-based LinkedUp sample application provides a simple +implementation of an open professional network that demonstrates how to +use inter-canister calls within a project. + +The LinkedUp sample application is implemented using the following +canisters: + +- The `linkedup` canister creates and stores basic profile information + for a user, including work experience and educational background. + +- The `connectd` canister creates and stores a user's connections. + +- The `linkedup_assets` canister stores the front-end + assets---including the JavaScript, HTML, and CSS files---that define + the user interface + +# Before you begin {#_before_you_begin} + +Before building the sample application, verify the following: + +- You have downloaded and installed the {sdk-short-name} package as + described in [Download and + install](../../quickstart/local-quickstart.xml#download-and-install). + +- You have stopped any Internet Computer network processes running on + the local computer. + +# Download the demo {#_download_the_demo} + +To experiment with inter-canister calls using the LinkedUp sample +application: + +1. Open a terminal shell and change to the folder you are using for + your Internet Computer sample projects. + +2. Clone the `linkedup` repository. + + ``` bash + git clone https://github.com/dfinity/linkedup.git + ``` + +3. Change to the local working directory for the `linkedup` repository. + + ``` bash + cd linkedup + ``` + +4. Install node modules by running the following command: + + ``` bash + npm install + ``` + + If necessary, fix any vulnerabilities found by running the following + command: + + ``` bash + npm audit fix + ``` + +5. Open the `dfx.json` file in a text editor and verify the `dfx` + setting has same the version number as the `dfx` executable you have + installed. + +# Start the local network {#_start_the_local_network} + +Before you can build the `linkedup` project, you need to connect to the +Internet Computer network either running locally in your development +environment or running remotely on a subnet that you can access. + +To start the network locally: + +1. Open a new terminal window or tab on your local computer. + +2. Navigate to the root directory for your project, if necessary. + +3. Start the Internet Computer network on your local computer by + running the following command: + + ``` bash + dfx start --background + ``` + + After the local Internet Computer network completes its startup + operations, you can continue to the next step. + +# Register canister identifiers {#_register_canister_identifiers} + +After you connect to the Internet Computer network running locally in +your development environment, you can register with the network to +generate unique canister identifiers for your project. + +To register canister identifiers for the local network: + +1. Check that you are still in your project directory, if needed. + +2. Register unique canister identifiers for the project by running the + following command: + + ``` bash + dfx canister create --all + ``` + + The command displays the network-specific canister identifiers for + the canisters defined in the `dfx.json` configuration file. + + "connectd" canister created with canister id: "75hes-oqbaa-aaaaa-aaaaa-aaaaa-aaaaa-aaaaa-q" + "linkedup" canister created with canister id: "cxeji-wacaa-aaaaa-aaaaa-aaaaa-aaaaa-aaaaa-q" + "linkedup_assets" canister created with canister id: "7kncf-oidaa-aaaaa-aaaaa-aaaaa-aaaaa-aaaaa-q" + + Keep in mind that because you are running the Internet Computer + locally, these identifiers are only valid on the local network. To + deploy canisters on a remote network, you must connect to that + network using the `--network` command-line option and a specific + network name or address to register identifiers on that network. + +# Build and deploy the demo project {#_build_and_deploy_the_demo_project} + +To build and deploy the LinkUp sample application, take the following +steps: + +1. Check that you are still in your project directory by running the + `pwd` command, if necessary. + +2. Build the LinkedUp canisters by running the following command: + + ``` bash + dfx build + ``` + +3. Deploy the project on the local network by running the following + command: + + ``` bash + dfx canister install --all + ``` + + You should see canister identifiers for the `connectd`, `linkedup` + and `linkedup_assets` canisters with a message similar to the + following: + + Installing code for canister connectd, with canister_id 75hes-oqbaa-aaaaa-aaaaa-aaaaa-aaaaa-aaaaa-q + Installing code for canister linkedup, with canister_id cxeji-wacaa-aaaaa-aaaaa-aaaaa-aaaaa-aaaaa-q + Installing code for canister linkedup_assets, with canister_id 7kncf-oidaa-aaaaa-aaaaa-aaaaa-aaaaa-aaaaa-q + +4. Copy the `linkedup_assets` canister identifier returned by the + `dfx canister install` command. + + In this sample application, only the `linkedup_assets` canister + includes the front-end assets used to access the application's + features. To open the application in a browser, therefore, you need + to specify the `linkedup_assets` canister identifier. + +5. Open the `linkedup_assets` canister in your web browser. + + For example, if binding to the default localhost address and port + number, the URL looks similar to this: + + http://127.0.0.1:8000/?canisterId=7kncf-oidaa-aaaaa-aaaaa-aaaaa-aaaaa-aaaaa-q + +# Create a profile and connections {#_create_a_profile_and_connections} + +To run through a demonstration of the LinkedUp sample application, take +the following steps: + +1. Open a browser tab or window. + +2. Type the web server host name, port, and the `canisterId` keyword, + then paste the `linkedup_assets` canister identifier as the URL to + display. + + 127.0.0.1:8000/?canisterId= + + The browser displays an introductory page. + + A public-private key pair will be automatically generated to + establish your identity for accessing the canister, so there's no + need to provide a user name and password or register an account to + store your identity before using the service. + +3. Click **Login**. + + The browser displays an empty profile page. + + ![linkedup empty maya](linkedup-empty-maya.png) + +4. Click **Edit**, type profile information, copy and paste the image + address for an avatar photo, then click **Submit**. + + ![linkedup edit maya](linkedup-edit-maya.png) + + After you click **Submit**, you have a profile with some work + history that can be viewed. + + For example: + + ![linkedup profile maya](linkedup-profile-maya.png) + +## Add another profile {#_add_another_profile} + +At this point, there are no other profiles to search for or to add as +connections. To try out the Search and Connect features, you can: + +- Run a script that populates the sample application with some + additional profiles. + +- Create a profile manually by opening a private window. + +For this tutorial, you will create another profile manually. + +To add a user profile with different identity: + +1. At the top right of the browser window, click the appropriate icon + to display the browser's menu options. + + For example, if you are using Google Chrome, click the vertical + ellipse to display the More menu. + +2. Click **New Incognito Window** if you are using Google Chrome or + **New Private Window** if you are using Firefox to enable you to + navigate to the canister without the user identity generated in your + initial browser connection to the canister. + +3. Copy and paste the URL from your first browser session into the + private browsing window, then click **Login**. + + ![linkedup incognito](linkedup-incognito.png) + + Notice that there's no profile in the private browsing window but + your original profile is still visible in your initial browser tab. + +4. Click **Edit**, type profile information, copy and paste the image + address for an avatar photo, then click **Submit**. + + ![linkedup edit dylan](linkedup-edit-dylan.png) + + After clicking **Submit**, you have a second profile with some work + history that can be viewed. + + For example: + + ![linkedup profile dylan](linkedup-profile-dylan.png) + +5. Type the first name or last name from the first profile you + created---for example, if you created a profile for Maya Garcia, + type Maya---then click **Search**. + + ![linkedup search from dylan for + maya](linkedup-search-from-dylan-for-maya.png) + + The profile matching your search criteria is displayed. + + ![linkedup search result](linkedup-search-result.png) + +6. Select the contact from the search results, wait for the Connect + button to be displayed, then click **Connect**. + + ![linkedup connect from dylan to + maya](linkedup-connect-from-dylan-to-maya.png) + + When the connection request completes, the second profile displays + the connection to the first profile. For example: + + ![linkedup connected to maya](linkedup-connected-to-maya.png) + +7. Return to the browser tab with your original profile. + + If you want to create a connection between the original profile and + the profile you created in the private browsing window, you can do + so by repeating the search, select, and connect steps. + +# Explore the configuration file {#_explore_the_configuration_file} + +Now that you have explored the basic features of the sample application, +you have some context for exploring how the configuration settings and +source files are used. + +To explore the configuration file: + +1. Change to the `linkedup` directory, then open the project's + `dfx.json` file. + +2. Note that there are two main canisters defined---`connectd` and + `linkedup`---each with a `main.mo` source file. + +3. Note that the `linkedup_assets` canister specifies a frontend entry + point of `main.js` and assets in the form of CSS and HTML files. + +4. Note that the application uses the default server IP address and + port number. + +# Explore the connectd source code {#_explore_the_connectd_source_code} + +The source code for the social connections canister, `connectd`, is +organized into the following files: + +- The `digraph.mo` file provides the functions to create a directed + graph of vertices and edges to describe a user's connections. + +- The `main.mo` contains the actor and key functions for defining the + connections associated with a user profile that can be called by the + LinkedUp sample application. + +- The `types.mo` file defines the custom type that maps a vertex to a + user identity for use in the `digraph` and `main` program files. + +# Explore the linkedup source code {#_explore_the_linkedup_source_code} + +The source code for the professional profile with work history and +educational background is organized into the following files: + +- The `main.mo` file contains the actor and key functions for the + LinkedUp sample application. + +- The `types.mo` file defines the custom types that describe the user + identity and profile fields that are imported and used in the `main` + program file for the `linkedup` canister. + +- The `utils.mo` file provides helper functions. + +## Query and update operations {#_query_and_update_operations} + +In working with the LinkedUp sample application, you might notice that +some operations---such as viewing a profile or performing a +search---returned results almost immediately. Other operations---such as +creating a profile or adding a connection---took a little longer. + +These differences in performance illustrate the difference between using +query and update calls in the `linkedup` canister. + +For example, in the `src/linkedup/main.mo` file, the `create` and +`update` functions are update calls that change the state of the +canister, but the program uses query calls for the `get` and `search` +functions to view or search for a profile: + + // Profiles + + public shared(msg) func create(profile: NewProfile): async () { + directory.createOne(msg.caller, profile); + }; + + public shared(msg) func update(profile: Profile): async () { + if(Utils.hasAccess(msg.caller, profile)) { + directory.updateOne(profile.id, profile); + }; + }; + + public query func get(userId: UserId): async Profile { + Utils.getProfile(directory, userId) + }; + + public query func search(term: Text): async [Profile] { + directory.findBy(term) + }; + +## Interaction between the canisters {#_interaction_between_the_canisters} + +In this sample application, the `linkedup` canister leverages functions +defined in the `connectd` canister. This separation simplifies the code +in each canister and illustrates how you can extend a project by calling +common functions defined in one canister from one or more other +canisters. + +To make the public functions defined in one canister available in the +another canister: + +1. Add an `import` statement in the calling canister. + + In this example, the public functions are defined in the `connectd` + canister and are called by the `linkedup` canister. + + Therefore, the `src/linkedup/main.mo` includes the following code: + + ``` motoko + // Make the Connectd app's public methods available locally + import Connectd "canister:connectd"; + ``` + +2. Use the `canister.function` syntax to call public methods in the + imported canister. + + In this example, the `linkedup` canister calls the `connect` and + `getConnections` function in the imported `connectd` canister. + +You can see the code that enables interaction between the `linkedup` +canister and the `connectd` canister in the `main.mo` source files. + +For example, the `src/connectd/main.mo` defines the following functions: + +\+ + +``` motoko +actor Connectd { + flexible var graph: Digraph.Digraph = Digraph.Digraph(); + + public func healthcheck(): async Bool { true }; + + public func connect(userA: Vertex, userB: Vertex): async () { + graph.addEdge(userA, userB); + }; + + public func getConnections(user: Vertex): async [Vertex] { + graph.getAdjacent(user) + }; + +}; +``` + +Because of the `Import` statement, the `connectd` functions are +available to the `linkedup` canister and the `src/linkedup/main.mo` +includes the following code: + +``` motoko + // Connections + + public shared(msg) func connect(userId: UserId): async () { + // Call Connectd's public methods without an API + await Connectd.connect(msg.caller, userId); + }; + + public func getConnections(userId: UserId): async [Profile] { + let userIds = await Connectd.getConnections(userId); + directory.findMany(userIds) + }; + + public shared(msg) func isConnected(userId: UserId): async Bool { + let userIds = await Connectd.getConnections(msg.caller); + Utils.includes(userId, userIds) + }; + + // User Auth + + public shared query(msg) func getOwnId(): async UserId { msg.caller } + +}; +``` + +# Stop the local network {#_stop_the_local_network} + +After you finish experimenting with the `linkedup` program, you can stop +the local Internet Computer network so that it doesn't continue running +in the background. + +To stop the local network: + +1. In the terminal that displays network operations, press Control-C to + interrupt the local network process. + +2. Stop the Internet Computer network by running the following command: + + ``` bash + dfx stop + ``` diff --git a/modules/developers-guide/pages/tutorials/multiple-actors.text b/modules/developers-guide/pages/tutorials/multiple-actors.text new file mode 100644 index 000000000..63b28ff98 --- /dev/null +++ b/modules/developers-guide/pages/tutorials/multiple-actors.text @@ -0,0 +1,321 @@ +--- +date: 2021-08-05 +title: Use multiple actors +--- + +In this tutorial, you are going to create a project with multiple +actors. Currently, you can only define one actor in a Motoko file and a +single actor is always compiled to a single canister. You can, however, +create **projects** that have multiple actors and can build multiple +canisters from the same `dfx.json` configuration file. + +For this tutorial, you are going to create separate program files for +three actors in the same project. This project defines the following +unrelated actors: + +- The `assistant` actor provides functions to add and show tasks in a + to-do list. + + For simplicity, the code sample for this tutorial only includes the + functions to add to-do items and to show the current list of to-do + items that have been added. A more complete version of this + program---with additional functions for marking items as complete + and removing items from the list---is available in the + [examples](https://github.com/dfinity/examples/) repository as + [Simple to-do + checklist](https://github.com/dfinity/examples/tree/master/motoko/simple-to-do). + +- The `rock_paper_scissors` actor provides a function for determining + a winner in a hard-coded rock-paper-scissors contest. + + This code sample illustrates the basic use of `switch` and `case` in + a Motoko program with hard-coded players and choices. + +- The `daemon` actor provides mock functions for starting and stopping + a daemon. + + This code sample simply assigns a variable and prints messages for + demonstration purposes. + +# Before you begin {#_before_you_begin} + +Before starting the tutorial, verify the following: + +- You have downloaded and installed the {sdk-short-name} package as + described in [Download and + install](../../quickstart/local-quickstart.xml#download-and-install). + +- You have stopped any Internet Computer network processes running on + the local computer. + +This tutorial takes approximately 20 minutes to complete. + +# Create a new project {#_create_a_new_project} + +To create a new project for this tutorial: + +1. Open a terminal shell on your local computer, if you don't already + have one open. + +2. Change to the folder you are using for your Internet Computer + projects, if you are using one. + +3. Create a new project by running the following command: + + ``` bash + dfx new multiple_actors + ``` + +4. Change to your project directory by running the following command: + + ``` bash + cd multiple_actors + ``` + +# Modify the default configuration {#_modify_the_default_configuration} + +You have already seen that creating a new project adds a default +`dfx.json` configuration file to your project directory. For this +tutorial, you need to add sections to this file to specify the location +of each program that defines an actor you want to build. + +To modify the default `dfx.json` configuration file: + +1. Open the `dfx.json` configuration file in a text editor, then change + the default `multiple_actors` canister name and source directory to + `assistant`. + + For example, under the `canisters` key: + + ``` json + "assistant": { + "main": "src/assistant/main.mo", + "type": "motoko" + }, + ``` + + Because you are going to add settings to this `canisters` section of + the configuration file, you must also add a **comma** after the + curly brace that encloses the location of the `assistant` main + source code file and the canister type. + +2. Remove the `multiple_actors_assets` section from the file. + +3. Add a new canister name, source code location, and canister type for + the `rock_paper_scissors` program and a new canister name, source + code location, and canister type for the `daemon` program files + below the `assistant` canister definition. + + After making the changes, the `canisters` section of the `dfx.json` + file should look similar to this: + + ``` json + Unresolved directive in multiple-actors.adoc - include::example$multiple-actors/dfx.json[] + ``` + + You can leave the other sections as-is. + +4. Save your changes and close the `dfx.json` file to continue. + +5. Change the name of the default source file directory to match the + name specified in the `dfx.json` configuration file by running the + following command: + + ``` bash + cp -r src/multiple_actors/ src/assistant/ + ``` + +6. Copy the `assistant` source file directory to create the main + program file for the `rock_paper_scissors` actor by running the + following command: + + ``` bash + cp -r src/assistant/ src/rock_paper_scissors/ + ``` + +7. Copy the `assistant` source file directory to create the main + program file for the `daemon` actor by running the following + command: + + ``` bash + cp -r src/assistant/ src/daemon/ + ``` + +# Modify the default programs {#_modify_the_default_programs} + +You now have three separate directories in the `src` directory, each +with a template `main.mo` file. For this tutorial, you will replace the +content in each template `main.mo` file with a different actor. + +To modify the default source code: + +1. Open the `src/assistant/main.mo` file in a text editor and delete + the existing content. + +2. Copy and paste the following sample code into the file: + + ``` motoko + Unresolved directive in multiple-actors.adoc - include::example$multiple-actors/assistant/main.mo[] + ``` + +3. Save your changes and close the `main.mo` file to continue. + +4. Open the `src/rock_paper_scissors/main.mo` file in a text editor and + delete the existing content. + +5. Copy and paste the following sample code into the file: + + ``` motoko + Unresolved directive in multiple-actors.adoc - include::example$multiple-actors/rock_paper_scissors/main.mo[] + ``` + +6. Save your changes and close the `main.mo` file to continue. + +7. Open the `src/daemon/main.mo` file in a text editor and delete the + existing content. + +8. Copy and paste the following sample code into the file: + + ``` motoko + Unresolved directive in multiple-actors.adoc - include::example$multiple-actors/daemon/main.mo[] + ``` + +9. Save your changes and close the `main.mo` file to continue. + +# Start the local network {#_start_the_local_network} + +Before you can build the `multiple_actors` project, you need to connect +to the Internet Computer network either running locally in your +development environment or running remotely on a subnet that you can +access. + +To start the network locally: + +1. Open a new terminal window or tab on your local computer. + +2. Navigate to the root directory for your project, if necessary. + +3. Start the Internet Computer network on your local computer by + running the following command: + + ``` bash + dfx start + ``` + +4. Leave the terminal that displays network operations open and switch + your focus to your original terminal where you created your new + project. + +# Register, build, and deploy your application {#_register_build_and_deploy_your_application} + +After you connect to the Internet Computer network running locally in +your development environment, you can register, build, and deploy your +multi-canister application locally. + +To deploy the application locally: + +1. Check that you are still in the root directory for your project, if + needed. + +2. Register, build, and deploy the application by running the following + command: + + ``` bash + dfx deploy + ``` + + If you have access to the Internet Computer running remotely, you + can deploy to the that network instead of deploying locally by + specifying the `--network` option and the network alias configured + in the `dfx.json` file. For example, if you are connecting to the + URL specified by the network alias `ic` you would run a command + similar the following: + + ``` bash + dfx deploy --network ic + ``` + + The `dfx deploy` command output displays information about the + operations it performs. For example, the command displays the + network-specific canister identifiers for the three canisters + defined in the `dfx.json` configuration file. + + Deploying all canisters. + Creating canisters... + Creating canister "assistant"... + "assistant" canister created with canister id: "75hes-oqbaa-aaaaa-aaaaa-aaaaa-aaaaa-aaaaa-q" + Creating canister "daemon"... + "daemon" canister created with canister id: "cxeji-wacaa-aaaaa-aaaaa-aaaaa-aaaaa-aaaaa-q" + Creating canister "rock_paper_scissors"... + "rock_paper_scissors" canister created with canister id: "7kncf-oidaa-aaaaa-aaaaa-aaaaa-aaaaa-aaaaa-q" + +# Verify deployment by calling functions {#_verify_deployment_by_calling_functions} + +You now have three programs deployed as a **canisters** on your local +replica network and can test each program by using `dfx canister call` +commands. + +To test the programs you have deployed: + +1. Use the `dfx canister call` command to call the canister `assistant` + using the `addTodo` function and pass it the task you want to add by + running the following command: + + ``` bash + dfx canister call assistant addTodo '("Schedule monthly demos")' + ``` + +2. Verify that the command returns the to-do list item using the + `showTodos` function by running the following command: + + ``` bash + dfx canister call assistant showTodos + ``` + + The command returns output similar to the following: + + (" + ___TO-DOs___ + (1) Schedule monthly demos") + +3. Use the `dfx canister call` command to call the canister + `rock_paper_scissors` using the `contest` function by running the + following command: + + ``` bash + dfx canister call rock_paper_scissors contest + ``` + + The command returns the result of the hard-coded contest similar to + the following: + + ("Bob won") + +4. Use the `dfx canister call` command to call the canister `daemon` + using the `launch` function by running the following command: + + ``` bash + dfx canister call daemon launch + ``` + +5. Verify the mock `launch` function returns \"The daemon process is + running\" message\": + + (""The daemon process is running"") + +# Stop the local network {#_stop_the_local_network} + +After you finish experimenting with your program, you can stop the local +Internet Computer network so that it doesn't continue running in the +background. + +To stop the local network: + +1. In the terminal that displays network operations, press Control-C to + interrupt the local network process. + +2. Stop the Internet Computer network by running the following command: + + ``` bash + dfx stop + ``` diff --git a/modules/developers-guide/pages/tutorials/multiple-factorial-actors.text b/modules/developers-guide/pages/tutorials/multiple-factorial-actors.text new file mode 100644 index 000000000..172f53b36 --- /dev/null +++ b/modules/developers-guide/pages/tutorials/multiple-factorial-actors.text @@ -0,0 +1,300 @@ +--- +author: February 2020 (Alpha) +date: 2021-08-05 +title: Using multiple actors +--- + +In this tutorial, you are going to create a project with multiple +actors. Currently, you can only define one actor in a Motoko file and a +single actor is always compiled to a single canister. In addition, you +cannot yet call functions defined in an actor in one canister from an +actor defined in another canister or define an actor class to support +multiple actor instances in your Motoko programs. You can, however, +create **projects** that have multiple actors and can build multiple +canisters from the same `dfx.json` configuration file. + +For this tutorial, you are going to create separate program files for +three actors in the same project. This project defines the following +unrelated actors: + +- The `assistant` actor provides functions to add and show tasks in a + to-do list. + + For simplicity, the code sample for this tutorial only includes the + functions to add to-do items and to show the current list of to-do + items that have been added. A more complete version of this + program-with additional functions for marking items as complete and + removing items from the list---is included in [Sample code, + applications, and microservices](../sample-apps.xml). + +- The `factorial` actor provides a function for determining the + factorial for a specified number. + +- The `daemon` actor provides mock functions for starting and stopping + a daemon. + + This code sample simply assigns a variable and prints messages for + demonstration purposes. + +# Before you begin {#_before_you_begin} + +Before starting the tutorial, verify the following: + +- You have downloaded and installed the SDK as described in [Getting + started](../getting-started.xml). + +- You have stopped any network replica processes running on the local + computer. + +This tutorial takes approximately 20 minutes to complete. + +# Create a new project {#_create_a_new_project} + +To create a new project for this tutorial: + +1. Open a terminal shell on your local computer, if you don't already + have one open. + +2. Change to the folder you are using for your Internet Computer + projects, if you are using one. + +3. Create a new project by running the following command: + + ``` bash + dfx new multiple_actors + ``` + +4. Change to your project directory by running the following command: + + ``` bash + cd multiple_actors + ``` + +# Modify the default configuration {#_modify_the_default_configuration} + +You have already seen that creating a new project adds a default +`dfx.json` configuration file to your project directory. For this +tutorial, you need to add sections to this file to specify the location +of each program that defines an actor you want to build. + +To modify the default `dfx.json` configuration file: + +1. Open the `dfx.json` configuration file in a text editor, then change + the default `multiple_actors` canister name and source directory to + `assistant`. + + For example: + + ``` bash + { + "canisters": { + "assistant": { + "frontend": { + "entrypoint": "src/multiple_actors/public/index.js" + }, + "main": "src/assistant/main.mo" + }, + ``` + + Because you are going to add settings to this `canisters` section of + the configuration file, you must also add a **comma** after the + curly brace that encloses the location of the `assistant` main + source code file. + +2. Add a new canister name and source file location for the `factorial` + program and a new canister name and source file location for the + `daemon` program files below the `assistant` source file location. + + For example: + + ``` bash + "factorial": { + "main": "src/factorial/main.mo" + }, + "daemon": { + "main": "src/daemon/main.mo" + } + }, + ``` + + You can leave the other sections as-is. + +3. Change the name of the default source file directory to match the + name specified in the `dfx.json` configuration file by running the + following command: + + ``` bash + cp -r src/multiple_actors/ src/assistant/ + ``` + +4. Copy the `assistant` source file directory to create the main + program file for the `factorial` actor by running the following + command: + + ``` bash + cp -r src/assistant/ src/factorial/ + ``` + +5. Copy the `assistant` source file directory to create the main + program file for the `daemon` actor by running the following + command: + + ``` bash + cp -r src/assistant/ src/daemon/ + ``` + +# Modify the default template programs {#_modify_the_default_template_programs} + +You now have three separate directories in the `src` directory, each +with a template `main.mo` file. For this tutorial, you will replace the +content in each template `main.mo` file with a different actor. + +To modify the default template source code: + +1. Open the `src/assistant/main.mo` file in a text editor and delete + the existing content. + +2. Copy and paste the following sample code into the file: + + ``` motoko + include::example$multiple-actors/assistant/main.mo + ``` + +3. Open the `src/factorial/main.mo` file in a text editor and delete + the existing content. + +4. Copy and paste the following sample code into the file: + + ``` motoko + include::example$multiple-actors/factorial/main.mo + ``` + +5. Open the `src/daemon/main.mo` file in a text editor and delete the + existing content. + +6. Copy and paste the following sample code into the file: + + ``` motoko + include::example$multiple-actors/daemon/main.mo + ``` + +# Build all of the canisters in the project {#_build_all_of_the_canisters_in_the_project} + +You now have a program that you can compile into an executable +WebAssembly module that you can deploy on your local replica network. + +To build the executable for each actor in the project: + +1. Change to the `~/ic-projects/multiple_actors` root directory for + your project, if needed. + +2. Build the WebAssembly executable for each program by running the + following command: + + ``` bash + dfx build --all + ``` + + If the command is successful, it builds all of the canisters you + have specified in the `dfx.json` file. + + ``` bash + Building canister assistant + Building canister factorial + Building canister daemon + ``` + +# Deploy the canisters in the project {#_deploy_the_canisters_in_the_project} + +You now have three separate compiled programs---one for each +actor---ready for deployment. + +To deploy the canisters: + +1. Start the Internet Computer network on your local computer by + running the following command: + + ``` bash + dfx start + ``` + +2. Open a new terminal shell, then change the + `~/ic-projects/multiple_actors` root directory for your project. + + For example: + + ``` bash + cd ~/ic-projects/multiple_actors + ``` + +3. Deploy your canisters on the local network by running the following + command: + + ``` bash + dfx canister install --all + ``` + +# Verify deployment by calling functions {#_verify_deployment_by_calling_functions} + +You now have three programs deployed as a **canisters** on your local +replica network and can test each program by using `dfx canister call` +commands. + +To test the programs you have deployed on the local replica network: + +1. Use the `dfx canister call` command to call the canister `assistant` + using the `addTodo` function and pass it the task you want to add by + running the following command: + + ``` bash + dfx canister call assistant addTodo '("Schedule monthly demos")' + ``` + +2. Verify that the command returns the to-do list item using the + `showTodos` function by running the following command: + + ``` bash + dfx canister call assistant showTodos + ``` + + The command returns output similar to the following: + + ``` bash + (" + ___TO-DOs___ + (1) Schedule monthly demos + ``` + +3. Use the `dfx canister call` command to call the canister `factorial` + using the `fac` function by running the following command: + + ``` bash + dfx canister call factorial fac '(8)' + ``` + + The command returns the result of the function: + + ``` bash + (40320) + ``` + +4. Use the `dfx canister call` command to call the canister `daemon` + using the `launch` function by running the following command: + + ``` bash + dfx canister call daemon launch + ``` + +5. Verify the mock `launch` function returns \"The daemon process is + running\" message\": + + ``` bash + (""The daemon process is running"") + ``` + +6. Stop the Internet Computer processes running on your local computer + by running the following command: + + ``` bash + dfx stop + ``` diff --git a/modules/developers-guide/pages/tutorials/my-contacts.text b/modules/developers-guide/pages/tutorials/my-contacts.text new file mode 100644 index 000000000..ad15f80a5 --- /dev/null +++ b/modules/developers-guide/pages/tutorials/my-contacts.text @@ -0,0 +1,403 @@ +--- +date: 2021-08-05 +title: Add a stylesheet +--- + +Cascading stylesheets represent one of the most common ways to customize +the user experience for an application. This tutorial illustrates how to +add a stylesheet when you use React to create a new front-end for your +project. If you already know how to add cascading stylesheets (CSS) to a +React-based project, you can skip this tutorial. + +::: note +This tutorial illustrates using the React framework to manage the +Document Object Model (DOM) for your canister. Because React has its own +custom DOM syntax, you need to modify the webpack configuration to +compile the front-end code, which is written in JSX. For more +information about learning to use React and JSX, see [Getting +started](https://reactjs.org/docs/getting-started.html) on the [React +website](https://reactjs.org/). +::: + +# Before you begin {#_before_you_begin} + +Before starting the tutorial, verify the following: + +- You have `node.js` installed for front-end development and can + install packages using `npm install` in your project. For + information about installing node for your local operating system + and package manager, see the [Node](https://nodejs.org/en/) website. + +- You have downloaded and installed the {sdk-short-name} package as + described in [Download and + install](../../quickstart/local-quickstart.xml#download-and-install). + +- You have installed the Visual Studio Code plugin for Motoko as + described in [Install the language editor + plug-in](../../quickstart/local-quickstart.xml#install-vscode) if + you are using Visual Studio Code as your IDE. + +- You have stopped any Internet Computer network processes running on + the local computer. + +::: note +Because of significant changes to the handling of HTTP requests and +front-end assets, this tutorial requires you to use the {sdk-short-name} +version `0.7.0` or later. For an overview of what's changed, see this +[article](../../http-middleware.xml). +::: + +# Create a new project {#_create_a_new_project} + +To create a new project directory for your custom front-end application: + +1. Open a terminal shell on your local computer, if you don't already + have one open. + +2. Change to the folder you are using for your Internet Computer + projects, if you are using one. + +3. Verify that you have `node.js` installed locally, if necessary. + +4. Create a new project by running the following command: + + ``` bash + dfx new contacts + ``` + +5. Change to your project directory by running the following command: + + ``` bash + cd contacts + ``` + +# Install the React framework {#_install_the_react_framework} + +if you've never used React before, you might want to explore the [Intro +to React](https://reactjs.org/tutorial/tutorial.html) tutorial or the +[React website](https://reactjs.org/) before editing the front-end code. + +To install required framework modules: + +1. Install the React module by running the following command: + + ``` bash + npm install --save react react-dom + ``` + +2. Install the required TypeScript language compiler loader by running + the following command: + + ``` bash + npm install --save-dev typescript ts-loader + ``` + +3. Install the required style loaders by running the following command: + + ``` bash + npm install --save-dev style-loader css-loader + ``` + + If the `npm install` command reports a vulnerability, you might also + want to run the `npm audit fix` command to attempt to fix the + vulnerability reported before continuing. + + ::: note + As an alternative to installing these modules, you can edit the + default `package.json` file to add dependencies for your project. + ::: + + Unresolved directive in my-contacts.adoc - include::example$add-stylesheet-package.json[] + + The version of the JavaScript agent in this example `package.json` + file is `0.9.2`. In most cases, however, you would want to use the + latest version of the agent available. When you create a new + project, the `dfx new` command automatically retrieves the latest + version of the JavaScript agent for you. You can also manually + retrieve the latest version after creating a project by running the + `npm install --save @dfinity/agent` command. + +# Modify the default program {#_modify_the_default_program} + +For this tutorial, you are going to modify the main program to with code +that allows you to store and look up contact information. + +To modify the default program: + +1. Open the `src/contacts/main.mo` file in a text editor and delete the + existing content. + +2. Copy and paste the following sample code into the file: + + ``` motoko + Unresolved directive in my-contacts.adoc - include::example$mycontacts/contacts.mo[] + ``` + +3. Save your changes and close the `main.mo` file to continue. + +# Modify the front-end files {#_modify_the_front_end_files} + +You are now ready to create a new front-end for your program. + +1. Open the webpack configuration file (`webpack.config.js`) in a text + editor. + +2. Modify the front-end entry to replace the default index.html with + index.jsx. + + ``` js + entry: { + // The frontend.entrypoint points to the HTML file for this build, so we need + // to replace the extension to `.js`. + index: path.join(__dirname, asset_entry).replace(/\.html$/, ".jsx"), + }, + ``` + +3. Locate the commented example for the `module` key above the + `plugins` section, then uncomment the following lines: + + ``` js + module: { + rules: [ + { test: /\.(js|ts)x?$/, loader: "ts-loader" }, + { test: /\.css$/, use: ['style-loader','css-loader'] } + ] + }, + ``` + + These settings enable your program to use the `ts-loader` compiler + and to import CSS files. + +4. Save your changes and close the `webpack.config.js` file to + continue. + +5. Create a new file named `tsconfig.json` in the root directory for + your project. + +6. Open the `tsconfig.json` file in a text editor, then copy and paste + the following into the file: + + ``` json + Unresolved directive in my-contacts.adoc - include::example$sample-tsconfig.json[] + ``` + +7. Save your changes and close the `tsconfig.json` file to continue. + +# Add a stylesheet to your project {#_add_a_stylesheet_to_your_project} + +You are now ready to create a new cascading stylesheet and add it to +your project. + +To add a stylesheet: + +1. Change to the `src/contacts_assets/assets` directory. + + ``` bash + cd src/contacts_assets/assets/ + ``` + +2. Open the `main.css` file in a text editor and delete the existing + content. + +3. Define some style properties for the front-end. + + For example, copy and paste the following sample styles into the + file: + + ``` bash + Unresolved directive in my-contacts.adoc - include::example$mycontacts/mycontacts.css[] + ``` + +4. Save your changes and close the `main.css` file to continue. + +5. Change to the `src/contacts_assets/src` directory. + + ``` bash + cd ../src + ``` + +6. Open the default `index.js` file in a text editor and delete the + existing content. + +7. Copy and paste the following sample code into the `index.js` file: + + ``` react + Unresolved directive in my-contacts.adoc - include::example$mycontacts/mod-index.jsx[] + ``` + +8. Rename the modified `index.js` file as `index.jsx` by running the + following command: + + ``` bash + mv index.js index.jsx + ``` + +9. Open the default `src/contacts_assets/src/index.html` file in a text + editor, then replace `main.css` as the stylesheet file name with + `mycontacts.css` and update the `body` contents with + `
`. + + For example: + + ``` bash + + + + + + contacts + + + + + +
+
+
+ + + ``` + +10. Navigate back to the root of your project directory. + + For example: + + ``` bash + cd ../../.. + ``` + +# Start the local network {#_start_the_local_network} + +Before you can build the `contacts` project, you need to connect to the +Internet Computer network either running locally in your development +environment or running remotely on a subnet that you can access. + +To start the network locally: + +1. Open a new terminal window or tab on your local computer. + +2. Start the Internet Computer network on your local computer by + running the following command: + + ``` bash + dfx start --background + ``` + + After the local Internet Computer network completes its startup + operations, you can continue to the next step. + +# Register, build, and deploy the application {#_register_build_and_deploy_the_application} + +After you connect to the Internet Computer network running locally in +your development environment, you can register, build, and deploy your +application locally. + +To deploy the application: + +1. Check that you are still in the root directory for your project, if + needed. + +2. Register, build, and deploy your application by running the + following command: + + ``` bash + dfx deploy + ``` + + The `dfx deploy` command output displays information about the + operations it performs. + + Keep in mind that because you are running the Internet Computer + locally, the identifiers displayed when you run the `dfx deploy` + command are only valid on the local network. + + To deploy canisters on an external Internet Computer network, you + must connect to that network using the `--network` command-line + option and a specific network name or address to register + identifiers on that network. For example, to deploy on the Internet + Computer using the reserve network alias `ic`, you would run a + command similar the following: + + ``` bash + dfx deploy --network=ic + ``` + +3. Start the Webpack development server: + + ``` bash + npm start + ``` + +# View the front-end {#_view_the_front_end} + +You can now access the front-end for the `contacts` program by entering +the canister identifier for the assets canister in a browser. + +To view the front-end: + +1. Open a browser and navigate to the `http://localhost:8080`. + +2. Verify that you are prompted with a **My Contacts** form. + + For example: + + ![Sample front-end](mycontacts-form.png) + +3. Create one or more test records by entering text in the Name, + Address, and Email input fields and a number in the Phone input + field, then clicking **Add Contact**. + +4. Clear the form fields and type a contact name in the Lookup name + field, then click **Lookup** to see the stored contact information. + + Keep in mind that the **Lookup name** you type must be an exact + match for the name of a contact you added. + +# Modify the stylesheet and test your changes {#_modify_the_stylesheet_and_test_your_changes} + +After viewing the Contacts application, you might want to make some +changes. + +To change stylesheet properties: + +1. Open the `src/contacts_assets/public/mycontacts.css` file in a text + editor and modify its style settings. + + For example, you might want to change the background color or style + the input form. + + You should see the changes update immediately in your open browser + window. + +# Modify the front-end or back-end code {#_modify_the_front_end_or_back_end_code} + +If you want to explore further, you might want to experiment with +modifying the front-end or back-end code for this tutorial. For example, +you might want try modifying the tutorial to do the following: + +- Change the front-end code to clear the input fields after adding a + new contact, for example, as part of an `onClick` event. + +- Change the Motoko program functions to do partial instead of exact + string matching on the `Name` field. (You will need to run + `dfx deploy` to test your changes on the local replica) + +- Change the Motoko program to allow lookups based on a different + field. + +# Stop the local network {#_stop_the_local_network} + +After you finish experimenting with your program, you can stop the local +Internet Computer network so that it doesn't continue running in the +background. + +To stop the local network: + +1. In the terminal that displays your webpack dev server, press + Control-C to interrupt the development server. + +2. Stop the Internet Computer network by running the following command: + + ``` bash + dfx stop + ``` diff --git a/modules/developers-guide/pages/tutorials/phonebook.text b/modules/developers-guide/pages/tutorials/phonebook.text new file mode 100644 index 000000000..86a79b8cd --- /dev/null +++ b/modules/developers-guide/pages/tutorials/phonebook.text @@ -0,0 +1,261 @@ +--- +date: 2021-08-05 +title: Import library modules +--- + +In this tutorial, you are going to write a simple program that enables +you to store and look up telephone numbers. This tutorial illustrates +how to import and use a few basic Motoko library functions. + +For this tutorial, the Motoko base library functions are defined in the +`List` and `AssocList` modules and enable you to work with lists as +linked key-value pairs. In this example, the **key** is a `name` and the +**value** is the `phone` text string associated with that name. + +This program supports the following function calls: + +- The `insert` function accepts the `name` and `phone` key-value pair + as input stored in the `book` variable. + +- The `lookup` function is a query that uses the specified `name` key + as input to find the associated phone number. + +# Before you begin {#_before_you_begin} + +Before starting the tutorial, verify the following: + +- You have downloaded and installed the {sdk-short-name} package as + described in [Download and + install](../../quickstart/local-quickstart.xml#download-and-install). + +- You have stopped any Internet Computer network processes running on + the local computer. + +This tutorial takes approximately 10 minutes to complete. + +# Create a new project {#_create_a_new_project} + +To create a new project for this tutorial: + +1. Open a terminal shell on your local computer, if you don't already + have one open. + +2. Change to the folder you are using for your Internet Computer + projects, if you are using one. + +3. Create a new project by running the following command: + + ``` bash + dfx new phonebook + ``` + +4. Change to your project directory by running the following command: + + ``` bash + cd phonebook + ``` + +# Modify the default program {#_modify_the_default_program} + +For this tutorial, let's create a new `main.mo` file for the simple +phone number lookup program. + +To modify the default template: + +1. Open the `src/phonebook/main.mo` file in a text editor and delete + the existing content. + +2. Copy and paste the following sample code into the `main.mo` file: + + ``` motoko + Unresolved directive in phonebook.adoc - include::example$phonebook.mo[] + ``` + + In looking at this sample program, you might notice the following + key elements: + + - The code defines `Name` and `Phone` as custom Text types. + Creating user-defined types improves the readability of the + code. + + - The `insert` function is an update call and the `lookup` + function is a query call. + + - The `Phone` type is identified as an optional value by using the + `?Phone` syntax. + +# Start the local network {#_start_the_local_network} + +Before you can build the `phonebook` project, you need to connect to the +Internet Computer network either running locally in your development +environment or running remotely on a subnet that you can access. + +Starting the network locally requires a `dfx.json` file, so you should +be sure you are in your project's root directory. For this tutorial, you +should have two separate terminal shells, so that you can start and see +network operations in one terminal and manage your project in another. + +To start the network locally: + +1. Open a new terminal window or tab on your local computer. + +2. Navigate to the root directory for your project, if necessary. + + - You should now have **two terminals** open. + + - You should have the **project directory** as your **current + working directory**. + +3. Start the Internet Computer network on your local computer by + running the following command: + + ``` bash + dfx start --clean + ``` + + For this tutorial, we're using the `--clean` option to start the + Internet Computer network in a clean state. + + This option removes any orphan background processes or canister + identifiers that might disrupt normal operations. For example, if + you forgot to issue a `dfx stop` when moving between projects, you + might have a process running in the background or in another + terminal. The `--clean` option ensures the you can start the + Internet Computer network and continue to the next step without + manually finding and terminating any running processes. + +4. Leave the terminal that displays network operations open and switch + your focus to your original terminal where you created your new + project. + +# Register, build, and deploy the application {#_register_build_and_deploy_the_application} + +After you connect to the Internet Computer network running locally in +your development environment, you can register, build, and deploy your +application locally. + +To deploy the application locally: + +1. Check that you are still in the root directory for your project, if + needed. + +2. Register, build, and deploy your application by running the + following command: + + ``` bash + dfx deploy phonebook + ``` + + The `dfx.json` file provides default settings for creating an + application front-end entry point and `assets` canister. + + In previous tutorials, we deleted the entries for the asset canister + because we weren't adding a front-end for the sample application. + That change kept our project workspace tidy by eliminating files + that would go unused. There's no requirement to do this, however, + and there's no harm in leaving the asset canister description in the + `dfx.json` file. For example, you might want to use it as a + placeholder if you intend to add front-end assets later. + + For this tutorial, you can deploy just the phonebook back-end + canister using the `dfx deploy phonebook` command because the + project is a terminal-based application that doesn't include any + front-end assets. + + Although this tutorial illustrates how to skip compiling a front-end + canister, you can add a simple user interface to this application + later by exploring the + [phone-book](https://github.com/dfinity/examples/tree/master/motoko/phone-book) + project in the [examples](https://github.com/dfinity/examples) + repository. + +# Add names and numbers using the insert function {#_add_names_and_numbers_using_the_insert_function} + +You now have a program deployed as a **canister** on your local replica +network and can test your program by using `dfx canister call` commands. + +To test the program you have deployed on the local replica network: + +1. Use the `dfx canister call` command to call the canister `phonebook` + using the `insert` function and pass it a name and phone number by + running the following command: + + ``` bash + dfx canister call phonebook insert '("Chris Lynn", "01 415 792 1333")' + ``` + +2. Add a second name and number pair by running the following command: + + ``` bash + dfx canister call phonebook insert '("Maya Garcia", "01 408 395 7276")' + ``` + +3. Verify that the command returns the number associated with \"Chris + Lynn\" using the `lookup` function by running the following command: + + ``` bash + dfx canister call phonebook lookup '("Chris Lynn")' + ``` + + The command returns output similar to the following: + + (opt "01 415 792 1333") + +4. Try to call the `lookup` function with the number associated with + \"Maya Garcia\" by running the following command: + + ``` bash + dfx canister call phonebook lookup '("01 408 395 7276")' + ``` + + Note that, in this case, the command returns `(null)` because the + phone number is not a key associated with the \"Maya Garcia\" name + entry. + +5. Try to call the `lookup` function again to return the phone numbers + for both \"Maya Garcia\" and \"Chris Lynn\" by running the following + command: + + ``` bash + dfx canister call phonebook lookup '("Maya Garcia","Chris Lynn")' + ``` + + Because the program is written to return one value for one key, the + command only returns information associated with the first key, in + this example the phone number for `Maya Garcia`. + +Unresolved directive in phonebook.adoc - +include::example\$candid-ui.adoc\[\] + +\+ ![Phonebook functions](candid-phonebook.png) + +# Revise the source code in your program {#_revise_the_source_code_in_your_program} + +To extend what you have learned in this tutorial, you might want to try +modifying the source code to return different results. + +For example, you might want to change the source code so that instead of +a program that inserts and looks up a current key-value (name-phone) +pair to create a program that stores contact information similar to a +database \"record\" in which a primary key is associated with multiple +fields. In this example, your program might enable users or another +program to add information---such as a home phone number, a cell phone +number, an email address, and a street address---and selectively return +all or specific field values. + +# Stop the local network {#_stop_the_local_network} + +After you finish experimenting with your program, you can stop the local +Internet Computer network so that it doesn't continue running in the +background. + +To stop the local network: + +1. In the terminal that displays network operations, press Control-C to + interrupt the local network process. + +2. Stop the Internet Computer network by running the following command: + + ``` bash + dfx stop + ``` diff --git a/modules/developers-guide/pages/tutorials/scalability-cancan.text b/modules/developers-guide/pages/tutorials/scalability-cancan.text new file mode 100644 index 000000000..b2dd3f9ea --- /dev/null +++ b/modules/developers-guide/pages/tutorials/scalability-cancan.text @@ -0,0 +1,171 @@ +--- +date: 2021-08-05 +title: Create scalable apps +--- + +The CanCan sample application is a simplified video-sharing service that +demonstrates several features that you can use as models for your own +applications. For example, here are a few things you can learn by +exploring the CanCan sample application: + +- How to build a scalable application by splitting content into + fragments for upload and storage then using queries to retrieve and + reassemble the fragments for efficient streaming. + +- How to configure interoperability for an application that uses + canisters written in different back-end languages. + +- How to implement a basic authentication model for storing videos + uploaded by different users. + +- How to build a front-end that implements more sophisticated user + interface features for desktop or mobile apps. + +# Splitting uploaded content into multiple canisters {#_splitting_uploaded_content_into_multiple_canisters} + +Because canisters are compiled WebAssembly modules, they have certain +known limitations. For example, currently WebAssembly modules have a +maximum of 4GB for memory and an upper limit on the number of object +calls allowed. + +For a video-sharing sample applications like CanCan, these limitations +mean that multiple canisters are required and that data must be broken +into smaller chunks for storage and retrieval. + +## Implementing a distributed hash table {#_implementing_a_distributed_hash_table} + +The initial attempt to build a scalable video-sharing service for the +Internet Computer used a distributed hash table (DHT) as a back-end +service with simple get and put functions that distributed data---chunks +of the video to be uploaded or streamed---into a predefined set of +canisters. In the early phases of the project, this approach was +sufficient for a proof-of-concept and verifying that the video data +could be properly transcoded for storage and retrieval. + +However, the scalability of the application was limited because the +distributed hash table relied on a specific number of canisters that it +could populate with data for storage and retrieve data from for viewing. +In addition, the original implementation of the distributed hash table +back-end service included code to accommodate common network +connectivity issues that could cause nodes to be unavailable or lose +data. + +## Simplifying scalability {#_simplifying_scalability} + +Because the Internet Computer protocol relies on replicated state across +nodes in a subnet, it provides certain guarantees about fault tolerance +and failover natively that are not generally available to applications +running on other platforms or protocols. + +With the realization that the Internet Computer could ensure that +canisters were available to receive and respond to requests,the original +distributed hash table back-end service was replaced with a simpler but +more scalable back-end service called BigMap. + +BigMap provides a simple, plug-in library for building scalable +applications using key-value storage on the Internet Computer. By using +the BigMap library as a back-end service, the CanCan sample application +can dynamically chunk, serialize, and distribute data to multiple +canisters. + +The library offers building blocks for application-specific, in-memory +data abstractions that scale using any number of canisters. Each +canister still has limited capacity, but the application instantiates +the canisters it needs and keeps track of the fragments that make up the +full video content for each user's videos in an index file called the +`manifest`. + +The code required for the `BigMap` service is much simpler than a +traditional distributed hash table because the Internet Computer as a +platform provides scalability, replication, failover, and fault +tolerance. + +# Demonstrating interoperability {#_demonstrating_interoperability} + +The BigMap service included in the CanCan sample application repository +is written in the Rust programming language. However, the CanCan sample +application also demonstrates interoperability between canisters written +in different languages. + +In this case, the `BigMap` functionality is implemented using the Rust +programming language and other services---such as encoding and decoding +of video content and the management of user principals for +authentication---are implemented using Motoko. + +By deploying different parts of the sample application as canisters, the +interaction between them provides a seamless user experience. + +Although the `BigMap` service you see in the CanCan repository is +written in Rust, the service was actually implemented in both Rust and +Motoko programming languages to demonstrate the following: + +- You can run both Motoko code and Rust code deployed as canisters on + the Internet Computer. + +- You can switch between back-end languages without affecting the + operation of the CanCan sample application. + +- Both language implementation work seamlessly because the Candid + language provides a common language for describing the BigMap API, + independent of JavaScript, Rust, or Motoko. + +# Authentication model {#_authentication_model} + +Much like the LinkedUp sample application, the CanCan sample application +uses the public-private key pair, browser-based local storage, and the +`Principal` data type to authenticate users. + +# Implementing front-end features {#_implementing_front_end_features} + +The CanCan sample application uses the React library in combination with +TypeScript to implement front-end user interface. + +# Data model overview {#_data_model_overview} + +The application stores information about users and information about +videos. To support most browsers, the videos are serialized into byte +arrays with video data stored in 500kb segments of bytes that are +referred to as +[Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) +objects. When a video is requested, the manifest loads the list of +chunks required to play the video and concatenates the chunks before +displaying the video in a standard `