### Start Clean Local Internet Computer Replica Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/deployment.md This command starts the local Internet Computer replica after cleaning its `dfx` state for the project. It's useful for resolving strange replica behavior or ensuring a fresh start, effectively resetting the local environment. ```bash dfx start --clean ``` -------------------------------- ### Bash Commands for Kybra Virtual Environment Setup and Deployment Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/deployment.md This snippet provides a sequence of bash commands to set up a Python virtual environment, activate it, install Kybra, install the Kybra DFX extension, and deploy your application. These steps are crucial for resolving many common deployment failures related to environment configuration. ```Bash ~/.pyenv/versions/3.10.7/bin/python -m venv venv source venv/bin/activate pip install kybra python -m kybra install-dfx-extension dfx deploy ``` -------------------------------- ### Install dfx 0.23.0 Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/installation.md This command installs dfx version 0.23.0 using the official DFINITY SDK installer script. It sets the DFX_VERSION environment variable before executing the installation script. ```bash DFX_VERSION=0.23.0 sh -ci "$(curl -fsSL https://sdk.dfinity.org/install.sh)" ``` -------------------------------- ### Start Local Internet Computer Replica Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/deployment.md This command initializes and starts a local Internet Computer replica in the project's root directory. It's essential for local development and testing of canisters before deploying to mainnet. The replica runs in the foreground by default. ```bash dfx start ``` -------------------------------- ### Start Background IC Replica with No Delay Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/deployment.md This command combines starting the local Internet Computer replica in the background with disabling artificial delays. It provides the fastest possible local deployment experience while freeing up the terminal for other tasks, ideal for active development. ```bash dfx start --background --artificial-delay 0 ``` -------------------------------- ### Start Local IC Replica with No Delay Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/deployment.md This command starts the local Internet Computer replica with artificial delays set to zero, resulting in faster deployments. It's recommended for development environments where rapid iteration and quick deployments are crucial for efficiency. ```bash dfx start --artificial-delay 0 ``` -------------------------------- ### Start Local IC Replica in Background Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/deployment.md Use this command to start the local Internet Computer replica as a background process. This allows you to continue using the terminal for other commands while the replica runs. It's useful for continuous development workflows. ```bash dfx start --background ``` -------------------------------- ### Install Python 3.10.7 using pyenv Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/installation.md This snippet installs pyenv using a curl script and then uses pyenv to install Python version 3.10.7. Ensure you have curl installed on your system before running these commands. ```bash # install pyenv curl https://pyenv.run | bash # install Python 3.10.7 ~/.pyenv/bin/pyenv install 3.10.7 ``` -------------------------------- ### Bash: Start Local DFX Replica in Background Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/hello_world.md This command starts the local DFX replica in the background, which is a prerequisite for deploying and testing Kybra canisters locally. It allows for continued command-line interaction while the replica runs. ```bash dfx start --background ``` -------------------------------- ### Add dfx to PATH in .bashrc Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/installation.md If dfx commands are not found after installation, this snippet appends the '$HOME/bin' directory to your PATH environment variable in the '.bashrc' file. This ensures the dfx executable is discoverable by your shell. ```bash echo 'export PATH="$PATH:$HOME/bin"' >> "$HOME/.bashrc" ``` -------------------------------- ### Start DFX Local Replica for Deployment Source: https://github.com/demergent-labs/kybra/blob/main/docs/hello_world.html These shell commands are used to start a local DFX replica in the background, which is necessary before deploying canisters. The second command provides an option to disable artificial delays for faster deployments. ```Shell dfx start --background ``` ```Shell dfx start --background --artificial-delay 0 ``` -------------------------------- ### Bash: Install Kybra Library and DFX Extension Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/hello_world.md This snippet installs the `kybra` Python package and its associated `dfx` extension using `pip`. These are crucial dependencies for developing and deploying Kybra canisters on the Internet Computer. ```bash pip install kybra python -m kybra install-dfx-extension ``` -------------------------------- ### Bash: Start Local DFX Replica with Zero Artificial Delay Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/hello_world.md This command starts the local DFX replica in the background with `--artificial-delay 0`. This option speeds up local deployments by eliminating simulated network latency, useful for rapid development and testing. ```bash dfx start --background --artificial-delay 0 ``` -------------------------------- ### Start DFX Local Replica Source: https://github.com/demergent-labs/kybra/blob/main/docs/deployment.html This snippet demonstrates how to start the Internet Computer local replica. It covers basic startup, background execution, and options for faster deployments by disabling artificial delays. The local replica is essential for developing and testing canisters locally. ```Shell dfx start ``` ```Shell dfx start --background ``` ```Shell dfx start --artificial-delay 0 ``` ```Shell dfx start --background --artificial-delay 0 ``` -------------------------------- ### Implement Kybra Canister Method: init Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/management_canister/start_canister.html This method is called exactly once when the canister is first created and installed. It is used for initial setup, such as initializing global state or performing one-time configurations. This method runs before any other canister methods are invoked. ```APIDOC Canister Method: init() Description: Called exactly once when the canister is first created and installed. Usage: Initializing global state, one-time configurations. ``` -------------------------------- ### Install Kybra and DFX Extension in Python Virtual Environment Source: https://github.com/demergent-labs/kybra/blob/main/docs/hello_world.html This snippet outlines the steps to create and activate a Python virtual environment, then install the Kybra library and its DFX extension. This ensures a clean and isolated development environment for Kybra projects, managing dependencies effectively. ```Shell ~/.pyenv/versions/3.10.7/bin/python -m venv venv source venv/bin/activate pip install kybra python -m kybra install-dfx-extension ``` -------------------------------- ### Install dfx 0.23.0 CLI and add to PATH Source: https://github.com/demergent-labs/kybra/blob/main/docs/installation.html This snippet provides the command to install the dfx 0.23.0 command-line interface, a crucial dependency for Kybra. It also includes an optional command to add the dfx binary to your system's PATH, resolving 'command not found' errors. ```Bash DFX_VERSION=0.23.0 sh -ci "$(curl -fsSL https://sdk.dfinity.org/install.sh)" echo 'export PATH="$PATH:$HOME/bin"' >> "$HOME/.bashrc" ``` -------------------------------- ### Kybra Canister Method: init Source: https://github.com/demergent-labs/kybra/blob/main/docs/query_methods.html Documents the `init` canister method, which is called exactly once when a canister is first created or installed. This method is used for initial setup, state initialization, and resource allocation. ```APIDOC Canister Method: init ``` -------------------------------- ### Kybra Canister Method: init Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/canister_apis/canister_balance.html Defines the 'init' canister method, which is executed exactly once when the canister is first installed on the Internet Computer. Use this method for initial setup and state initialization. ```APIDOC Method: init() Description: Executed once when the canister is installed. Usage: @init def init_canister(): # Initialization logic here ``` -------------------------------- ### Python Example: Start a Kybra Canister Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/management_canister/start_canister.html This snippet demonstrates how to use the `start_canister` function from Kybra's management canister API. It takes a `Principal` as input, representing the canister ID to be started. The function returns a `DefaultResult` indicating success or failure, handling potential errors from the management canister call. ```Python from kybra import ( Async, CallResult, match, Principal, update, Variant, void, ) from kybra.canisters.management import management_canister class DefaultResult(Variant, total=False): Ok: bool Err: str @update def execute_start_canister(canister_id: Principal) -> Async[DefaultResult]: call_result: CallResult[void] = yield management_canister.start_canister( {"canister_id": canister_id} ) return match( call_result, {"Ok": lambda _: {"Ok": True}, "Err": lambda err: {"Err": err}} ) ``` -------------------------------- ### Install Kybra 0.7.1 Python Package Source: https://github.com/demergent-labs/kybra/blob/main/examples/motoko_examples/hello-world/requirements.txt This snippet demonstrates how to install the Kybra 0.7.1 Python package using pip, the standard Python package installer. Kybra allows developers to write smart contracts for the Internet Computer in Python. Ensure you have Python and pip installed and accessible in your environment before running this command. ```bash pip install kybra==0.7.1 ``` -------------------------------- ### Install Python 3.10.7 using pyenv Source: https://github.com/demergent-labs/kybra/blob/main/docs/installation.html This snippet demonstrates how to install pyenv, a Python version management tool, and then use it to install the specific Python version 3.10.7 required for Kybra. Ensure you have curl installed before running these commands. ```Bash # install pyenv curl https://pyenv.run | bash # install Python 3.10.7 ~/.pyenv/bin/pyenv install 3.10.7 ``` -------------------------------- ### Canister Method: init Reference in Kybra Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/management_canister/sign_with_ecdsa.html This entry provides the API reference for the 'init' canister method in Kybra. This method is called exactly once when a canister is first created and installed. It is used for initial setup and configuration of the canister's state. ```APIDOC init ``` -------------------------------- ### Initialize Kybra virtual environment and deploy Source: https://github.com/demergent-labs/kybra/blob/main/docs/deployment.html This sequence of shell commands initializes a Python virtual environment, activates it, installs Kybra, installs the Kybra dfx extension, and then attempts to deploy the canisters. This is a common set of steps to ensure your environment is correctly set up for Kybra deployment. ```Shell ~/.pyenv/versions/3.10.7/bin/python -m venv venv source venv/bin/activate pip install kybra python -m kybra install-dfx-extension dfx deploy ``` -------------------------------- ### Implement Kybra Canister Method: init Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/candid/text.html Details the 'init' canister method, an optional callback function executed exactly once when a canister is first created and installed. This method is used for initial setup, such as initializing state variables or performing one-time configurations. It takes no parameters and returns nothing. ```APIDOC canister_method.init() ``` -------------------------------- ### Deploy Kybra Canister with DFX Source: https://github.com/demergent-labs/kybra/blob/main/docs/hello_world.html This shell command deploys the configured Kybra canister to the local DFX replica. It initiates the process of compiling and installing the canister code onto the local Internet Computer instance. ```Shell dfx deploy ``` -------------------------------- ### Kybra Canister Method: init Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/call_apis/msg_cycles_accept.html The `init` method is a special canister lifecycle hook executed once when the canister is first installed on the Internet Computer. It is used to initialize the canister's state, set up initial configurations, or perform any one-time setup tasks. This method takes no arguments and returns nothing. ```APIDOC Canister Method: init() Description: Executed once when the canister is first installed. Parameters: None Returns: None ``` -------------------------------- ### Kybra Management Canister: Start Canister Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/canister_methods/canister_methods.html Documents the `start_canister` API for the Kybra management canister. This function initiates the execution of a specified canister. ```APIDOC start_canister() ``` -------------------------------- ### Canister Method: init Function Reference Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/timers/set_timer_interval.html Documents the `init` canister method, which is called exactly once when a canister is first deployed or created. This method is used for initial setup, such as initializing stable memory, setting up default configurations, or performing any one-time bootstrapping logic. It ensures the canister starts in a defined state. ```APIDOC Canister Method: init() Description: Called once when the canister is first deployed or created. Parameters: None. Returns: None. Usage: Implement for initial setup and configuration. ``` -------------------------------- ### Python: Start IC Canister with Kybra Management Canister Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/reference/management_canister/start_canister.md This Python snippet demonstrates how to initiate the start of an Internet Computer (IC) canister using Kybra's `management_canister` module. It takes a `Principal` (canister ID) as input and returns a `DefaultResult` indicating the success or failure of the operation. The function handles the asynchronous call and maps the `CallResult` to a user-friendly `DefaultResult` variant. ```Python from kybra import ( Async, CallResult, match, Principal, update, Variant, void, ) from kybra.canisters.management import management_canister class DefaultResult(Variant, total=False): Ok: bool Err: str @update def execute_start_canister(canister_id: Principal) -> Async[DefaultResult]: call_result: CallResult[void] = yield management_canister.start_canister( {"canister_id": canister_id} ) return match( call_result, {"Ok": lambda _: {"Ok": True}, "Err": lambda err: {"Err": err}} ) ``` -------------------------------- ### Resolve 'linker cc not found' error on Ubuntu Source: https://github.com/demergent-labs/kybra/blob/main/docs/installation.html This snippet provides the resolution for the 'linker cc not found' error commonly encountered on Ubuntu during installation. It installs the `build-essential` package, which includes necessary compilers and development tools. ```Bash sudo apt install build-essential ``` -------------------------------- ### Bash: Set Up Kybra Hello World Project Directory Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/hello_world.md This snippet creates the `kybra_hello_world` project directory and its essential subdirectories and files, including `src/main.py` and `dfx.json`, to establish the basic structure for a Kybra canister. ```bash mkdir kybra_hello_world cd kybra_hello_world mkdir src touch src/main.py touch dfx.json ``` -------------------------------- ### Document Kybra Canister Method: init Source: https://github.com/demergent-labs/kybra/blob/main/docs/examples.html This entry documents the 'init' canister method in Kybra. It describes the purpose and behavior of the initialization method, which is called once when the canister is first deployed. ```APIDOC Canister Method: init Description: Called once when the canister is first deployed. ``` -------------------------------- ### Set Message on Kybra Canister via DFX CLI Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/hello_world.md This example illustrates how to update the message on a deployed Kybra canister. It uses the 'dfx canister call' command to set the message to 'Hello World!'. ```bash dfx canister call kybra_hello_world set_message '("Hello World!")' ``` -------------------------------- ### Resolve 'is cmake not installed?' error on Ubuntu Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/installation.md This snippet provides the resolution for the 'is cmake not installed?' error on Ubuntu systems. It installs the 'cmake' package, a cross-platform build system generator. ```bash sudo apt install cmake ``` -------------------------------- ### Set Up Kybra Hello World Project Directory Structure Source: https://github.com/demergent-labs/kybra/blob/main/docs/hello_world.html This snippet provides the shell commands to initialize the project directory and file structure for a new Kybra application. It creates the main project folder, a source directory, and essential configuration files like `main.py` and `dfx.json`. ```Shell mkdir kybra_hello_world cd kybra_hello_world mkdir src touch src/main.py touch dfx.json ``` -------------------------------- ### Canister Method: init Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/call_apis/reject.html Defines the 'init' method, which is called exactly once when a canister is created. It is used for initial setup and configuration. ```APIDOC function init(): void; ``` -------------------------------- ### Python: Execute Canister WASM Module Installation Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/reference/management_canister/install_code.md This Python snippet demonstrates how to install a WASM module onto an Internet Computer canister using Kybra's `management_canister` functionality. It takes a canister ID and the WASM module bytes as input, performs the installation with a specified amount of cycles, and returns a result indicating success or an error message. The `install_code` method is called with `mode: install`. ```Python from kybra import ( Async, blob, CallResult, match, Principal, update, Variant, void, ) from kybra.canisters.management import management_canister class DefaultResult(Variant, total=False): Ok: bool Err: str @update def execute_install_code( canister_id: Principal, wasm_module: blob ) -> Async[DefaultResult]: call_result: CallResult[void] = yield management_canister.install_code( { "mode": {"install": None}, "canister_id": canister_id, "wasm_module": wasm_module, "arg": bytes(), } ).with_cycles(100_000_000_000) return match( call_result, {"Ok": lambda _: {"Ok": True}, "Err": lambda err: {"Err": err}} ) ``` -------------------------------- ### Python Example: Get Rejection Message from Kybra Service Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/call_apis/reject_message.html This example demonstrates how to handle rejections in Kybra by calling a service that rejects and then retrieving the rejection message. It defines a `SomeService` class with a `reject` method and an `update` function `get_rejection_message` that calls this service and uses `ic.reject_message()` to get the reason for rejection. This snippet requires the `kybra` library and an Internet Computer environment. ```Python from kybra import Async, ic, Principal, Service, service_update, update, void class SomeService(Service): @service_update def reject(self, message: str) -> void: ... some_service = SomeService(Principal.from_str("rkp4c-7iaaa-aaaaa-aaaca-cai")) @update def get_rejection_message(message: str) -> Async[str]: yield some_service.reject(message) return ic.reject_message() ``` -------------------------------- ### Canister Method: init Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/canister_methods/canister_methods.html Provides details and usage for the Kybra Canister Method 'init'. This method is called once when the canister is first created or installed. ```APIDOC Canister Method: init Description: Called once when the canister is first created or installed. Parameters: None Returns: None ``` -------------------------------- ### Resolve 'linker cc not found' error on Ubuntu Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/installation.md This snippet provides the resolution for the 'linker cc not found' error commonly encountered on Ubuntu systems. It installs the 'build-essential' package, which provides necessary development tools like the C compiler. ```bash sudo apt install build-essential ``` -------------------------------- ### Bash: Deploy Kybra Canister to Local DFX Replica Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/hello_world.md This command deploys the configured Kybra canister to the running local DFX replica. It compiles the canister and makes it available for interaction, completing the local deployment process. ```bash dfx deploy ``` -------------------------------- ### Canister Method: init Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/canister_methods/pre_upgrade.html Defines the 'init' canister method, which is called exactly once when a canister is first created. This method is used for initial setup, configuration, and state initialization. ```APIDOC service { init: (args: InitArgs) -> (); }; ``` -------------------------------- ### Resolve 'Python ssl extension not compiled' error on Ubuntu Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/installation.md This snippet provides the resolution for the 'ERROR: The Python ssl extension was not compiled. Missing the OpenSSL lib' error on Ubuntu systems. It installs the 'libssl-dev' package, which provides development files for OpenSSL. ```bash sudo apt-get install libssl-dev ``` -------------------------------- ### Build Kybra Book for Deployment with mdBook Source: https://github.com/demergent-labs/kybra/blob/main/contributing/the_kybra_book.md This snippet outlines the steps to build the Kybra documentation for deployment. It navigates to the book's directory and compiles the book into static HTML files, placing them in the specified output directory, typically for static site hosting. After building, the generated files should be committed to Git. ```bash cd the_kybra_book mdbook build --dest-dir ../docs # Then commit the changes to git and merge into main on GitHub ``` -------------------------------- ### Serve Kybra Book Locally with mdBook Source: https://github.com/demergent-labs/kybra/blob/main/contributing/the_kybra_book.md This snippet provides commands to navigate into the 'the_kybra_book' directory and serve the documentation locally using 'mdbook'. It automatically opens the served book in your default web browser, allowing for real-time preview and editing. ```bash cd the_kybra_book mdbook serve --open ``` -------------------------------- ### Kybra Management Canister API: start_canister Source: https://github.com/demergent-labs/kybra/blob/main/docs/query_methods.html Documents the `start_canister` method of the Management Canister, used to start a stopped canister. This allows for controlled activation of canister services. ```APIDOC Management Canister API: start_canister ``` -------------------------------- ### APIDOC: Implement 'init' Canister Method Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/canister_apis/print.html This API reference describes the 'init' canister method. It is a special method that is called exactly once when a canister is created. Canisters can implement this method to perform initial setup and configuration. ```APIDOC service : { init: () -> (); } ``` -------------------------------- ### Python: Execute Canister Install Code with Cycles Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/reference/call_apis/call_with_payment128.md This Python snippet, using the Kybra framework, demonstrates how to call the Internet Computer's management canister to install a WASM module. It includes a 128-bit cycle payment for the operation. The function takes a canister ID and the WASM module as input, returning a result indicating success or failure. ```Python from kybra import Async, blob, CallResult, match, Principal, update, Variant, void from kybra.canisters.management import management_canister class DefaultResult(Variant, total=False): Ok: bool Err: str @update def execute_install_code( canister_id: Principal, wasm_module: blob ) -> Async[DefaultResult]: call_result: CallResult[void] = yield management_canister.install_code( { "mode": {"install": None}, "canister_id": canister_id, "wasm_module": wasm_module, "arg": bytes(), } ).with_cycles128(100_000_000_000) return match( call_result, {"Ok": lambda _: {"Ok": True}, "Err": lambda err: {"Err": err}} ) ``` -------------------------------- ### Python Example: Interacting with Kybra StableBTreeMap Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/stable_memory/stable_structures.html This example demonstrates the initialization and usage of Kybra's `StableBTreeMap` for persistent storage in a Python canister. It defines custom key and value types and implements various operations like `insert`, `get`, `contains_key`, and `remove`. This allows data to persist across canister upgrades. ```Python from kybra import ( Alias, nat64, nat8, Opt, query, StableBTreeMap, Tuple, update, Vec, ) Key = Alias[nat8] Value = Alias[str] map = StableBTreeMap[Key, Value](memory_id=0, max_key_size=100, max_value_size=1_000) @query def contains_key(key: Key) -> bool: return map.contains_key(key) @query def get(key: Key) -> Opt[Value]: return map.get(key) @update def insert(key: Key, value: Value) -> Opt[Value]: return map.insert(key, value) @query def is_empty() -> bool: return map.is_empty() @query def items() -> Vec[Tuple[Key, Value]]: return map.items() @query def keys() -> Vec[Key]: return map.keys() @query def len() -> nat64: return map.len() @update def remove(key: Key) -> Opt[Value]: return map.remove(key) @query def values() -> Vec[Value]: return map.values() ``` -------------------------------- ### DFX Deployment Output for Web UI Access Source: https://github.com/demergent-labs/kybra/blob/main/docs/hello_world.html This text snippet shows the typical output from the `dfx deploy` command, providing the URL to access the deployed Kybra canister's Candid interface via a web browser. This URL allows for graphical interaction with the canister's methods. ```Text Deployed canisters. URLs: Backend canister via Candid interface: kybra_hello_world: http://127.0.0.1:8000/?canisterId=ryjl3-tyaaa-aaaaa-aaaba-cai&id=rrkah-fqaaa-aaaaa-aaaaq-cai ``` -------------------------------- ### Access Kybra Canister Web UI from DFX Output Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/hello_world.md This snippet shows the terminal output after deploying a canister, which includes the URL for accessing its web user interface. Users can open this URL in a browser to interact with the canister graphically. ```bash Deployed canisters. URLs: Backend canister via Candid interface: kybra_hello_world: http://127.0.0.1:8000/?canisterId=ryjl3-tyaaa-aaaaa-aaaba-cai&id=rrkah-fqaaa-aaaaa-aaaaq-cai ``` -------------------------------- ### Kybra Canister Method: init Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/candid/nat64.html Defines the 'init' canister method, which is executed exactly once when a Kybra canister is first deployed. This method is used for initial setup, configuration, and state initialization. ```APIDOC function init(); ``` -------------------------------- ### Canister Method: init Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/stable_memory/stable_grow.html Defines the 'init' canister method, which is called exactly once when a canister is first created. This method is used for initial setup and configuration. ```APIDOC function init(): void { // Called exactly once when the canister is first created. // Used for initial setup, state initialization, and configuration. // Parameters: None. // Returns: void. } ``` -------------------------------- ### Install Code on the Internet Computer with Kybra Python Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/management_canister/install_code.html This Python snippet demonstrates how to install a WebAssembly module onto an Internet Computer canister using Kybra's `management_canister.install_code` function. It takes a `canister_id` and `wasm_module` as input, attaches cycles for the operation, and returns a `DefaultResult` indicating success or an error. This function is asynchronous and handles the `CallResult` from the management canister. ```Python from kybra import ( Async, blob, CallResult, match, Principal, update, Variant, void, ) from kybra.canisters.management import management_canister class DefaultResult(Variant, total=False): Ok: bool Err: str @update def execute_install_code( canister_id: Principal, wasm_module: blob ) -> Async[DefaultResult]: call_result: CallResult[void] = yield management_canister.install_code( { "mode": {"install": None}, "canister_id": canister_id, "wasm_module": wasm_module, "arg": bytes(), } ).with_cycles(100_000_000_000) return match( call_result, {"Ok": lambda _: {"Ok": True}, "Err": lambda err: {"Err": err}} ) ``` -------------------------------- ### Management Canister: install_code Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/canister_methods/pre_upgrade.html Provides the 'install_code' method of the Management Canister, allowing a canister to install or upgrade the Wasm module of another canister. This is crucial for deploying and updating applications. ```APIDOC service { install_code: (args: InstallCodeArgs) -> (); }; ``` -------------------------------- ### Document Kybra Canister Method: http_request Source: https://github.com/demergent-labs/kybra/blob/main/docs/examples.html This entry documents the 'http_request' canister method in Kybra. It describes the purpose and behavior of this method for handling incoming HTTP GET requests, including its parameters and expected return format. ```APIDOC Canister Method: http_request Description: Handles incoming HTTP GET requests to the canister. ``` -------------------------------- ### Management Canister: install_code Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/candid/int.html Provides a reference for the Kybra Management Canister function 'install_code'. This function installs or upgrades the Wasm code of a canister. ```APIDOC // Refer to Kybra documentation for the full API definition of 'install_code' ``` -------------------------------- ### Kybra Python: Send Cycles and Get Refunded Amount Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/reference/call_apis/msg_cycles_refunded.md This Python snippet illustrates how to send a specified amount of cycles (1,000,000 in this example) to another Kybra service's method (`receive_cycles` on the `Cycles` canister) and then retrieve the amount of cycles refunded from that call. It uses `ic.msg_cycles_refunded()` to get the refund amount upon a successful call or returns an error string if the call fails. The `Cycles` service is an external dependency. ```Python from kybra import ( Async, CallResult, ic, match, nat64, Principal, Service, service_update, update, Variant, ) class SendCyclesResult(Variant, total=False): Ok: nat64 Err: str class Cycles(Service): @service_update def receive_cycles(self) -> nat64: ... cycles = Cycles(Principal.from_str("rrkah-fqaaa-aaaaa-aaaaq-cai")) # Reports the number of cycles returned from the Cycles canister @update def send_cycles() -> Async[SendCyclesResult]: result: CallResult[nat64] = yield cycles.receive_cycles().with_cycles(1_000_000) return match( result, { "Ok": lambda _: {"Ok": ic.msg_cycles_refunded()}, "Err": lambda err: {"Err": err}, }, ) ``` -------------------------------- ### Common dfx Canister Interaction Commands Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/deployment.md This snippet provides a collection of frequently used `dfx` commands for building, deploying, uninstalling, and calling methods on Internet Computer canisters. These commands are essential for managing and interacting with your deployed code from the command line. ```bash # assume a canister named my_canister # builds and deploys all canisters specified in dfx.json dfx deploy # builds all canisters specified in dfx.json dfx build # builds and deploys my_canister dfx deploy my_canister # builds my_canister dfx build my_canister # removes the Wasm binary and state of my_canister dfx uninstall-code my_canister # calls the method_name method on my_canister with a string argument dfx canister call my_canister method_name '("This is a Candid string argument")' ``` -------------------------------- ### Python: Get Rejection Code for Invalid Destination Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/call_apis/reject_code.html This Python example demonstrates how to call a nonexistent canister and then retrieve the RejectionCode using ic.reject_code(). It showcases handling DestinationInvalid errors that occur when attempting to interact with an invalid or non-existent canister principal. ```Python from kybra import ( Async, ic, Principal, RejectionCode, Service, service_update, update, void, ) class Nonexistent(Service): @service_update def method(self) -> void: ... nonexistent_canister = Nonexistent(Principal.from_str("rkp4c-7iaaa-aaaaa-aaaca-cai")) @update def get_rejection_code_destination_invalid() -> Async[RejectionCode]: yield nonexistent_canister.method() return ic.reject_code() ``` -------------------------------- ### Canister Method: init Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/stable_memory/stable64_size.html This canister method is called exactly once when a canister is first created. It is used to perform initial setup, such as initializing state variables or configuring dependencies. ```APIDOC service { init: (args: InitArgs) -> () oneway; } ``` -------------------------------- ### Initialize Kybra Book Theme and Sidebar with JavaScript Source: https://github.com/demergent-labs/kybra/blob/main/docs/examples.html This JavaScript snippet initializes the theme (dark/light mode) and sidebar visibility settings for the Kybra Book documentation site. It retrieves user preferences from local storage or defaults to system preferences, applying the chosen theme and sidebar state to the HTML document. ```JavaScript var path_to_root = ""; var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light"; try { var theme = localStorage.getItem('mdbook-theme'); var sidebar = localStorage.getItem('mdbook-sidebar'); if (theme.startsWith('"') && theme.endsWith('"')) { localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1)); } if (sidebar.startsWith('"') && sidebar.endsWith('"')) { localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1)); } } catch (e) { } var theme; try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { } if (theme === null || theme === undefined) { theme = default_theme; } var html = document.querySelector('html'); html.classList.remove('no-js') html.classList.remove('light') html.classList.add(theme); html.classList.add('js'); var html = document.querySelector('html'); var sidebar = null; if (document.body.clientWidth >= 1080) { try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { } sidebar = sidebar || 'visible'; } else { sidebar = 'hidden'; } html.classList.remove('sidebar-visible'); html.classList.add("sidebar-" + sidebar); ``` -------------------------------- ### Kybra Canister Method: init Function Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/management_canister/raw_rand.html Defines the `init` canister method, which is executed exactly once when a canister is first created. This method is used for initial setup, configuration, and state initialization. ```APIDOC Kybra Canister Method: init Description: A special canister method executed exactly once when the canister is first created. Used for initial setup. Function Signature: init() -> null Parameters: - None Returns: - null: This method does not return a value. ``` -------------------------------- ### JSON: Configure dfx.json for Kybra Canister Deployment Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/hello_world.md This `dfx.json` configuration file defines the `kybra_hello_world` canister. It specifies the canister type as `kybra` and points to `src/main.py` as the main source file, enabling `dfx` to build and deploy the canister. ```json { "canisters": { "kybra_hello_world": { "type": "kybra", "main": "src/main.py" } } } ``` -------------------------------- ### Create a Simple Kybra Python Counter Canister Source: https://github.com/demergent-labs/kybra/blob/main/examples/randomness/requirements.txt This example shows a basic Kybra smart contract implementing a counter. It includes an initialization function, a query method to get the count, and an update method to increment it. This demonstrates fundamental Kybra decorators and state management. ```Python from kybra import query, update, init class Counter: count: int = 0 @init def init(self): self.count = 0 @query def get_count(self) -> int: return self.count @update def increment_count(self): self.count += 1 ``` -------------------------------- ### Get Rejection Code for Invalid Destination in Kybra Python Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/reference/call_apis/reject_code.md This Python example illustrates how to retrieve a rejection code when attempting to call a method on a nonexistent Kybra canister. It defines a `Nonexistent` service and an update function that calls a method on an invalid principal, then captures the `RejectionCode` using `ic.reject_code()`. ```Python from kybra import ( Async, ic, Principal, RejectionCode, Service, service_update, update, void, ) class Nonexistent(Service): @service_update def method(self) -> void: ... nonexistent_canister = Nonexistent(Principal.from_str("rkp4c-7iaaa-aaaaa-aaaca-cai")) @update def get_rejection_code_destination_invalid() -> Async[RejectionCode]: yield nonexistent_canister.method() return ic.reject_code() ``` -------------------------------- ### Deploy All Canisters to Local IC Replica Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/deployment.md This command builds and deploys all canisters defined in your `dfx.json` file to the local Internet Computer replica. It's the primary command for pushing your entire project's code to the local development environment for testing. ```bash dfx deploy ``` -------------------------------- ### Management Canister API: install_code Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/management_canister/deposit_cycles.html Describes the 'install_code' method, enabling a canister to install or upgrade code on another canister. This is a core operation for deploying and updating decentralized applications. ```APIDOC install_code ``` -------------------------------- ### Canister Method: init Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/management_canister/delete_canister.html Defines the `init` method, a special canister method that is called exactly once when a canister is first created and installed. This method is used for initial setup, such as initializing state variables or performing one-time configurations. It runs before any other public methods can be called. ```APIDOC service Canister { init(args: any): (); } ``` -------------------------------- ### Management Canister API: install_code Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/candid/candid.html Reference documentation for the 'install_code' Management Canister API in Kybra. This API allows a canister to install or upgrade the code of another canister. ```APIDOC install_code ``` -------------------------------- ### Kybra Canister Method: init Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/candid/variant.html This snippet references the 'init' canister method in Kybra. This method is called exactly once when the canister is first created, allowing for initial setup and state initialization. ```APIDOC CanisterMethod init(): Called once upon canister creation for initialization. ``` -------------------------------- ### Canister Method: init Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/management_canister/uninstall_code.html Documents the 'init' canister method in Kybra. This method is called exactly once when a canister is first deployed, used for initial setup and state initialization. ```APIDOC init ``` -------------------------------- ### Bash: Create and Activate Python Virtual Environment for Kybra Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/hello_world.md This snippet demonstrates how to create a Python virtual environment named `venv` and activate it. This isolates project dependencies, ensuring a clean development environment for Kybra. ```bash ~/.pyenv/versions/3.10.7/bin/python -m venv venv source venv/bin/activate ``` -------------------------------- ### Canister Method: init Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/management_canister/deposit_cycles.html Describes the 'init' canister method, a special callback executed exactly once when a canister is first created. This method is used for initial setup, state initialization, and resource allocation. ```APIDOC init ``` -------------------------------- ### Verify Message on Kybra Canister via DFX CLI Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/hello_world.md After setting a message, this snippet shows how to confirm the update by retrieving the message again. The expected output is '("Hello World!")', confirming the message was successfully stored. ```bash dfx canister call kybra_hello_world get_message ``` -------------------------------- ### Kybra Canister Method: init Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/call_apis/reject_message.html Defines the Kybra canister method 'init'. This method is called exactly once when a canister is first created, allowing for initial setup and configuration. ```APIDOC service { init: () -> () oneway; } ``` -------------------------------- ### Deploy All Canisters to IC Mainnet Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/deployment.md This command deploys all canisters defined in your `dfx.json` file to the Internet Computer mainnet. Ensure you have sufficient cycles configured before attempting this deployment. This is the final step for making your application publicly available. ```bash dfx deploy --network ic ``` -------------------------------- ### Implement Init Canister Method in Kybra Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/management_canister/ecdsa_public_key.html The 'init' method is a special canister method called exactly once when a canister is first created. It is used for initial setup, configuration, and state initialization. ```APIDOC service : { init: () -> () oneway; } ``` -------------------------------- ### Kybra Canister Methods Reference Source: https://github.com/demergent-labs/kybra/blob/main/docs/hello_world.html Outlines the special lifecycle and entry point methods that a Kybra canister can implement. These methods define how a canister responds to various events, including upgrades, message inspection, and HTTP requests, ensuring proper canister behavior. ```APIDOC Canister Methods: - heartbeat - http_request - http_request_update - init - inspect message - post upgrade - pre upgrade - query - update ``` -------------------------------- ### Resolve 'is cmake not installed?' error on Ubuntu Source: https://github.com/demergent-labs/kybra/blob/main/docs/installation.html This snippet provides the resolution for the 'is cmake not installed?' error on Ubuntu systems. It installs CMake, a cross-platform build system generator, which is required for certain compilation processes. ```Bash sudo apt install cmake ``` -------------------------------- ### Kybra Management Canister API: install_code Source: https://github.com/demergent-labs/kybra/blob/main/docs/query_methods.html Documents the `install_code` method of the Management Canister, used to install new Wasm code onto an existing canister. This is fundamental for deploying and upgrading canister logic. ```APIDOC Management Canister API: install_code ``` -------------------------------- ### Define a Simple Kybra Query in Python Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/reference/canister_methods/query.md This Python code snippet illustrates the fundamental structure for defining a read-only query method in Kybra. It utilizes the @query decorator to mark the simple_query function, which takes no arguments and returns a static string. This example is a starting point for implementing data fetching logic within Kybra applications. ```Python from kybra import query @query def simple_query() -> str: return "This is a query method" ``` -------------------------------- ### Document Kybra Canister API: time Source: https://github.com/demergent-labs/kybra/blob/main/docs/examples.html This entry documents the 'time' API available for Kybra canisters. It describes how to retrieve the current time in nanoseconds since the Unix epoch, including its return value. ```APIDOC Canister API: time Description: Retrieves the current time in nanoseconds since the Unix epoch. ``` -------------------------------- ### Python: Fetch Bitcoin Fee Percentiles Source: https://github.com/demergent-labs/kybra/blob/main/the_kybra_book/src/reference/management_canister/bitcoin_get_current_fee_percentiles.md This Python function, `get_current_fee_percentiles`, retrieves the current Bitcoin transaction fee percentiles from the Internet Computer's management canister. It requires the Kybra framework and handles network specification (Regtest in this example). The function returns a `GetCurrentFeePercentilesResult` which is either a vector of `MillisatoshiPerByte` on success or an error string. ```python from kybra import Async, CallResult, match, update, Variant, Vec from kybra.canisters.management import management_canister, MillisatoshiPerByte BITCOIN_API_CYCLE_COST = 100_000_000 class GetCurrentFeePercentilesResult(Variant, total=False): Ok: Vec[MillisatoshiPerByte] Err: str @update def get_current_fee_percentiles() -> Async[GetCurrentFeePercentilesResult]: call_result: CallResult[ Vec[MillisatoshiPerByte] ] = yield management_canister.bitcoin_get_current_fee_percentiles( {"network": {"Regtest": None}} ).with_cycles( BITCOIN_API_CYCLE_COST ) return match( call_result, {"Ok": lambda ok: {"Ok": ok}, "Err": lambda err: {"Err": err}} ) ``` -------------------------------- ### Kybra Canister Method: init Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/candid/null.html Implements the 'init' lifecycle method for Kybra canisters. This method is called exactly once when a canister is first created, allowing for initial setup and configuration. ```APIDOC init() -> None; ``` -------------------------------- ### Document Kybra Canister API: print Source: https://github.com/demergent-labs/kybra/blob/main/docs/examples.html This entry documents the 'print' API available for Kybra canisters. It describes how to output messages to the canister's log for debugging purposes, including its input parameters. ```APIDOC Canister API: print Description: Outputs messages to the canister's log for debugging. ``` -------------------------------- ### Deploy DFX Canisters to Local Replica Source: https://github.com/demergent-labs/kybra/blob/main/docs/deployment.html This snippet illustrates how to deploy canisters to the local Internet Computer replica. It covers deploying all canisters defined in `dfx.json` or targeting a specific canister. This is a crucial step after building your canister code. ```Shell dfx deploy ``` ```Shell dfx deploy canister_name ``` -------------------------------- ### Kybra Python Example: Get 128-bit Cycles Refunded Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/call_apis/msg_cycles_refunded128.html This Python code snippet demonstrates how to use `ic.msg_cycles_refunded128()` in Kybra. It shows a service method that sends 1,000,000 cycles to another canister and then retrieves the amount of cycles refunded from that call. The result is returned as either the refunded amount or an error string. ```Python from kybra import ( Async, CallResult, ic, match, nat, Principal, Service, service_update, update, Variant, ) class SendCyclesResult128(Variant, total=False): Ok: nat Err: str class Cycles(Service): @service_update def receive_cycles128(self) -> nat: ... cycles = Cycles(Principal.from_str("rrkah-fqaaa-aaaaa-aaaaq-cai")) # Reports the number of cycles returned from the Cycles canister @update def send_cycles128() -> Async[SendCyclesResult128]: result: CallResult[nat] = yield cycles.receive_cycles128().with_cycles128(1_000_000) return match( result, { "Ok": lambda _: {"Ok": ic.msg_cycles_refunded128()}, "Err": lambda err: {"Err": err}, }, ) ``` -------------------------------- ### Install Kybra 0.7.1 with pip Source: https://github.com/demergent-labs/kybra/blob/main/examples/candid_encoding/requirements.txt This snippet demonstrates how to install Kybra version 0.7.1 using pip, the Python package installer. Ensure you have Python 3.8+ and pip installed on your system before execution. This command will add Kybra to your Python environment, allowing you to use its functionalities for Internet Computer development. ```Python pip install kybra==0.7.1 ``` -------------------------------- ### Python Example: Get Bitcoin Balance with Kybra Source: https://github.com/demergent-labs/kybra/blob/main/docs/reference/management_canister/bitcoin_get_balance.html This Python snippet demonstrates how to call the "bitcoin_get_balance" method of the Internet Computer's management canister using Kybra. It shows how to pass the address and network parameters, handle the "CallResult" using "match", and manage cycles required for the API call. ```Python from kybra import Async, CallResult, match, update, Variant from kybra.canisters.management import management_canister, Satoshi BITCOIN_API_CYCLE_COST = 100_000_000 class ExecuteGetBalanceResult(Variant, total=False): Ok: Satoshi Err: str @update def get_balance(address: str) -> Async[ExecuteGetBalanceResult]: call_result: CallResult[Satoshi] = yield management_canister.bitcoin_get_balance( {"address": address, "min_confirmations": None, "network": {"Regtest": None}} ).with_cycles(BITCOIN_API_CYCLE_COST) return match( call_result, {"Ok": lambda ok: {"Ok": ok}, "Err": lambda err: {"Err": err}} ) ``` -------------------------------- ### Deploy all Kybra canisters to IC mainnet Source: https://github.com/demergent-labs/kybra/blob/main/docs/deployment.html This command deploys all canisters defined in your `dfx.json` file to the Internet Computer (IC) mainnet. Ensure you have cycles set up before execution. ```Shell dfx deploy --network ic ```