### Setting Up and Running React TypeScript Project (Bash) Source: https://github.com/b3pay/ic-reactor/blob/main/examples/react-provider/README.md This snippet outlines the essential bash commands required to prepare and launch a React TypeScript application. It covers installing all project dependencies and then initiating the development server. ```bash npm install npm run start ``` -------------------------------- ### Installing All Project Dependencies (Yarn/NPM) - Shell Source: https://github.com/b3pay/ic-reactor/blob/main/examples/nextjs/README.md This command installs all necessary Node.js, Candid, and WASM related dependencies for the project. It acts as a wrapper for individual `install` commands, streamlining the setup process. ```Shell yarn install:all ``` ```Shell npm run install:all ``` -------------------------------- ### Starting Development Server with Create React App (npm) Source: https://github.com/b3pay/ic-reactor/blob/main/examples/custom-provider/README.md Runs the React application in development mode, making it accessible via a local server. The page reloads automatically on code edits, and lint errors are displayed in the console. ```Shell npm start ``` -------------------------------- ### Building Production Bundle with Create React App (Shell) Source: https://github.com/b3pay/ic-reactor/blob/main/examples/multiple-provider/README.md This command compiles the React application into a production-ready bundle, optimizing it for performance and minifying the code. The output is placed in the `build` folder, ready for deployment to a web server. ```Shell npm run build ``` -------------------------------- ### Starting Development Server with Create React App (Shell) Source: https://github.com/b3pay/ic-reactor/blob/main/examples/ckbtc-wallet/README.md This command runs the React application in development mode, making it accessible via a local server (typically http://localhost:3000). It enables hot reloading on code changes and displays linting errors directly in the console, facilitating a rapid development workflow. ```Shell npm start ``` -------------------------------- ### Building Production Bundle for Create React App (Shell) Source: https://github.com/b3pay/ic-reactor/blob/main/examples/ckbtc-wallet/README.md Compiles the React application into a production-ready bundle, optimizing it for performance and deployment. The output is placed in the `build` folder, minified, and includes hashed filenames for efficient caching, preparing the app for live environments. ```Shell npm run build ``` -------------------------------- ### Starting Development Server with Create React App (Shell) Source: https://github.com/b3pay/ic-reactor/blob/main/examples/multiple-provider/README.md This command runs the React application in development mode, typically opening it in a web browser at http://localhost:3000. It enables live reloading on code edits and displays lint errors directly in the console, facilitating a rapid development workflow. ```Shell npm start ``` -------------------------------- ### Building Production Bundle for Create React App (npm) Source: https://github.com/b3pay/ic-reactor/blob/main/examples/custom-provider/README.md Compiles the React application into optimized production-ready assets within the `build` folder. This process bundles React, minifies code, and includes hashes in filenames for efficient deployment. ```Shell npm run build ``` -------------------------------- ### Ejecting Create React App Configuration (npm) Source: https://github.com/b3pay/ic-reactor/blob/main/examples/custom-provider/README.md Removes the single build dependency from the project, copying all configuration files (webpack, Babel, ESLint) directly into the project. This provides full control over the build setup but is a one-way operation, meaning you cannot revert to the managed setup. ```Shell npm run eject ``` -------------------------------- ### Ejecting Create React App Configuration (Shell) Source: https://github.com/b3pay/ic-reactor/blob/main/examples/ckbtc-wallet/README.md This irreversible command removes the single build dependency (react-scripts) and copies all underlying configuration files (webpack, Babel, ESLint) directly into the project. It grants full control over the build setup but means the project is no longer managed by Create React App's abstractions, requiring manual configuration management. ```Shell npm run eject ``` -------------------------------- ### Launching Test Runner for Create React App (npm) Source: https://github.com/b3pay/ic-reactor/blob/main/examples/custom-provider/README.md Initiates the test runner in interactive watch mode, allowing developers to run tests and receive immediate feedback on code changes. Refer to Create React App documentation for more details on testing. ```Shell npm test ``` -------------------------------- ### Installing @ic-reactor/core with npm Source: https://github.com/b3pay/ic-reactor/blob/main/packages/core/README.md Instructions for installing the `@ic-reactor/core` package using the npm package manager. This is a prerequisite for using the library. ```bash npm install @ic-reactor/core ``` -------------------------------- ### Launching Test Runner with Create React App (Shell) Source: https://github.com/b3pay/ic-reactor/blob/main/examples/multiple-provider/README.md This command initiates the test runner in an interactive watch mode, allowing developers to run tests and see results as code changes. It's used for verifying application functionality and ensuring code quality. ```Shell npm test ``` -------------------------------- ### Ejecting Create React App Configuration (Shell) Source: https://github.com/b3pay/ic-reactor/blob/main/examples/multiple-provider/README.md This command removes the single build dependency from the project, copying all configuration files (webpack, Babel, ESLint, etc.) directly into the project. It provides full control over the build setup but is a one-way operation, meaning you cannot revert to the managed Create React App configuration afterward. ```Shell npm run eject ``` -------------------------------- ### Starting Local DFINITY Replica (Yarn/NPM) - Shell Source: https://github.com/b3pay/ic-reactor/blob/main/examples/nextjs/README.md These commands start a local instance of the DFINITY Internet Computer replica. This allows developers to deploy and test their canisters locally without interacting with the mainnet. ```Shell yarn dfx:start ``` ```Shell npm run dfx:start ``` -------------------------------- ### Installing @ic-reactor/core with Yarn Source: https://github.com/b3pay/ic-reactor/blob/main/packages/core/README.md Instructions for installing the `@ic-reactor/core` package using the Yarn package manager. This is an alternative prerequisite for using the library. ```bash yarn add @ic-reactor/core ``` -------------------------------- ### Installing Node.js Dependencies (Yarn/NPM) - Shell Source: https://github.com/b3pay/ic-reactor/blob/main/examples/nextjs/README.md These commands install the Node.js package dependencies defined in the project's `package.json` file. This is a standard step for setting up the frontend and any Node.js-based tooling. ```Shell yarn install ``` ```Shell npm install ``` -------------------------------- ### Launching Test Runner for Create React App (Shell) Source: https://github.com/b3pay/ic-reactor/blob/main/examples/ckbtc-wallet/README.md Executes the test runner in an interactive watch mode, allowing developers to run tests and see results as code changes. This is crucial for continuous integration and ensuring code quality within the React project. ```Shell npm test ``` -------------------------------- ### Installing @ic-reactor/react Package Source: https://github.com/b3pay/ic-reactor/blob/main/packages/react/README.md These commands demonstrate how to install the @ic-reactor/react library using either npm or yarn, which are common package managers for JavaScript projects. ```bash npm install @ic-reactor/react ``` ```bash yarn add @ic-reactor/react ``` -------------------------------- ### Starting Application in Production (TypeScript) Source: https://github.com/b3pay/ic-reactor/blob/main/examples/nodejs/README.md This script initiates the application in production mode. It first triggers the build process using `npm run build` to compile the TypeScript project, and then executes the resulting JavaScript file located at `build/index.js`. ```Shell npm run start ``` -------------------------------- ### Running Next.js Development Server (Yarn/NPM) - Shell Source: https://github.com/b3pay/ic-reactor/blob/main/examples/nextjs/README.md These commands start the Next.js development server, making the frontend application accessible locally, typically at `http://localhost:3000`. This enables hot-reloading and other development features for the Next.js app. ```Shell yarn dev ``` ```Shell npm run dev ``` -------------------------------- ### Rendering Canister Actor and Initializing Core - JavaScript Source: https://github.com/b3pay/ic-reactor/blob/main/examples/html/index.html This asynchronous function renders the actor for a given canister ID. It updates the agent's host based on network selection, fetches the Candid definition, creates a `reactorCore` instance, and then calls `tokenDetails` and `userWallet` to display token information and user-specific wallet details. ```JavaScript const renderActor = async (event) => { event?.preventDefault() previousActorCleanup?.() balanceUnsub?.() transferUnsub?.() agentManager.updateAgent({ host: networkSelect.value === "local" ? Reactor.utils.LOCAL_HOST_NETWORK_URI : Reactor.utils.IC_HOST_NETWORK_URI, }) const canisterId = canisterIdInput.value resultDiv.innerHTML = `Loading ${canisterId}` const { idlFactory } = await candidAdapter.getCandidDefinition(canisterId) resultDiv.innerHTML = `Loaded ${canisterId}` const reactorCore = Reactor.createReactorCore({ agentManager, canisterId, idlFactory, withDevtools: true }) previousActorCleanup = reactorCore.cleanup resultDiv.innerHTML = "" balanceDiv.innerHTML = "" tokenDetails(reactorCore) userWallet(reactorCore) } ``` -------------------------------- ### Starting Application in Development (TypeScript) Source: https://github.com/b3pay/ic-reactor/blob/main/examples/nodejs/README.md This script starts the application in development mode, enabling hot reloading. It utilizes `nodemon` for watching file changes and `ts-node` for directly executing TypeScript files without prior compilation. ```Shell npm run start:dev ``` -------------------------------- ### Initializing Reactor Agent and UI Elements - JavaScript Source: https://github.com/b3pay/ic-reactor/blob/main/examples/html/index.html This snippet initializes the `Reactor` agent and candid adapter, sets up variables for managing subscriptions, and retrieves references to various HTML elements. It also attaches event listeners to the login button and the canister form for submitting and rendering the actor. ```JavaScript const agentManager = Reactor.createAgentManager({ withDevtools: true }) const candidAdapter = Reactor.createCandidAdapter({ agentManager }) let previousActorCleanup = null let balanceUnsub = null let transferUnsub = null const canisterForm = document.getElementById("canisterForm") document.addEventListener("DOMContentLoaded", function () { canisterForm.addEventListener("submit", renderActor, false) }) const canisterIdInput = document.getElementById("canisterIdInput") const networkSelect = document.getElementById("networkSelect") const userPara = document.getElementById("user") const loginButton = document.getElementById("loginButton") const resultDiv = document.getElementById("result") const userForm = document.getElementById("userForm") const balanceDiv = document.getElementById("balance") const transferForm = document.getElementById("transferForm") const transferResult = document.getElementById("transferResult") loginButton.addEventListener("click", login, false) ``` -------------------------------- ### Managing State with Reactor Store (TypeScript) Source: https://github.com/b3pay/ic-reactor/blob/main/packages/core/README.md This example illustrates the use of `createReactorStore` for more granular control over state management and actor interactions. It demonstrates authenticating an agent, logging in a user, and then calling a canister method ('version') using the `callMethod` function provided by the store. ```TypeScript import { createReactorStore } from "@ic-reactor/core" import { candid, canisterId, idlFactory } from "./declarations/candid" type Candid = typeof candid const { agentManager, callMethod } = createReactorStore({ canisterId, idlFactory, }) // Usage example await agentManager.authenticate() const authClient = agentManager.getAuth() authClient?.login({ onSuccess: () => { console.log("Logged in successfully") }, onError: (error) => { console.error("Failed to login:", error) }, }) // Call a method const version = callMethod("version") console.log("Response from version method:", await version) ``` -------------------------------- ### Testing WebAssembly Project with wasm-pack test (Shell) Source: https://github.com/b3pay/ic-reactor/blob/main/packages/parser/README.md This command runs tests for the WebAssembly project in headless browsers, specifically using Firefox in this example. It's used to verify the functionality of the compiled WebAssembly module. ```Shell wasm-pack test --headless --firefox ``` -------------------------------- ### Initiating a Token Transfer in Reactor (JavaScript) Source: https://github.com/b3pay/ic-reactor/blob/main/examples/html/index.html This snippet retrieves the recipient's principal and the transfer amount from HTML form elements. It then constructs and executes a `transferCall` to perform the token transfer, including optional fields like `created_at_time`, `fee`, `memo`, and `from_subaccount`. ```JavaScript const owner = Reactor.utils.Principal.fromText(event.target.elements.to.value) const amount = BigInt(event.target.elements.amount.value) transferCall([ { to: { owner, subaccount: [] }, amount, created_at_time: [], fee: [], memo: [], from_subaccount: [], }, ]) }) } ``` -------------------------------- ### Installing WASM Transformer (Yarn/NPM) - Shell Source: https://github.com/b3pay/ic-reactor/blob/main/examples/nextjs/README.md These commands install the `ic-wasm` tool, which is used for transforming WebAssembly (WASM) canisters. This tool can optimize or modify canister WASM modules before deployment to the Internet Computer. ```Shell yarn wasm:install ``` ```Shell npm run wasm:install ``` -------------------------------- ### Managing User Authentication with Reactor - JavaScript Source: https://github.com/b3pay/ic-reactor/blob/main/examples/html/index.html This function handles user login and logout using the `agentManager`. It subscribes to authentication state changes to dynamically update the UI (login button text and user principal display) and automatically attempts to authenticate upon page load. ```JavaScript function login() { const { authenticated } = agentManager.getAuthState() if (authenticated) { balanceUnsub?.() transferUnsub?.() agentManager.logout() userForm.style.display = "none" } else { agentManager.login({ onSuccess: () => { renderActor() }, }) } } agentManager.subscribeAuthState( ({ identity, authenticating, authenticated }) => { const userPrincipal = identity?.getPrincipal().toText() loginButton.textContent = authenticating ? "Authenticating..." : authenticated ? "Logout" : "Login" userPara.textContent = `${userPrincipal || "Not logged in"}` } ) agentManager.authenticate() ``` -------------------------------- ### Connecting to Local IC Network (Port) with Agent Manager (TypeScript) Source: https://github.com/b3pay/ic-reactor/blob/main/packages/core/README.md For development and testing, `createAgentManager` can be configured to connect to a local IC network instance. This example demonstrates connecting to a local replica by setting `withLocalEnv` to true and specifying a custom `port`. ```TypeScript // agent.ts import { createAgentManager } from "@ic-reactor/core" export const agentManager = createAgentManager({ withLocalEnv: true, port: 8000 // Default port is 4943 }) ``` -------------------------------- ### Installing Candid Extractor (Yarn/NPM) - Shell Source: https://github.com/b3pay/ic-reactor/blob/main/examples/nextjs/README.md These commands install the `candid-extractor` tool, which is used to extract Candid interface definitions from canister WASM modules. This is crucial for generating type-safe bindings for frontend interaction with the backend canisters. ```Shell yarn candid:install ``` ```Shell npm run candid:install ``` -------------------------------- ### Creating and Using an Actor Manager (TypeScript) Source: https://github.com/b3pay/ic-reactor/blob/main/packages/core/README.md This example demonstrates how to use `createActorManager` to create a dedicated manager for a specific actor, enabling fine-grained control over its lifecycle and method interactions. It shows initializing the manager with an `agentManager`, `canisterId`, and `idlFactory`, then calling a method on the managed actor. ```TypeScript // actor.ts import { createActorManager } from "@ic-reactor/core" import { candid, canisterId, idlFactory } from "./declarations/candid" import { agentManager } from "./agent" type Candid = typeof candid const candidActor = createActorManager({ agentManager, canisterId, idlFactory, }) // Usage example const data = await candidActor.callMethod("version") console.log(data) ``` -------------------------------- ### Managing User Wallet Balance and Transfers - JavaScript Source: https://github.com/b3pay/ic-reactor/blob/main/examples/html/index.html This function handles user-specific wallet operations. It retrieves the user's principal, queries the ICRC-1 token balance, and sets up an update call for token transfers. It also creates UI elements to display the balance and transfer results, with a refresh button for the balance. ```JavaScript const userWallet = async ({ getPrincipal, queryCall, updateCall }) => { userForm.style.display = "flex" const owner = getPrincipal() const { subscribe: balanceSubscribe, call: balanceCall } = queryCall({ functionName: "icrc1_balance_of", args: [{ owner, subaccount: [] }], }) const { subscribe: transferSubscribe, call: transferCall } = updateCall({ functionName: "icrc1_transfer", }) const refreshButton = document.createElement("button") refreshButton.textContent = "↻" refreshButton.onclick = () => balanceCall() balanceDiv.appendChild(refreshButton) const balancePara = document.createElement("p") balanceDiv.appendChild(balancePara) balanceUnsub = balanceSubscribe(({ data, loading, error }) => { balancePara.innerHTML = loading ? "Loading..." : error ? `Error: ${error.message}` : Reactor.utils.jsonToString(data) }) transferUnsub = transferSubscribe(({ data, loading, error }) => { transferResult.innerHTML = loading ? "Loading..." : error ? `Error: ${error.message}` : data ? `Transfer Result: ${Reactor.utils.jsonToString(data)}` : "" }) transferForm.addEventListener("submit", (event) => { event.preventDefault() }) ``` -------------------------------- ### Defining ICRC1 Name Query in Candid Source: https://github.com/b3pay/ic-reactor/blob/main/examples/javascript/src/index.html This snippet defines a Candid interface method `icrc1_name` which is a query function. It takes no arguments and returns a `text` (string) value, typically representing the name of an ICRC-1 compliant token on the Internet Computer. ```Candid icrc1_name:()->(text) query; ``` -------------------------------- ### Querying ICRC Token Metadata - JavaScript Source: https://github.com/b3pay/ic-reactor/blob/main/examples/html/index.html This function fetches various ICRC-1 token metadata (decimals, fee, name, symbol, total supply, etc.) using `queryCall`. It dynamically creates UI elements for each piece of data, including a refresh button, and subscribes to updates to display the information. ```JavaScript const tokenDetails = async ({ queryCall }) => { // Function names as per your React component const functionNames = [ "icrc1_decimals", "icrc1_fee", "icrc1_metadata", "icrc1_minting_account", "icrc1_name", "icrc1_supported_standards", "icrc1_symbol", "icrc1_total_supply", ] functionNames.forEach((functionName) => { const { subscribe, call } = queryCall({ functionName }) const container = document.createElement("div") container.className = "flex-row" const resultPara = document.createElement("p") const refreshButton = document.createElement("button") refreshButton.textContent = "↻" refreshButton.onclick = () => call() container.appendChild(refreshButton) container.appendChild(resultPara) subscribe(({ data, loading, error }) => { resultPara.textContent = loading ? "Loading..." : error ? `Error: ${error.message}` : `${functionName}: ${Reactor.utils.jsonToString(data)}` }) resultDiv.appendChild(container) }) } ``` -------------------------------- ### Styling UI Elements with CSS Source: https://github.com/b3pay/ic-reactor/blob/main/examples/javascript/src/index.html This CSS snippet defines basic styling for a web application, including box-sizing, font-family, flexbox layouts for rows and columns, and consistent styling for form elements like inputs, textareas, selects, fieldsets, and buttons. It also applies specific styles to elements with IDs 'balance' and 'transferResult'. ```CSS * { box-sizing: border-box; } body { font-family: Arial, sans-serif; width: 100%; max-width: 600px; margin: 0 auto; } .flex-row { display: flex; gap: 10px; width: 100%; align-items: center; } .flex-column { display: flex; flex-direction: column; gap: 10px; width: 100%; } input, textarea, select, fieldset, button { padding: 5px; border: 1px solid #ccc; border-radius: 5px; } button { max-height: 30px; min-width: 30px; cursor: pointer; } #balance { display: flex; gap: 10px; } #transferResult { white-space: pre-wrap; } ``` -------------------------------- ### Loading @ic-reactor/core UMD via Script Tag Source: https://github.com/b3pay/ic-reactor/blob/main/packages/core/README.md Demonstrates how to include the `@ic-reactor/core` library directly in an HTML file using its UMD (Universal Module Definition) version via a script tag. This method is suitable for browser environments without a module bundler. ```html ``` -------------------------------- ### Building Application for Production (TypeScript) Source: https://github.com/b3pay/ic-reactor/blob/main/examples/nodejs/README.md This script compiles the TypeScript application into JavaScript, preparing it for production deployment. It cleans the `build` directory before compiling the project, ensuring a fresh build. ```Shell npm run build ``` -------------------------------- ### Performing Login, Query, and Update Calls with Reactor Core (TypeScript) Source: https://github.com/b3pay/ic-reactor/blob/main/packages/core/README.md Demonstrates how to perform user login, make a query call (`icrc1_balance_of`), and initiate an update call (`icrc1_transfer`) using the `createReactorCore` instance. It shows handling success/error callbacks for login and subscribing to update call status. ```typescript // later in your code await login({ onSuccess: () => { console.log("Logged in successfully") }, onError: (error) => { console.error("Failed to login:", error) }, }) // queryCall, will automatically call and return a promise with the result const { dataPromise, call } = queryCall({ functionName: "icrc1_balance_of", args: [{ owner: getPrincipal(), subaccount: [] }], }) console.log(await dataPromise) // updateCall const { call, subscribe } = updateCall({ functionName: "icrc1_transfer", args: [ { to: { owner: getPrincipal(), subaccount: [] }, amount: BigInt(10000000000), fee: [], memo: [], created_at_time: [], from_subaccount: [], }, ], }) // subscribe to the update call subscribe(({ loading, error, data }) => { console.log({ loading, error, data }) }) const result = await call() console.log(result) ``` -------------------------------- ### Interacting with Multiple Canisters via Actor Managers (TypeScript) Source: https://github.com/b3pay/ic-reactor/blob/main/packages/core/README.md Shows how to use the previously created `actorA` and `actorB` instances to perform query calls on their respective canisters. It demonstrates fetching a `version` from `actorA` and a `balance` from `actorB`, logging the asynchronous results. ```typescript const { dataPromise: version } = actorA.queryCall({ functionName: "version", }) console.log("Response from CanisterA method:", await version) const { dataPromise: balance } = actorB.queryCall({ functionName: "balance", args: [principal, []], }) console.log("Response from CanisterB method:", await balance) ``` -------------------------------- ### Deploying Canisters to Local IC (Yarn/NPM) - Shell Source: https://github.com/b3pay/ic-reactor/blob/main/examples/nextjs/README.md These commands deploy the project's canisters to the locally running DFINITY Internet Computer replica. This makes the backend services available for local testing and development. ```Shell yarn deploy ``` ```Shell npm run deploy ``` -------------------------------- ### Initializing Reactor Core for Single Canister Interaction (TypeScript) Source: https://github.com/b3pay/ic-reactor/blob/main/packages/core/README.md Initializes a Reactor instance using `createReactorCore` for interacting with a single Internet Computer canister. It sets up the agent and provides methods for authentication, querying, and updating actors, using provided canister ID and IDL factory. ```typescript import { createReactorCore } from "@ic-reactor/core" import { candid, canisterId, idlFactory } from "./declarations/candid" type Candid = typeof candid const { queryCall, updateCall, getPrincipal, login } = createReactorCore({ canisterId, idlFactory, withProcessEnv: true, // will use process.env.DFX_NETWORK }) ``` -------------------------------- ### Formatting Code with Prettier (TypeScript) Source: https://github.com/b3pay/ic-reactor/blob/main/examples/nodejs/README.md This script applies code formatting using Prettier across the project. It helps maintain consistent code style and readability by automatically reformatting files according to predefined rules. ```Shell npm run prettier-format ``` -------------------------------- ### Cloning wasm-pack-template with cargo generate (Shell) Source: https://github.com/b3pay/ic-reactor/blob/main/packages/parser/README.md This command sequence uses `cargo generate` to clone the `wasm-pack-template` repository into a new project directory named `my-project`, and then navigates into that directory. It's the initial step for setting up a new Rust and WebAssembly project. ```Shell cargo generate --git https://github.com/rustwasm/wasm-pack-template.git --name my-project cd my-project ``` -------------------------------- ### Deploying Identity Canister to Local IC (Yarn/NPM) - Shell Source: https://github.com/b3pay/ic-reactor/blob/main/examples/nextjs/README.md These commands specifically deploy the identity canister to the local DFINITY Internet Computer replica. This is often required for authentication and user management within the application. ```Shell yarn identity:deploy ``` ```Shell npm run identity:deploy ``` -------------------------------- ### Running Jest Tests Once (TypeScript) Source: https://github.com/b3pay/ic-reactor/blob/main/examples/nodejs/README.md This script executes the `jest` test suite a single time. It's used for running all defined tests to verify application functionality and ensure code quality. ```Shell npm run test ``` -------------------------------- ### Initializing Reactor Core with Candid Adapter (TypeScript) Source: https://github.com/b3pay/ic-reactor/blob/main/packages/core/README.md This snippet demonstrates how to use `createCandidAdapter` to dynamically fetch a canister's Candid definition, then pass it to `createReactorCore` for making method calls. It shows how to retrieve the IDL factory and subsequently call a read-only method like 'name' on the NNS ICP Ledger Canister. ```TypeScript import { createReactorCore, createCandidAdapter } from "@ic-reactor/core" import { agentManager } from "./agent" const candidAdapter = createCandidAdapter({ agentManager }) const canisterId = "ryjl3-tyaaa-aaaaa-aaaba-cai" // NNS ICP Ledger Canister // Usage example try { const { idlFactory } = await candidAdapter.getCandidDefinition(canisterId) const { callMethod } = createReactorCore({ agentManager, canisterId, idlFactory, }) const name = await callMethod("name") console.log(name) // { name: 'Internet Computer' } } catch (error) { console.error(error) } ``` -------------------------------- ### Deploying Canisters to Main Internet Computer Network (Yarn) - Shell Source: https://github.com/b3pay/ic-reactor/blob/main/examples/nextjs/README.md This command deploys the project's canisters to the main Internet Computer network. The `--network=ic` flag specifies the target network, making the application publicly accessible. ```Shell yarn deploy --network=ic ``` -------------------------------- ### Connecting to IC Network with Agent Manager (TypeScript) Source: https://github.com/b3pay/ic-reactor/blob/main/packages/core/README.md This snippet shows the simplest way to initialize `createAgentManager` to connect to the default Internet Computer main network. This agent manager instance can then be reused across various `ic-reactor` components for consistent network interaction. ```TypeScript // agent.ts import { createAgentManager } from "@ic-reactor/core" export const agentManager = createAgentManager() // Connects to IC network by default ``` -------------------------------- ### Building WebAssembly Project with wasm-pack build (Shell) Source: https://github.com/b3pay/ic-reactor/blob/main/packages/parser/README.md This command compiles the Rust library into WebAssembly, generating the necessary JavaScript and WebAssembly files for publishing to NPM. It's a core step in the development workflow. ```Shell wasm-pack build ``` -------------------------------- ### Connecting to Local IC Network (Host) with Agent Manager (TypeScript) Source: https://github.com/b3pay/ic-reactor/blob/main/packages/core/README.md This snippet provides an alternative method for connecting `createAgentManager` to a local IC network by directly specifying the `host` URL. This offers flexibility when the local replica is running on a non-standard address or port. ```TypeScript // agent.ts import { createAgentManager } from "@ic-reactor/core" export const agentManager = createAgentManager({ host: "http://localhost:8000" }) ``` -------------------------------- ### Formatting Code with Prettier in Watch Mode (TypeScript) Source: https://github.com/b3pay/ic-reactor/blob/main/examples/nodejs/README.md This script runs Prettier in watch mode, automatically formatting code as files are changed. This ensures continuous adherence to code style guidelines during development without manual intervention. ```Shell npm run prettier-watch ``` -------------------------------- ### Fetching Candid Definition with CandidAdapter (TypeScript) Source: https://github.com/b3pay/ic-reactor/blob/main/packages/core/README.md Demonstrates how to use `createCandidAdapter` to instantiate a `CandidAdapter` and then fetch the Candid interface definition for a given canister ID. It includes error handling for cases where the definition cannot be retrieved. ```typescript import { createCandidAdapter } from "@ic-reactor/core" import { agentManager } from "./agent" const candidAdapter = createCandidAdapter({ agentManager }) const canisterId = "ryjl3-tyaaa-aaaaa-aaaba-cai" // Usage example try { const definition = await candidAdapter.getCandidDefinition(canisterId) console.log(definition) } catch (error) { console.error(error) } ``` -------------------------------- ### Creating Multiple Actor Managers for Different Canisters (TypeScript) Source: https://github.com/b3pay/ic-reactor/blob/main/packages/core/README.md Demonstrates how to create separate actor managers for different canisters (`candidA`, `candidB`) using `createActorManager`. Each actor manager is associated with a shared `agentManager` and configured with its specific canister ID and IDL factory, enabling modular interaction. ```typescript // Assuming you've already set up `candidA`, `candidB`, and `agentManager` import { createActorManager } from "@ic-reactor/core" import * as candidA from "./declarations/candidA" import * as candidB from "./declarations/candidB" import { agentManager } from "./agent" type CandidA = typeof candidA.candidA type CandidB = typeof candidB.candidB const actorA = createActorManager({ agentManager, canisterId: candidA.canisterId, idlFactory: candidA.idlFactory, }) const actorB = createActorManager({ agentManager, canisterId: candidB.canisterId, idlFactory: candidB.idlFactory, }) ``` -------------------------------- ### Running Jest Tests in Watch Mode (TypeScript) Source: https://github.com/b3pay/ic-reactor/blob/main/examples/nodejs/README.md This script runs the `jest` test suite in watch mode. It continuously monitors for file changes and re-executes relevant tests automatically, facilitating a rapid development and testing workflow. ```Shell npm run test:dev ``` -------------------------------- ### Publishing WebAssembly Package to NPM with wasm-pack publish (Shell) Source: https://github.com/b3pay/ic-reactor/blob/main/packages/parser/README.md This command publishes the compiled WebAssembly package to the NPM registry, making it available for use in JavaScript projects. It's the final step for distributing the WebAssembly module. ```Shell wasm-pack publish ``` -------------------------------- ### Managing IC Blockchain Authentication with useAuth Hook (React/JSX) Source: https://github.com/b3pay/ic-reactor/blob/main/packages/react/README.md This React component illustrates how to manage user authentication with the Internet Computer blockchain using the useAuth hook from @ic-reactor/react. It provides functionality for logging in and out, displays authentication status, loading states, and any errors, showing the authenticated principal if available. ```javascript // Login.tsx\nimport { useAuth } from "./actor"\n\nconst Login = () => {\n const {\n login,\n logout,\n loginLoading,\n loginError,\n identity,\n authenticating,\n authenticated,\n } = useAuth()\n\n return (\n
\n

