### Building Candid UI Canister with DFX and NPM Source: https://github.com/dfinity/candid/blob/master/tools/ui/README.md This snippet outlines the steps to build and deploy the Candid UI canister. It involves navigating to the `ui` directory, installing Node.js dependencies, starting the DFX replica, creating and building all canisters, and finally installing them on the Internet Computer. ```bash cd ui/ npm install dfx start --background dfx canister create --all dfx build dfx canister install --all ``` -------------------------------- ### Starting Local Canister Execution Environment with dfx Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-howto.adoc This `dfx` command starts the local canister execution environment in the background. This environment is a prerequisite for deploying and interacting with canisters locally, including using the Candid UI for testing and debugging. ```Bash dfx start --background ``` -------------------------------- ### Encoding Candid Values with didc Examples Source: https://github.com/dfinity/candid/blob/master/tools/didc/README.md These examples demonstrate how to use `didc encode` to convert Candid values into their binary representation. It covers basic encoding, pretty-printing the output, encoding with a DID file and method, and illustrates a type mismatch error. ```Shell $ didc encode '(42, vec {1;2;-3})' 4449444c016d7c027c002a0301027d ``` ```Shell $ didc encode '(42, vec {1;2;-3})' -t '(nat, vec int32)' -f pretty Length: 24 (0x18) bytes 0000: 44 49 44 4c 01 6d 75 02 7d 00 2a 03 01 00 00 00 DIDL.mu.}.*..... 0010: 02 00 00 00 fd ff ff ff ........ ``` ```Shell $ didc encode '("text")' -d hello.did -m greet 4449444c0001710474657874 ``` ```Shell $ didc encode '("text")' -d list.did -t '(list)' Error: type mismatch: "text" can not be of type opt node ``` -------------------------------- ### Candid Import Example with Service Merging Source: https://github.com/dfinity/candid/blob/master/spec/Candid.md This example illustrates the use of `import` in Candid. File `A.did` defines a service `A`, and `B.did` imports `A.did` to define service `B` based on `A`. It highlights a constraint where `import service` cannot be used if method names would duplicate. ```Candid type A = service { f : () -> () }; service : A ``` ```Candid import "A.did"; // Cannot use `import service` because of method name duplication service B : A ; ``` -------------------------------- ### Decoding Candid Binary Data with didc Examples Source: https://github.com/dfinity/candid/blob/master/tools/didc/README.md These examples illustrate how to use `didc decode` to convert Candid binary data back into human-readable Candid values. It demonstrates basic decoding and decoding with a specified Candid type for interpretation. ```Shell $ didc decode '4449444c016d7c027c002a0301027d' (42, vec { 1; 2; -3; }) ``` ```Shell $ didc decode '4449444c016d7c027c002a0301027d' -t '(int)' (42) ``` -------------------------------- ### Example Candid Type Definitions Source: https://github.com/dfinity/candid/blob/master/tools/didc/config.md This snippet provides example Candid type definitions, including a recursive `tree` variant, a `pair` record, an optional `left` type, and a service definition with a method `f`. These types are used to illustrate how the type selectors can be applied. ```Candid type tree = variant { leaf: int; branch: record { left: tree; right: tree } }; type pair = record { left: int; right: nat }; type left = opt int; service : { f : (record {a:int; b:int}, record {a:int; b:int}) -> (); } ``` -------------------------------- ### Example Candid Service Definition Source: https://github.com/dfinity/candid/blob/master/spec/Candid.md This example demonstrates a complete Candid service definition. It includes four methods: `addUser` for creating a user, `userName` and `userAge` for querying user details (both marked as `query` for efficiency), and `deleteUser` for removing a user (marked as `oneway` for fire-and-forget semantics, with no return value). ```Candid service : { addUser : (name : text, age : nat8) -> (id : nat64); userName : (id : nat64) -> (text) query; userAge : (id : nat64) -> (nat8) query; deleteUser : (id : nat64) -> () oneway; } ``` -------------------------------- ### Candid: Service Reference Example Source: https://github.com/dfinity/candid/blob/master/spec/Candid.md Provides an example of a Candid service reference, defining a `broker` service that can find other services. The `findCounterService` function returns a service reference to a `CounterService` with `up` and `current` methods. ```Candid type broker = service { findCounterService : (name : text) -> (service {up : () -> (); current : () -> (nat)}); } ``` -------------------------------- ### Defining a Basic Counter Service Interface in Candid Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-concepts.adoc This Candid snippet defines the interface for a 'counter' service, detailing its public methods. It includes 'add' and 'subtract' for modifying the counter's value, 'get' for reading the current value (annotated as a 'query' method), and 'subscribe' for registering a callback function. This example illustrates how methods are defined with argument and result types, and can incorporate Internet Computer-specific annotations. ```Candid service counter : { add : (nat) -> (); subtract : (nat) -> (); get : () -> (int) query; subscribe : (func (int) -> ()) -> (); } ``` -------------------------------- ### Example TOML Configuration for Candid Applications Source: https://github.com/dfinity/candid/blob/master/spec/Type-selector.md This TOML example demonstrates how to specify configurations for different Candid applications, specifically 'random' data generation and 'rust' binding generation. The `[random]` section configures tree depth and leaf value ranges, while the `[rust]` section sets visibility, derive attributes, integer type mapping, and function argument naming for generated Rust code. This format allows users to define arbitrary key-value pairs tied to specific `.did` files. ```TOML [random] left.tree = { depth = 1, range = [-200, -100] } right.tree = { depth = 5, range = [100, 200] } [rust] visibility = "pub(crate)" attributes = "#[derive(CandidType, Deserialize, Clone, Debug)]" int.use_type = "i128" f.arg0.name = "input" ``` -------------------------------- ### Defining an Initial Candid Service Interface Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-concepts.adoc This snippet defines an initial Candid service interface named 'counter'. It includes methods for adding, subtracting, getting a value, and subscribing to updates. The 'get' method is marked as a 'query' call, indicating it does not modify the service's state. ```Candid service counter : { add : (nat) -> (); subtract : (nat) -> (); get : () -> (int) query; subscribe : (func (int) -> ()) -> (); } ``` -------------------------------- ### Adding a Simple Ping Method to Candid Service Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-concepts.adoc This example demonstrates how to add a basic 'ping' method to a Candid service. The method takes no arguments and returns no results, represented by empty sequences '()', showcasing fundamental method declaration. ```Candid service : { ping : () -> (); } ``` -------------------------------- ### Candid Function Type Syntax Examples Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-types.adoc This snippet provides various examples of Candid `func` type syntax. It showcases different function signatures, including those with no arguments or results, single arguments/results, named parameters, and the `query` annotation for read-only methods, as well as higher-order functions. ```Candid func () -> () func (text) -> (text) func (dividend : nat, divisor : nat) -> (div : nat, mod : nat); func () -> (int) query func (func (int) -> ()) -> () ``` -------------------------------- ### Candid: Variant Type Examples Source: https://github.com/dfinity/candid/blob/master/spec/Candid.md Illustrates examples of Candid variant type definitions, including a simple enumeration (`color`) and a recursive variant (`tree`). The `tree` example demonstrates how variants can contain complex nested types, including records and self-references. ```Candid type color = variant { red; green; blue }; type tree = variant { leaf : int; branch : record {left : tree; val : int; right : tree}; } ``` -------------------------------- ### Candid: Record Type Examples Source: https://github.com/dfinity/candid/blob/master/spec/Candid.md Provides examples of Candid record type definitions, demonstrating both named fields and the tuple field shorthand. The latter two examples show equivalent record definitions, highlighting how omitted field IDs are implicitly assigned numeric values. ```Candid record { name : text; street : text; num : nat; city : text; zip : nat; } record { nat; nat } record { 0 : nat; 1 : nat } ``` -------------------------------- ### Representing Candid Record Values - Textual Syntax Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-types.adoc Shows examples of textual representations for Candid record values, demonstrating how to assign values to named fields, fields with special characters, and tuple-like records. ```Candid record {} record { first_name = "John"; second_name = "Doe" } record { "name with spaces" = 42; "unicode, too: ☃" = true } record { "a"; "tuple"; null } ``` -------------------------------- ### Generating Random Candid Values with didc Examples Source: https://github.com/dfinity/candid/blob/master/tools/didc/README.md These examples showcase `didc random` for generating arbitrary Candid values. It demonstrates generating values based on a type, and customizing generation parameters like numeric ranges and text patterns via command-line arguments or a TOML configuration file. ```Shell $ didc random -t '(int, text)' (-72_594_379_354_493_140_610_202_928_640_651_761_468, "_J`:t7^>") ``` ```Shell $ didc random -t '(int, text)' -c 'random = { range = [-10, +10], text = "name" }' (-6, "Cindy Klocko") ``` ```Shell $ didc random -d service.did -m method -c random.toml -a '("seed argument")' -l js [new BigNumber('-4'), 'Marcus Kris'] ``` -------------------------------- ### Candid Natural Number (nat) Type Syntax Examples Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-types.adoc Demonstrates textual representations for the Candid `nat` type, which represents unbounded non-negative integers. Examples include decimal numbers, numbers with underscores for readability, and hexadecimal numbers. ```Candid 1234 1_000_000 0xDEAD_BEEF ``` -------------------------------- ### Candid Function Textual Syntax Examples Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-types.adoc This snippet demonstrates the textual syntax for referencing Candid functions, typically used for public methods of services identified by their principal. It includes examples of referencing methods with standard names and those containing special characters, like the snowflake emoji. ```Candid func "w7x7r-cok77-xa".hello func "w7x7r-cok77-xa"."☃" func "aaaaa-aa".create_canister ``` -------------------------------- ### Defining an Empty Candid Service Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-concepts.adoc This snippet illustrates the simplest possible Candid service description, which defines a service with no public methods. It serves as a foundational example for understanding the basic syntax of a Candid service. ```Candid service : {} ``` -------------------------------- ### Candid Fixed-Size Integer Type Annotation Examples Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-types.adoc Illustrates how to use type annotations in Candid textual syntax to distinguish between different fixed-size integer types like `nat8` and `int8`, and how to explicitly specify `nat64` using parentheses. ```Candid 100 : nat8 -100 : int8 (42 : nat64) ``` -------------------------------- ### Candid Integer (int) Type Syntax Examples Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-types.adoc Shows textual representations for the Candid `int` type, which represents unbounded whole numbers (positive, negative, and zero). Examples include decimal numbers, numbers with underscores, and hexadecimal numbers, with explicit signs. ```Candid 1234 -1234 +1234 1_000_000 -1_000_000 +1_000_000 0xDEAD_BEEF -0xDEAD_BEEF +0xDEAD_BEEF ``` -------------------------------- ### Candid Service Method with Multiple Arguments (Original) Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-types.adoc This example shows a Candid service method signature with multiple named text arguments. It sets the context for demonstrating how argument changes can be handled, or mishandled, in Candid. ```Candid service { foo : (first_name : text, middle_name : text, last_name : text) -> () } ``` -------------------------------- ### Evolving a Candid Service Interface Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-concepts.adoc This snippet shows an evolved version of the 'counter' service interface, demonstrating Candid's subtyping rules. It introduces a 'set' method, modifies existing methods like 'add' and 'subtract' with new return values and optional parameters, and extends 'get' and 'subscribe' with additional return values and optional parameters, respectively, ensuring backward compatibility. ```Candid type timestamp = nat; service counter : { set : (nat) -> (); add : (int) -> (new_val : nat); subtract : (nat, trap_on_underflow : opt bool) -> (new_val : nat); get : () -> (nat, last_change : timestamp) query; subscribe : (func (nat) -> (unregister : opt bool)) -> (); } ``` -------------------------------- ### Candid Configuration Example: Limiting Tree Depth Source: https://github.com/dfinity/candid/blob/master/tools/didc/config.md This Candid code snippet demonstrates how to configure a specific branch of a tree to limit its depth to 1. It highlights the verbose nature of Candid's textual representation when expressing nested configuration options, contrasting it with the more concise Dhall syntax. ```Candid vec { record { "left"; record { branch = vec { record { "tree"; record { config = opt record { depth = opt 1 }; branch = vec {} } } }; } }; } ``` -------------------------------- ### Example Candid Interface Definition Source: https://github.com/dfinity/candid/blob/master/spec/Type-selector.md This Candid Interface Definition Language (IDL) snippet provides a concrete example of Candid types and a service. It defines a recursive `tree` variant type, a `pair` record type, and a service with a function `f` that takes two `pair` arguments and returns one `pair`. This interface is used to illustrate how the Candid type selectors would match specific nodes within it. ```Candid IDL type tree = variant { leaf: int; branch: record { left: tree; right: tree } }; type pair = record { left: int; right: int }; service : { f : (pair, pair) -> (pair); } ``` -------------------------------- ### Representing Candid Variant Values - Textual Syntax Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-types.adoc Shows examples of textual representations for Candid variant values, demonstrating how to assign values to specific tags, including tags with special characters and enumeration-like tags. ```Candid variant { ok = 42 } variant { "unicode, too: ☃" = true } variant { fall } ``` -------------------------------- ### Declaring a Candid Service Interface Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-types.adoc This snippet illustrates the basic syntax for defining a service type in Candid. It includes examples of methods with `nat` (natural number) and `int` (integer) parameters and return types, as well as a `query` annotation for read-only methods and a `func` type for higher-order functions. ```Candid service { add : (nat) -> (); subtract : (nat) -> (); get : () -> (int) query; subscribe : (func (int) -> ()) -> (); } ``` -------------------------------- ### Specifying a Query Method in Candid Service Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-concepts.adoc This example specifically focuses on the 'query' annotation applied to the 'get_address' method within a Candid service. It explains that this annotation allows the method to be invoked as an efficient query call, bypassing consensus for faster data retrieval. ```Candid service address_book : { set_address: (name : text, addr : address) -> (); get_address: (name : text) -> (opt address) query; } ``` -------------------------------- ### Candid Service Textual Representation Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-types.adoc This snippet shows examples of how service principals are represented textually in Candid. These string literals typically identify specific service instances on the Internet Computer. ```Candid service "w7x7r-cok77-xa" service "zwigo-aiaaa-aaaaa-qaa3a-cai" service "aaaaa-aa" ``` -------------------------------- ### Candid: Recursive Type Definition Examples Source: https://github.com/dfinity/candid/blob/master/spec/Candid.md Provides examples of recursive type definitions in Candid, including a `stream` and mutually recursive `node` and `list` types. It also demonstrates an invalid cyclic type definition (`A = B; B = A;`) that is disallowed due to being vacuous. ```Candid type stream = opt record {head : nat; next : func () -> stream}; type node = record {head : nat; tail : list}; type list = opt node; type A = B; type B = A; // error: cyclic type definition ``` -------------------------------- ### Candid Text Type Syntax Examples Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-types.adoc Illustrates various textual representations for the Candid `text` type, including empty strings, basic strings, escaped characters (newline, carriage return, tab, backslash, double quote, single quote), and Unicode escapes. It also shows raw byte sequences that must be UTF-8. ```Candid "" "Hello" "Escaped characters: \n \r \t \\ \" \'" "Unicode escapes: \u{2603} is ☃ and \u{221E} is ∞" "Raw bytes (must be utf8): \E2\98\83 is also ☃" ``` -------------------------------- ### Candid: Function Reference Example Source: https://github.com/dfinity/candid/blob/master/spec/Candid.md Illustrates a Candid function reference within a service definition. The `engine` service's `search` method takes a `callback` parameter, which is a function reference, allowing asynchronous results to be returned. ```Candid type engine = service { search : (query : text, callback : func (vec result) -> ()); } ``` -------------------------------- ### Candid Optional Type Literals Syntax Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-types.adoc This snippet illustrates the textual syntax for Candid `opt` (optional) types. It includes examples of the `null` value, an optional boolean, an optional number, a nested optional null, and a doubly nested optional string, showcasing how optional values are expressed. ```Candid null opt true opt 8 opt null opt opt "test" ``` -------------------------------- ### Candid Record Supertyping - Original Type Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-types.adoc Defines an initial Candid record type used as an example for demonstrating supertyping. This type includes fields for first name, second name, and a score. ```Candid record { first_name : text; second_name : text; score : nat } ``` -------------------------------- ### Calling Counter Canister `inc` Method with Argument using dfx Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-howto.adoc This `dfx` command-line example demonstrates how to call the `inc` method of the `counter` canister, passing `42` as the `step` argument. The output `(43)` shows the returned value after the increment operation, confirming successful interaction. ```Bash $ dfx canister call counter inc '(42)' (43) ``` -------------------------------- ### Candid Vector Literals Syntax Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-types.adoc This snippet shows examples of textual syntax for Candid `vec` types. It includes an empty vector and a vector containing two string elements, demonstrating how sequences of values are represented in Candid's textual format. ```Candid vec {} vec { "john@doe.com"; "john.doe@example.com" }; ``` -------------------------------- ### Defining Candid Comment Syntax Source: https://github.com/dfinity/candid/blob/master/spec/Candid.md This snippet defines the syntax for comments in Candid. It shows both single-line comments, starting with `//`, and block comments, enclosed by `/*` and `*/`. Block comments in Candid support proper nesting. ```Candid ::= | //* | /*(|)*/ ``` -------------------------------- ### Candid Service Method Returning `empty` Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-types.adoc This snippet provides a practical example of the `empty` type in Candid. When used as a return type, `empty` signifies that the method 'never returns successfully' because the `empty` type has no possible values. ```Candid service : { always_fails () -> (empty) } ``` -------------------------------- ### Illustrating Positional Typing in Candid Methods Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-concepts.adoc This example highlights Candid's positional typing for method arguments and results. It demonstrates that changing the order of named return values (e.g., 'mod' then 'div') does not alter the method's type, as values are identified by their position, not their names. ```Candid divMod : (dividend : nat, divisor : nat) -> (mod : nat, div : nat); ``` -------------------------------- ### Candid Record Subtyping - Original Type Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-types.adoc Defines an initial Candid record type used as an example for demonstrating subtyping. This type includes fields for first name, optional middle name, second name, and a score. ```Candid record { first_name : text; middle_name : opt text; second_name : text; score : int } ``` -------------------------------- ### Candid Float Literals Syntax Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-types.adoc This snippet demonstrates various valid textual representations for `float32` and `float64` types in Candid, including decimal, scientific, and hexadecimal floating-point notations. These examples illustrate how floating-point numbers are expressed in Candid's textual syntax. ```Candid 1245.678 +1245.678 -1_000_000.000_001 34e10 34E+10 34e-10 0xDEAD.BEEF 0xDEAD.BEEFP-10 0xDEAD.BEEFp+10 ``` -------------------------------- ### Defining Assertion Test Forms for Candid Data Source: https://github.com/dfinity/candid/blob/master/test/README.md This grammar defines the four assertion forms used within Candid test files (`.test.did`). These forms allow asserting successful decoding/parsing, failed decoding/parsing, equality of two decoded/parsed values, or inequality of two decoded/parsed values. The `` can be textual or binary (`blob `), and an optional `` provides a test description. For example, `assert blob "DIDL\00\01\7e\00" == (true) : (bool)` asserts equality. ```Candid Test Grammar ::= | assert : | assert !: | assert == : | assert != : ::= | blob ::= ? ``` -------------------------------- ### Calling Counter Canister `inc` Method with Random Argument using dfx Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-howto.adoc This `dfx` command-line example shows how to call the `inc` method of the `counter` canister without explicitly providing an argument. `dfx` automatically generates a random `nat` value for the `step` argument, and the canister returns the incremented value, useful for quick testing. ```Bash $ dfx canister call counter inc Unspecified argument, sending the following random argument: (1_543_454_453) (1_543_454_454) ``` -------------------------------- ### Defining Candid Variant Type - Shape Example Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-types.adoc Demonstrates the definition of a Candid `variant` type named `shape`, showcasing different tag types including `null`, primitive types, nested records, and tags with unicode characters. ```Candid type shape = variant { dot : null; circle : float64; rectangle : record { width : float64; height : float64 }; "💬" : text; }; ``` -------------------------------- ### Defining Counter Canister Interface in Candid Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-howto.adoc This Candid interface definition specifies a `Counter` service with a single method `inc`. The `inc` method takes one argument, `step`, of type `nat` (natural number), and returns a value of type `nat`. This interface serves as an example for subsequent interactions. ```Candid service Counter : { inc : (step: nat) -> (nat); } ``` -------------------------------- ### Candid Record Supertyping - Evolved Type Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-types.adoc Illustrates an evolved Candid record type that is a supertype of the original. This example shows how fields can be removed (second_name), their types changed (score from nat to int), and optional fields added (country). ```Candid record { first_name : text; score: int; country : opt text } ``` -------------------------------- ### Candid Service with Higher-Order Functions (Inbound/Outbound) Source: https://github.com/dfinity/candid/blob/master/spec/Candid.md This example illustrates a Candid service with higher-order functions 'h1' and 'h2', which take functions as parameters. 'h1' expects a function that produces 't' (outbound from 'f1''s perspective), and 'h2' expects a function that consumes 't' (inbound to 'f2''s perspective). It highlights how subtyping rules apply recursively, allowing 't' to be extended safely even when passed as a function parameter. ```Candid type t = {x : nat}; service : { h1 : (f1 : () -> t) -> (); // might call f1() and expects a t h2 : (f2 : t -> ()) -> (); // might call f2({x = 5}) } ``` -------------------------------- ### Candid Service Definition for Rust Canister Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-howto.adoc This Candid service definition (`.did` file) manually describes the `hello` canister's interface. It specifies a `greet` method that takes no arguments and returns a `text` type. This file is essential for other canisters or tools to interact with the Rust-implemented `hello` canister. ```candid service : { greet : () -> (text); } ``` -------------------------------- ### Defining Candid Name and Identifier Syntax Source: https://github.com/dfinity/candid/blob/master/spec/Candid.md This snippet specifies the syntax for names in Candid. A name can be either a standard identifier, following typical programming language rules (alphanumeric and underscore, starting with alpha or underscore), or an arbitrary string enclosed in double quotes. Quoted text strings are used when a name conflicts with a Candid keyword. ```Candid ::= | ::= (A..Z|a..z|_)(A..Z|a..z|_|0..9)* ::= "*" ``` -------------------------------- ### Importing Core Functions from @dfinity/didc - JavaScript Source: https://github.com/dfinity/candid/blob/master/tools/didc-js/wasm-package/README.md This snippet demonstrates how to import the essential functions `getServiceMethods`, `encode`, and `decode` from the `@dfinity/didc` library. These functions are crucial for interacting with Candid values in JavaScript projects. ```javascript import { getServiceMethods, encode, decode } from "@dfinity/didc"; ``` -------------------------------- ### Adding Services: State Transition Rule Source: https://github.com/dfinity/candid/blob/master/spec/IDL-Soundness.md This rule describes how a new service 'A' with type 's' can be added to the global state 'S'. The premise 'A fresh in S' ensures that 'A' is not already present in the state. The conclusion shows the state 'S' transitioning to a new state where 'A : s' is added to 'S'. ```Type Theory Notation A fresh in S ───────────────────── S --> (A : s) ∪ S ``` -------------------------------- ### Calling Console Initialization Function - JavaScript Source: https://github.com/dfinity/candid/blob/master/tools/ui/src/candid.html This line executes the `initializeConsoleControls` function, which is responsible for setting up the interactive behavior of the console elements in the Candid UI. It ensures the UI is ready for user interaction upon page load. ```JavaScript initializeConsoleControls(); ``` -------------------------------- ### Learning Service References: State Transition Rule Source: https://github.com/dfinity/candid/blob/master/spec/IDL-Soundness.md This rule allows a service 'B' to learn about a reference to service 'A' at type 's'. The premise 'A : s ∈ S' ensures that service 'A' with type 's' exists in the current state 'S'. The conclusion shows the state 'S' transitioning to include the assertion 'B has A : s', indicating that 'B' now holds a reference to 'A'. ```Type Theory Notation A : s ∈ S ──────────────────────────── S --> (B has A : s) ∪ S ``` -------------------------------- ### Initializing Candid UI Console Controls - JavaScript Source: https://github.com/dfinity/candid/blob/master/tools/ui/src/candid.html This JavaScript function defines the logic for managing the console's display. It retrieves DOM elements, sets up event listeners for output and methods buttons, and includes helper functions to open, close, and switch between the 'Output Log' and 'Methods' panes, ensuring only one is active at a time. ```JavaScript function initializeConsoleControls() { const consoleEl = document.getElementById('console'); const outputButton = document.getElementById('output-button'); const methodsButton = document.getElementById('methods-button'); const outputPane = document.getElementById('output-pane'); const methodsPane = document.getElementById('methods-pane'); const buttons = [outputButton, methodsButton]; const panes = [outputPane, methodsPane]; function openConsole() { if (!consoleEl.classList.contains('open')) { consoleEl.classList.add('open'); } } function toggleConsole() { if (consoleEl.classList.contains('open')) { consoleEl.classList.remove('open'); buttons.forEach(button => { button.classList.remove('active-tab'); button.blur(); }); panes.forEach(pane => { pane.style.display = 'none'; }); } else { consoleEl.classList.add('open'); } } outputButton.addEventListener('click', () => { if (outputButton.classList.contains('active-tab')) { toggleConsole(); } else { openConsole(); outputPane.style.display = 'block'; outputButton.classList.add('active-tab'); methodsPane.style.display = 'none'; methodsButton.classList.remove('active-tab'); } }); methodsButton.addEventListener('click', () => { if (methodsButton.classList.contains('active-tab')) { toggleConsole(); } else { openConsole(); methodsPane.style.display = 'block'; methodsButton.classList.add('active-tab'); outputPane.style.display = 'none'; outputButton.classList.remove('active-tab'); } }); outputButton.click(); } ``` -------------------------------- ### Generating JavaScript Bindings for Candid Services Source: https://github.com/dfinity/candid/blob/master/tools/didc/README.md This snippet demonstrates using `didc bind` to generate an IDL factory in JavaScript from a Candid DID file. The generated code provides the necessary interface for interacting with a Candid service, defining its methods and their signatures. ```Shell $ didc bind hello.did -t js ``` ```JavaScript export const idlFactory = ({ IDL }) => { return IDL.Service({ 'greet' : IDL.Func([IDL.Text], [IDL.Text], []) }); } ``` -------------------------------- ### Git Release Tagging and Pushing Source: https://github.com/dfinity/candid/blob/master/README.md These shell commands are used to create a new Git tag for a release and then push that tag to the remote origin. The tag is typically named after the release date, and the message for the tag is also the date. ```Shell git tag 2020-04-01 -m "2020-04-01" ``` ```Shell git push origin 2020-04-01 ``` -------------------------------- ### Defining Candid Service with Multiple Methods and Types Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-concepts.adoc This snippet shows a more complex Candid service with two methods: 'reverse' and 'divMod'. It illustrates how to define methods with specific argument and result types (e.g., 'text', 'nat') and how to use named parameters for documentation purposes. ```Candid service : { reverse : (text) -> (text); divMod : (dividend : nat, divisor : nat) -> (div : nat, mod : nat); } ``` -------------------------------- ### Candid Higher-Order Subtyping Soundness Instantiations Source: https://github.com/dfinity/candid/blob/master/spec/Candid.md Provides instantiations for higher-order subtyping soundness in Candid, referencing an external document for full details. It defines how different relations (`~>`, `<:`, `in`, `<:h`) are interpreted in the context of higher-order subtyping, noting that some aspects are still pending or host-language dependent. ```Candid s1 ~> s2 ≔ s2 <: s1 t1 <: t2 ≔ t1 <: t2 s1 in t1 <: s2 in t2 ≔ (to be done) s1 <:h s2 ≔ (host-language dependent) ``` -------------------------------- ### Candid Record Subtyping - Evolved Type Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-types.adoc Illustrates an evolved Candid record type that is a subtype of the original. This example shows how fields can be deprecated (middle_name), their types changed (score from int to nat), and new fields added (country). ```Candid record { first_name : text; middle_name : opt empty; second_name : text; score : nat; country : text } ``` -------------------------------- ### TOML Configuration for didc Rust Bindgen Source: https://github.com/dfinity/candid/blob/master/tools/didc/README.md This TOML configuration file customizes `didc`'s Rust binding generation and random value generation. It specifies the target for Rust bindgen (e.g., `custom`), the Handlebar template file, and various attributes like visibility and derive macros for generated Rust types. ```TOML [didc.rust] target = "custom" # Other targets: canister_call, agent, stub template = "template.hbs" # required for custom target # any tags mentioned from hbs candid_crate = "candid" service_name = "service" [rust] visibility = "pub(crate)" attributes = "#[derive(CandidType, Deserialize, Debug)]" GetBlocksResponse.attributes = "#[derive(CandidType, Deserialize, Debug, Clone, Serialize)]" GetBlocksResponseArchivedBlocksItem.name = "ABetterName" ``` -------------------------------- ### Motoko Actor for Counter Service Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-concepts.adoc This Motoko code defines an actor that implements a simple counter service. It includes public asynchronous functions for adding, subtracting, and subscribing, along with a query function to retrieve the current integer value, demonstrating how a Candid service description can be automatically generated from Motoko source. ```Motoko actor { var v : Int = 0; public func add(d : Nat) : async () { v += d; }; public func subtract(d : Nat) : async () { v -= d; }; public query func get() : async Int { v }; public func subscribe(handler : func (Int) -> async ()) { … } } ``` -------------------------------- ### Defining Candid Type Selector Syntax Source: https://github.com/dfinity/candid/blob/master/spec/Type-selector.md This snippet defines the grammar for the Candid type selector, a configuration language used to select specific type nodes within a Candid interface. It specifies the structure of a selector, which can be a path or a scoped path, and details how paths and scopes are constructed using names, numbers, and predefined prefixes like `func:`, `arg:`, and `ret:`. ```Candid Selector Syntax := (. )? | := (. )* := (. )* := func: | func:init | arg: | ret: ``` -------------------------------- ### Defining Candid Record Types - Syntax Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-types.adoc Illustrates various ways to define record types in Candid, including empty records, records with named fields, fields with special characters, and tuple-like records with implicit labels. ```Candid record {} record { first_name : text; second_name : text } record { "name with spaces" : nat; "unicode, too: ☃" : bool } record { text; text; opt bool } ``` -------------------------------- ### Adding Type Relationship B has C: s2 (Formal Notation) Source: https://github.com/dfinity/candid/blob/master/spec/IDL-Soundness.md This snippet describes the conditions under which the type relationship 'B has C : s2' can be added to the system's state. It relies on an existing relationship 'A has C at s1 ∈ S', a transition '[S] A =(t1)=(t2)=> B' within the state S, and a subtyping condition 's1 in t1 <: s2 in t2'. The subsequent text explains how these conditions ensure 's3 <: s2' for 'C : s3 ∈ S', maintaining consistency. ```Formal Notation A has C at s1 ∈ S [S] A =(t1)=(t2)=> B s1 in t1 <: s2 in t2 ``` -------------------------------- ### Applying Host-Language Subtyping: State Transition Rule Source: https://github.com/dfinity/candid/blob/master/spec/IDL-Soundness.md This rule allows the type of a service reference to be updated based on host-language subtyping. If service 'A' has a reference to service 'B' at type 's1', and 's1' is a host-language subtype of 's2' ('s1 <:h s2'), then the state can transition to reflect that 'A' now holds the reference to 'B' at the more general type 's2'. ```Type Theory Notation A has B at s1 ∈ S s1 <:h s2 ────────────────────────────────── S --> (A has B : s2) ∪ S ``` -------------------------------- ### Defining Candid IDL for Service Methods - JavaScript Source: https://github.com/dfinity/candid/blob/master/tools/didc-js/wasm-package/README.md This snippet defines a Candid Interface Definition Language (IDL) in text format. This IDL describes the service's methods, their input/output types, and custom data structures like `StoreNumberInput`, `InitArgs`, and `SomeType`. It is typically fetched from a canister's `candid:service` public metadata. ```javascript export const IDL = ` type StoreNumberInput = record { number : nat64; }; type InitArgs = record { name : text; }; type SomeType = record { field1 : text; field2 : nat64; }; service : (InitArgs) -> { store_number : (input : StoreNumberInput) -> (); get_number : () -> (nat64) query; }; `; ``` -------------------------------- ### Candid Transitive Coherence Failure Example Source: https://github.com/dfinity/candid/blob/master/spec/Candid.md Illustrates a scenario where transitive coherence does not hold for Candid coercion. It shows that even if `` coerces to `` and `` coerces to ``, coercing `` directly to type `` might result in a different value `` than ``, implying that coercion is not strictly transitive in terms of value identity. ```Candid : ~> : : ~> : : ~> : ``` -------------------------------- ### Defining Root Production for Candid Encoding Tests Source: https://github.com/dfinity/candid/blob/master/test/README.md This snippet defines the root production rule for Candid encoding test files (`.test.did`). An `` consists of zero or more type definitions (``) followed by zero or more encoding tests (``). This structure allows for defining custom types before asserting test conditions. ```Candid Test Grammar ::= ;* ;* ``` -------------------------------- ### Candid Service Method with Record Argument (Original) Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-types.adoc This snippet presents the recommended pattern for Candid service methods that are anticipated to have evolving arguments. By taking a single record as an argument, fields are identified by name, offering flexibility for future changes. ```Candid service { foo : (record { first_name : text; middle_name : text; last_name : text}) -> () } ``` -------------------------------- ### Defining Argument Mapping (A) and Byte Stream (B) in Candid Source: https://github.com/dfinity/candid/blob/master/spec/Candid.md This snippet defines the `A` function for argument mapping, which serializes an argument list into a pair of byte stream `B` and references `R`. It also details the structure of the `B` byte stream, which includes a 'DIDL' magic number, a type definition table `T*`, argument list types `I*`, and argument list values `M`. This structure is also used for function results. ```Candid Notation A(kv* : *) = ( B(kv* : *), R(kv* : *) ) B(kv* : *) = i8('D') i8('I') i8('D') i8('L') magic number T*(*) type definition table I*(*) types of the argument list M(kv* : *) values of argument list ``` -------------------------------- ### Defining Candid Variant Type - Full Null Syntax Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-types.adoc Shows the full, explicit syntax for a Candid variant type where all tags are explicitly typed as `null`, demonstrating the equivalence to the shortened enumeration syntax. ```Candid type season = variant { spring : null; summer: null; fall: null; winter : null } ``` -------------------------------- ### Candid CLI Subcommand Overview Source: https://github.com/dfinity/candid/blob/master/tools/didc/README.md This snippet outlines the primary subcommands available in the `didc` command-line tool, detailing their respective functionalities for Candid file operations, language bindings, testing, encoding, decoding, and random value generation. ```Shell didc 0.1.0 USAGE: didc SUBCOMMANDS: check Type check Candid file bind Binding for different languages test Generate test suites for different languages encode Encode Candid value decode Decode Candid binary data random Generate random Candid values ``` -------------------------------- ### Defining Initial Candid Service Interface Source: https://github.com/dfinity/candid/blob/master/spec/Candid.md This snippet defines an initial Candid interface, 'Version 1', including a record type 't' with a single 'nat' field 'x', and a service with 'produce' (outbound 't') and 'consume' (inbound 't') functions. It serves as a baseline for demonstrating interface evolution. ```Candid // Version 1 type t = {x : nat}; service : { produce : () -> t; consume : t -> (); } ``` -------------------------------- ### Defining Candid Service with Optional Variant Return Type for Extensibility Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-types.adoc This snippet demonstrates an improved Candid service definition where the `get_member_status` method returns an optional variant type. Wrapping the variant in `opt` allows for the addition of new tags in the future, with old clients receiving unknown fields as `null`, ensuring backward compatibility. ```Candid service { get_member_status (member_id : nat) -> (opt variant {active; expired}); } ``` -------------------------------- ### Evolving Services: State Transition Rule Source: https://github.com/dfinity/candid/blob/master/spec/IDL-Soundness.md This rule defines how a service 'A' can evolve its type from 's1' to 's2'. The premise 's1 ~> s2' indicates that 's1' can evolve into 's2' according to the IDL's evolution rules. The conclusion shows the state transitioning from 'A' having type 's1' to 'A' having type 's2', while the rest of the state 'S'' remains unchanged. ```Type Theory Notation s1 ~> s2 ──────────────────────────────── { A : s1, S' } --> { A : s2, S'} ``` -------------------------------- ### Defining Candid Import Declarations Source: https://github.com/dfinity/candid/blob/master/spec/Candid.md This grammar rule defines the syntax for import declarations in Candid, allowing interface definitions to be modularized across multiple files. It specifies the `import` keyword, optionally followed by `service`, and a URL text string referring to the imported file. ```Candid ::= ... | import service? ``` -------------------------------- ### Sending Service References: State Transition Rule Source: https://github.com/dfinity/candid/blob/master/spec/IDL-Soundness.md This rule describes the state transition when service 'A' sends a reference to service 'C' to service 'B'. It requires 'A' to already have a reference to 'C' at type 's1', 'A' to be able to send a message of type 't1' to 'B' expecting 't2', and the reference type 's1' within 't1' to be subtype-compatible with 's2' within 't2'. The result is that 'B' gains a reference to 'C' at type 's2'. ```Type Theory Notation A has C at s1 ∈ S [S] A =(t1)=(t2)=> B s1 in t1 <: s2 in t2 ──────────────────────────────────────────────────────────────────── S --> (B has C : s2) ∪ S ``` -------------------------------- ### Encoding Candid Values (M) to Byte Sequences - Formal Specification Source: https://github.com/dfinity/candid/blob/master/spec/Candid.md This snippet defines the `M` function, which maps Candid values to their corresponding byte sequences, indexed by their type. It specifies how primitive values (e.g., `nat`, `int`, `float`, `bool`, `text`, `null`) are encoded using `leb128`, `sleb128`, or direct byte representations. It also details the encoding of composite values (e.g., `opt`, `vec`, `record`, `variant`) and reference types (e.g., `service`, `func`, `principal`), including how optional values, vectors, and record fields are serialized. ```Formal Specification M : -> -> i8* M(n : nat) = leb128(n) M(i : int) = sleb128(i) M(n : nat) = i(n) M(i : int) = i(signed_N^-1(i)) M(z : float) = f(z) M(b : bool) = i8(if b then 1 else 0) M(t : text) = leb128(|utf8(t)|) i8*(utf8(t)) M(_ : null) = . M(_ : reserved) = . // NB: M(_ : empty) will never be called M : -> -> i8* M(null : opt ) = i8(0) M(?v : opt ) = i8(1) M(v : ) M(v^N : vec ) = leb128(N) M(v : )^N M(kv* : record {*}) = M(kv : )* M(kv : variant {*}) = leb128(i) M(kv : *[i]) M : (, ) -> -> i8* M((k,v) : k:) = M(v : ) M : -> -> i8* M(ref(r) : service ) = i8(0) M(id(v*) : service ) = i8(1) M(v* : vec nat8) M(ref(r) : func ) = i8(0) M(pub(s,n) : func ) = i8(1) M(s : service {}) M(n : text) M(ref(r) : principal) = i8(0) M(id(v*) : principal) = i8(1) M(v* : vec nat8) ``` -------------------------------- ### Mapping Candid Function Types to Motoko Source: https://github.com/dfinity/candid/blob/master/docs/modules/candid-guide/pages/candid-types.adoc This Motoko snippet shows the direct correspondence of the Candid function types defined previously. It illustrates how Candid `func` types map to `shared` Motoko functions, with `async` wrapping non-`oneway` results and arguments/results becoming tuples when multiple are present. ```Motoko type F0 = shared () -> async (); type F1 = shared Text -> async Text; type F2 = shared (Text, Bool) -> (); type F3 = shared (text) -> (); type F4 = shared query () -> async Text; ``` -------------------------------- ### Encoding Candid Service Constructor Parameters to Hex - JavaScript Source: https://github.com/dfinity/candid/blob/master/tools/didc-js/wasm-package/README.md This snippet shows how to encode Candid text values into a hex representation for the service's constructor parameters. The `encode` function is used with the `serviceParams` kind to target the initialization arguments. ```javascript const encoded = encode({ idl: IDL, input: '(record { name="MyCanister" })', withType: { kind: "serviceParams" }, targetFormat: "hex" }); ``` -------------------------------- ### Retrieving Service Method Names from IDL - JavaScript Source: https://github.com/dfinity/candid/blob/master/tools/didc-js/wasm-package/README.md This snippet shows how to use the `getServiceMethods` function to extract an array of method names defined within a Candid IDL string. This is useful for dynamically listing available methods in a service. ```javascript const methods = getServiceMethods(IDL); ``` -------------------------------- ### Candid Syntactic Shorthands for Values Source: https://github.com/dfinity/candid/blob/master/spec/Candid.md These grammar rules define syntactic shorthands for Candid values that simplify common patterns. They include `blob ` for byte vectors, named fields in records mapping to hashed natural numbers, implicit field indices for records, and shorthand for null values in variants. ```Candid ::= ... | blob := vec { N;* } where N;* is the sequence of bytes in the string, interpreted [as in the WebAssembly textual format](https://webassembly.github.io/spec/core/text/values.html#strings) ::= ... | = := = | := N = where N is either 0 or previous + 1 (only in records) | := = null (only in variants) | := = null (only in variants) ```