Login:

\n
\n {loginLoading &&
Loading...
}\n {loginError ?
{JSON.stringify(loginError)}
: null}\n {identity &&
{identity.getPrincipal().toText()}
}\n
\n {authenticated ? (\n
\n \n
\n ) : (\n
\n \n
\n )}\n
\n )\n}\n\nexport default Login ``` -------------------------------- ### Creating an Agent Manager for Multiple Canisters (TypeScript) Source: https://github.com/b3pay/ic-reactor/blob/main/packages/core/README.md Creates a global agent manager instance using `createAgentManager`. This manager handles the underlying agent connection to the Internet Computer network and is a prerequisite for managing multiple actor instances independently. ```typescript // agent.ts import { createAgentManager } from "@ic-reactor/core" export const agentManager = createAgentManager() // Connects to IC network by default ``` -------------------------------- ### Querying IC Canister Method with useQueryCall Hook (React/JSX) Source: https://github.com/b3pay/ic-reactor/blob/main/packages/react/README.md This React component demonstrates using the useQueryCall hook from @ic-reactor/react to interact with an IC canister. It calls the get_balance function with a principal argument, configures auto-refetching, and handles loading, success, and error states, displaying the balance or relevant messages to the user. ```javascript // Balance.tsx\nimport { useQueryCall } from "./actor"\n\nconst Balance = ({ principal }) => {\n const { call, data, loading, error } = useQueryCall({\n functionName: "get_balance",\n args: [principal],\n refetchInterval: 1000,\n refetchOnMount: true,\n onLoading: () => console.log("Loading..."),\n onSuccess: (data) => console.log("Success!", data),\n onError: (error) => console.log("Error!", error),\n })\n\n return (\n
\n \n {loading &&

Loading...

}\n {data &&

Balance: {data}

}\n {error &&

Error: {error}

}\n
\n )\n}\n\nexport default Balance ``` -------------------------------- ### Styling UI Elements with CSS Source: https://github.com/b3pay/ic-reactor/blob/main/examples/typescript/src/index.html This CSS snippet defines global box-sizing, body typography and width, flexbox layouts for rows and columns, and basic styling for form elements like inputs, selects, fieldsets, and buttons. It also includes specific display rules for `#balance` and `#transferResult` elements. ```CSS * { box-sizing: border-box; } body { font-family: Arial, sans-serif; width: 100%; max-width: 600px; margin: 0 auto; } .flex-row { display: flex; gap: 10px; width: 100%; align-items: center; } .flex-column { display: flex; flex-direction: column; gap: 10px; width: 100%; } input, select, fieldset, button { padding: 5px; border: 1px solid #ccc; border-radius: 5px; } button { max-height: 30px; min-width: 30px; cursor: pointer; } #balance { display: flex; gap: 10px; } #transferResult { white-space: pre-wrap; } ``` -------------------------------- ### Creating IC Reactor Actor Declaration File (TypeScript) Source: https://github.com/b3pay/ic-reactor/blob/main/packages/react/README.md This TypeScript snippet demonstrates how to create an actor declaration file using @ic-reactor/react. It imports necessary components like canisterId, idlFactory, and actor from a declaration, then uses createReactor to initialize the library with the canister's ID and IDL factory, exposing hooks for state, authentication, and queries. ```typescript // actor.ts\nimport { canisterId, idlFactory, actor } from "declaration/actor"\nimport { createReactor } from "@ic-reactor/react"\n\ntype Actor = typeof actor\n\nexport const { useActorStore, useAuth, useQueryCall } = createReactor({\n canisterId,\n idlFactory,\n host: "https://localhost:4943",\n}) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.