### Install @dfinity/utils Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Install the utils-js package using npm. Ensure peer dependencies are also installed. ```bash npm i @dfinity/utils ``` ```bash npm i @icp-sdk/core ``` -------------------------------- ### Install @dfinity/zod-schemas Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/zod-schemas/README.md Install the library using npm. Ensure peer dependencies are also installed. ```bash npm i @dfinity/zod-schemas ``` ```bash npm i @icp-sdk/core ``` -------------------------------- ### Install Individual Packages Source: https://github.com/dfinity/icp-js-canisters/blob/main/README.md Alternatively, install individual packages if you only need specific functionalities. Ensure peer dependencies like @dfinity/utils are also installed. ```bash npm i @dfinity/utils npm i @dfinity/ledger-icp npm i @dfinity/ledger-icrc npm i @dfinity/nns npm i @dfinity/sns npm i @dfinity/cmc npm i @dfinity/ckbtc ``` -------------------------------- ### Install ic-management-js Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/ic-management/README.md Install the ic-management-js package using npm. Ensure peer dependencies are also installed. ```bash npm i @dfinity/ic-management ``` ```bash npm i @icp-sdk/core @dfinity/utils ``` -------------------------------- ### Install @dfinity/ledger-icrc Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/ledger-icrc/README.md Install the ledger-icrc-js library using npm. Ensure peer dependencies are also installed. ```bash npm i @dfinity/ledger-icrc ``` ```bash npm i @icp-sdk/core @dfinity/utils ``` -------------------------------- ### Install ledger-icp-js Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/ledger-icp/README.md Install the ledger-icp-js package using npm. Ensure peer dependencies are also installed. ```bash npm i @dfinity/ledger-icp ``` ```bash npm i @icp-sdk/core @dfinity/utils ``` -------------------------------- ### Install ckbtc-js Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/ckbtc/README.md Install the ckbtc-js library and its peer dependencies using npm. ```bash npm i @dfinity/ckbtc ``` ```bash npm i @icp-sdk/core @dfinity/utils ``` -------------------------------- ### Install Core Dependencies Source: https://github.com/dfinity/icp-js-canisters/blob/main/README.md To ensure proper tree-shaking and avoid code duplication, install the core dependencies referenced by the SDK packages. ```bash npm i @icp-sdk/core @dfinity/utils ``` -------------------------------- ### Install @icp-sdk/canisters with bun Source: https://github.com/dfinity/icp-js-canisters/blob/main/docs/src/content/docs/installation.mdx Use this command to install the package with bun. ```shell bun add @icp-sdk/canisters ``` -------------------------------- ### Install @icp-sdk/canisters Source: https://github.com/dfinity/icp-js-canisters/blob/main/README.md Install the recommended modular library from npm. This is the primary entry point for interacting with canisters. ```bash npm i @icp-sdk/canisters ``` -------------------------------- ### Install @icp-sdk/canisters with yarn Source: https://github.com/dfinity/icp-js-canisters/blob/main/docs/src/content/docs/installation.mdx Use this command to install the package with yarn. Peer dependencies may need to be installed manually. ```shell yarn add @icp-sdk/canisters ``` ```shell yarn add @dfinity/ckbtc @dfinity/cketh @dfinity/cmc @dfinity/ic-management @dfinity/ledger-icp @dfinity/ledger-icrc @dfinity/nns @dfinity/sns @dfinity/utils @icp-sdk/core ``` -------------------------------- ### Install cketh-js Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/cketh/README.md Install the cketh-js library and its peer dependencies using npm. ```bash npm i @dfinity/cketh ``` ```bash npm i @icp-sdk/core @dfinity/utils ``` -------------------------------- ### Install @icp-sdk/canisters with pnpm Source: https://github.com/dfinity/icp-js-canisters/blob/main/docs/src/content/docs/installation.mdx Use this command to install the package with pnpm. Peer dependencies may need to be installed manually. ```shell pnpm add @icp-sdk/canisters ``` ```shell pnpm install @dfinity/ckbtc @dfinity/cketh @dfinity/cmc @dfinity/ic-management @dfinity/ledger-icp @dfinity/ledger-icrc @dfinity/nns @dfinity/sns @dfinity/utils @icp-sdk/core ``` -------------------------------- ### Install @icp-sdk/canisters with npm Source: https://github.com/dfinity/icp-js-canisters/blob/main/docs/src/content/docs/installation.mdx Use this command to install the package with npm. ```shell npm install @icp-sdk/canisters ``` -------------------------------- ### Install nns-js Package Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/nns/README.md Install the nns-js package using npm. Ensure peer dependencies are also installed. ```bash npm i @dfinity/nns ``` ```bash npm i @icp-sdk/core @icp-sdk/utils ``` -------------------------------- ### Install sns-js Package Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/sns/README.md Install the sns-js package and its peer dependencies using npm. ```bash npm i @dfinity/sns ``` ```bash npm i @icp-sdk/core @dfinity/utils @dfinity/ledger ``` -------------------------------- ### Install Peer Dependencies with yarn Source: https://github.com/dfinity/icp-js-canisters/blob/main/docs/src/content/docs/upgrading/v1.md Manually install peer dependencies for @icp-sdk/canisters if using yarn. ```shell yarn add @dfinity/ckbtc @dfinity/cketh @dfinity/cmc @dfinity/ic-management @dfinity/ledger-icp @dfinity/ledger-icrc @dfinity/nns @dfinity/sns @dfinity/utils @icp-sdk/core ``` -------------------------------- ### Install Peer Dependencies with pnpm Source: https://github.com/dfinity/icp-js-canisters/blob/main/docs/src/content/docs/upgrading/v1.md Manually install peer dependencies for @icp-sdk/canisters if using pnpm. ```shell pnpm install @dfinity/ckbtc @dfinity/cketh @dfinity/cmc @dfinity/ic-management @dfinity/ledger-icp @dfinity/ledger-icrc @dfinity/nns @dfinity/sns @dfinity/utils @icp-sdk/core ``` -------------------------------- ### Install cmc-js Package Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/cmc/README.md Install the cmc-js package and its peer dependencies using npm. ```bash npm i @dfinity/cmc npm i @icp-sdk/core @dfinity/utils ``` -------------------------------- ### Create a Patch Branch Source: https://github.com/dfinity/icp-js-canisters/blob/main/HACKING.md Create a new branch for patch releases, ensuring it starts with 'release//patch-' to be compatible with the publish workflow. Branch from the specific release tag you intend to patch. ```bash git checkout -b release/v89/patch-1 v89 ``` -------------------------------- ### Query Neuron List with nns-js Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/nns/README.md Example of querying the list of neurons controlled by the caller using the NnsGovernanceCanister. Requires agent creation and canister ID. ```typescript import { NnsGovernanceCanister } from "@dfinity/nns"; import { createAgent } from "@dfinity/utils"; const agent = await createAgent({ identity, host: HOST, }); const { listNeurons } = NnsGovernanceCanister.create({ agent, canisterId: MY_GOVERNANCE_CANISTER_ID, }); const myNeurons = await listNeurons({ certified: false }); ``` -------------------------------- ### Initialize CkEthMinterCanister and Get Smart Contract Address Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/cketh/README.md Instantiate the CkEthMinterCanister with an agent and canister ID, then call getSmartContractAddress to retrieve the Ethereum smart contract address. ```typescript import { CkEthMinterCanister, } from "@dfinity/cketh"; import { createAgent, } from "@dfinity/utils"; const agent = await createAgent({ identity, host: HOST, }); const { getSmartContractAddress, } = CkEthMinterCanister.create({ agent, canisterId: MY_CKETH_MINTER_CANISTER_ID, }); const address = await getSmartContractAddress({}); ``` -------------------------------- ### Local Environment Neuron Query Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/nns/README.md Querying neurons on a local environment requires fetching the root key when initializing the agent and potentially adapting the port. This example also shows inlining a canister ID. ```typescript import { NnsGovernanceCanister } from "@dfinity/nns"; import { Principal } from "@icp-sdk/core/principal"; import { createAgent } from "@dfinity/utils"; const agent = await createAgent({ identity, host: "http://localhost:8000", fetchRootKey: true, }); const { listNeurons } = NnsGovernanceCanister.create({ agent, canisterId: Principal.fromText("rrkah-fqaaa-aaaaa-aaaaq-cai"), }); const myNeurons = await listNeurons({ certified: false }); ``` -------------------------------- ### Remove Old Packages with npm Source: https://github.com/dfinity/icp-js-canisters/blob/main/docs/src/content/docs/upgrading/v1.md Use this command to remove deprecated packages before installing the new @icp-sdk/canisters package. ```shell npm remove @dfinity/ckbtc @dfinity/cketh @dfinity/cmc @dfinity/ic-management @dfinity/ledger-icp @dfinity/ledger-icrc @dfinity/nns @dfinity/sns ``` -------------------------------- ### defaultAgent Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Get a default agent that connects to mainnet with the anonymous identity. ```APIDOC ## defaultAgent ### Description Get a default agent that connects to mainnet with the anonymous identity. ### Returns The default agent to use. ``` -------------------------------- ### Update Imports from Old to New Package Source: https://github.com/dfinity/icp-js-canisters/blob/main/docs/src/content/docs/upgrading/v1.md Replace old import paths with the new modular paths from @icp-sdk/canisters. This example shows the change for CkEthMinterCanister. ```typescript - import { CkEthMinterCanister } from "@dfinity/cketh"; + import { CkEthMinterCanister } from "@icp-sdk/canisters/cketh"; ``` -------------------------------- ### Get or Create HttpAgent Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md The `getAgent` method retrieves a cached `HttpAgent` for a given `identity` or creates a new one if it doesn't exist. This optimizes resource usage by reusing agents. ```typescript const agent = await agentManager.getAgent({ identity: identity, }); ``` -------------------------------- ### Integrate Local Changes with NNS-Dapp Source: https://github.com/dfinity/icp-js-canisters/blob/main/HACKING.md Steps to test local changes of an ICP.js library within the NNS-Dapp. This involves navigating to the NNS-Dapp's frontend directory, reinstalling dependencies, removing the existing library, and installing your local version. Remember not to commit these changes to package.json or package-lock.json. ```bash # navigate to frontend directory cd frontend # remove node modules rm -r node_modules # reinstall modules npm ci # remove the library you want to test npm rm @dfinity/the-library-you-want-to-test # install the library pointing to local ic-js npm i /User/path/to/packages/the-library-you-want-to-test ``` -------------------------------- ### Cherry-pick Fixes onto a Patch Branch Source: https://github.com/dfinity/icp-js-canisters/blob/main/HACKING.md Example of creating a feature branch off a patch branch, cherry-picking commits from 'main', and pushing for review. The Pull Request should target the patch branch. ```bash # Example: cherry-pick onto a feature branch for review git checkout -b fix/backport-toBase64 release/v89/patch-1 git cherry-pick git cherry-pick git push -u origin fix/backport-toBase64 # Then open a PR targeting release/v89/patch-1 ``` -------------------------------- ### Get ICP/ICRC Ledger Metadata Source: https://github.com/dfinity/icp-js-canisters/blob/main/docs/src/content/docs/quick-start.md Use the IcrcLedgerCanister to fetch metadata for ICP and ICRC ledgers. This requires an agent and the ledger's canister ID. ```typescript import { IcrcLedgerCanister } from "@icp-sdk/canisters/ledger/icrc"; import { createAgent } from "@dfinity/utils"; const agent = await createAgent({ identity, host: HOST, }); const { metadata } = IcrcLedgerCanister.create({ agent, canisterId: MY_LEDGER_CANISTER_ID, }); const data = await metadata({}); ``` -------------------------------- ### Update Peer Dependencies Source: https://github.com/dfinity/icp-js-canisters/blob/main/HACKING.md Command to remove and then install a package as a peer dependency, ensuring it's saved in package-lock.json. Requires npm version 7 or higher. ```bash npm rm @icp-sdk/core --workspaces npm i @icp-sdk/core --save-peer --workspaces ``` -------------------------------- ### Build a Specific Library for Testing Source: https://github.com/dfinity/icp-js-canisters/blob/main/HACKING.md Build the library you intend to test locally. If issues arise, consider building all workspaces at once. ```bash npm run build --workspace=packages/the-library-you-want-to-test ``` -------------------------------- ### Build or Test All Packages Source: https://github.com/dfinity/icp-js-canisters/blob/main/HACKING.md Run this command from the root directory to build or test all packages in the monorepo. ```bash npm run build/test ``` -------------------------------- ### Initialize SNS Wrapper (Explorative Way) Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/sns/README.md Initialize an SNS wrapper using the explorative approach, which queries the root canister for SNS project canister IDs. This approach simplifies code but may incur higher costs. ```typescript import { createAgent } from "@dfinity/utils"; import { initSnsWrapper } from "@dfinity/sns"; const agent = await createAgent({ identity, host: HOST, }); const wrapper = await initSnsWrapper({ rootOptions: { canisterId: rootCanisterId, }, agent, certified, }); const { metadata, swapState } = wrapper; const [data, token] = await metadata({}); console.log("Sns:", data, token, swapState); ``` -------------------------------- ### Initialize New Workspace Package Source: https://github.com/dfinity/icp-js-canisters/blob/main/ADMIN.md Use this command to initialize a new package within an npm workspace. Ensure you are in the project root directory. ```bash npm init -w ./packages/a ``` -------------------------------- ### Build or Test a Specific Package Source: https://github.com/dfinity/icp-js-canisters/blob/main/HACKING.md Use this command to build or test a particular package, specifying its path. Ensure that 'packages/utils' and 'packages/ledger-icrc' are built first due to inter-package dependencies. ```bash npm run build/test --workspace=packages/sns ``` -------------------------------- ### Instantiate and Fetch Metadata Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/ledger-icp/README.md Instantiate the IcpLedgerCanister with an agent and canister ID, then fetch token metadata. Requires prior creation of an agent. ```typescript import { createAgent, } from "@dfinity/utils"; import { IcpLedgerCanister } from "@dfinity/ledger-icp"; const agent = await createAgent({ identity, host: HOST, }); const { metadata } = IcpLedgerCanister.create({ agent, canisterId: MY_LEDGER_CANISTER_ID, }); const data = await metadata({}); ``` -------------------------------- ### Initialize and Use CkBtcMinterCanister Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/ckbtc/README.md Instantiate the CkBtcMinterCanister with an agent and canister ID to access its methods, such as retrieving a BTC address. ```typescript import { CkBtcMinterCanister } from "@dfinity/ckbtc"; import { createAgent } from "@dfinity/utils"; const agent = await createAgent({ identity, host: HOST, }); const { getBtcAddress } = CkBtcMinterCanister.create({ agent, canisterId: MY_CKBTC_MINTER_CANISTER_ID, }); const btcAddress = await getBtcAddress({}); ``` -------------------------------- ### createServices Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Creates canister services with specified options and IDL factories. ```APIDOC ## createServices ### Description Creates canister services with specified options and IDL factories. ### Type Signature `({ options: { canisterId, serviceOverride, certifiedServiceOverride, agent: agentOption, callTransform, queryTransform, }, idlFactory, certifiedIdlFactory, }: { options: Required, "canisterId">> and Omit, "canisterId"> and Pick<...>; idlFactory: IDL.InterfaceFactory; certifi...` ``` -------------------------------- ### Get ckETH Smart Contract Address Source: https://github.com/dfinity/icp-js-canisters/blob/main/docs/src/content/docs/quick-start.md Use the CkEthMinterCanister to retrieve the smart contract address for ckETH. Ensure you have created an agent and provided the canister ID. ```typescript import { CkEthMinterCanister } from "@icp-sdk/canisters/cketh"; import { createAgent } from "@dfinity/utils"; const agent = await createAgent({ identity, host: HOST, }); const { getSmartContractAddress } = CkEthMinterCanister.create({ agent, canisterId: MY_CKETH_MINTER_CANISTER_ID, }); const address = await getSmartContractAddress({}); ``` -------------------------------- ### Fetch Token Metadata with IcrcLedgerCanister Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/ledger-icrc/README.md Instantiate IcrcLedgerCanister and fetch token metadata. Requires an agent created with identity and host. ```typescript import { IcrcLedgerCanister, } from "@dfinity/ledger-icrc"; import { createAgent, } from "@dfinity/utils"; const agent = await createAgent({ identity, host: HOST, }); const { metadata } = IcrcLedgerCanister.create({ agent, canisterId: MY_LEDGER_CANISTER_ID, }); const data = await metadata({}); ``` -------------------------------- ### Implement Empty Test for New Library Source: https://github.com/dfinity/icp-js-canisters/blob/main/ADMIN.md Add an empty test file for a new library to ensure the test command does not fail due to a lack of tests. An import statement is required to prevent the file from being treated as a global script. ```javascript import * as lib from "./index"; describe("my-lib", () => { it("is implemented", () => { expect(lib).toEqual({}); }); }); ``` -------------------------------- ### Instantiate SNS Governance Canister (Descriptive Way) Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/sns/README.md Instantiate a specific SNS canister, like SnsGovernanceCanister, using the descriptive approach. This method limits the scope of features but is more verbose. ```typescript import { createAgent } from "@dfinity/utils"; import { SnsGovernanceCanister } from "@dfinity/sns"; const agent = await createAgent({ identity, host: HOST, }); const { metadata } = SnsGovernanceCanister.create({ agent, canisterId: rootCanisterId, }); const data = await metadata({ certified: true }); console.log("Summary data:", data); ``` -------------------------------- ### Initialize TokenAmountV2 from String Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Use `fromString` to initialize a token amount from a string. Accepted formats include standard decimal, with commas, or with single quotes for thousands separators. Requires a `Token` object for context. ```typescript TokenAmountV2.fromString({ amount: "1234567.8901", token: token }); ``` -------------------------------- ### Inspect Package Versions in Release Tags Source: https://github.com/dfinity/icp-js-canisters/blob/main/HACKING.md Iterate through release tags to inspect the package.json file and identify which tag shipped a specific version of a package. Useful for backporting fixes. ```bash # Check which tag had the target version for tag in v88 v89 v90; do echo "--- $tag ---" git show $tag:packages/utils/package.json | head -5 done ``` -------------------------------- ### Use ckETH Module Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/canisters/README.md Import and use the CkEthMinterCanister to interact with ckETH. Requires an agent created with createAgent. ```typescript import { CkEthMinterCanister } from "@icp-sdk/canisters/cketh"; import { createAgent } from "@dfinity/utils"; const agent = await createAgent({ identity, }); const { getSmartContractAddress } = CkEthMinterCanister.create({ agent, }); const address = await getSmartContractAddress({}); ``` -------------------------------- ### Initialize TokenAmountV2 from Number Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Use `fromNumber` to initialize a token amount from a number. Note that 1 integer is considered 10^token.decimals ulps. Requires a `Token` object for context. ```typescript TokenAmountV2.fromNumber({ amount: 1234567.8901, token: token }); ``` -------------------------------- ### Fetch Canister Status with ICMgmtCanister Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/ic-management/README.md Instantiate ICMgmtCanister and use its canisterStatus method to fetch the status of a specified canister. Requires an agent created with identity and host. ```typescript import { IcManagementCanister } from "@dfinity/ic-management"; import { createAgent } from "@dfinity/utils"; const agent = await createAgent({ identity, host: HOST, }); const { canisterStatus } = IcManagementCanister.create({ agent, }); const { status, memory_size, ...rest } = await canisterStatus(YOUR_CANISTER_ID); ``` -------------------------------- ### Token Parsing Utilities Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Utilities for parsing and converting token amounts. ```APIDOC ## fromString Initialize from a string. Accepted formats: 1234567.8901 1'234'567.8901 1,234,567.8901 ### Method Signature `fromString({ amount, token, }: { amount: string; token: Token; }) => FromStringToTokenError or TokenAmountV2` ### Parameters - `params.amount` (string): The amount in string format. - `params.token` (Token): The token type. ## fromNumber Initialize from a number. 1 integer is considered 10^{token.decimals} ulps ### Method Signature `fromNumber({ amount, token, }: { amount: number; token: Token; }) => TokenAmountV2` ### Parameters - `params.amount` (number): The amount in number format. - `params.token` (Token): The token type. ## toUlps Returns the amount in ulps. ### Method Signature `toUlps() => bigint` ## toE8s Returns the amount in ulps in e8s precision. ### Method Signature `toE8s() => bigint` ``` -------------------------------- ### Create AgentManager Instance Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Use the static `create` method to instantiate `AgentManager`. This method handles agent caching based on identity and configuration. ```typescript const agentManager = AgentManager.create({ fetchRootKey: true, host: "https://ic0.app", }); ``` -------------------------------- ### createAgent Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Create an agent for a given identity. ```APIDOC ## createAgent ### Description Create an agent for a given identity. ### Parameters - `params` (object) - The parameters to create a new HTTP agent - `params.identity` (object) - A mandatory identity to use for the agent - `params.host` (string) - An optional host to connect to, particularly useful for local development - `params.fetchRootKey` (boolean) - Fetch root key for certificate validation during local development or on testnet - `params.verifyQuerySignatures` (boolean) - Check for signatures in the state tree signed by the node that replies to queries - i.e. certify responses. - `params.retryTimes` (number) - Set the number of retries the agent should perform before error. ### Returns A promise that resolves with the created HttpAgent. ``` -------------------------------- ### Use ICRC Ledger Module Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/canisters/README.md Import and use the IcrcLedgerCanister to interact with ICRC ledgers. Requires an agent created with createAgent. ```typescript import { IcrcLedgerCanister } from "@icp-sdk/canisters/ledger/icrc"; import { createAgent } from "@dfinity/utils"; const agent = await createAgent({ identity, }); const { metadata } = IcrcLedgerCanister.create({ agent, }); const data = await metadata({}); ``` -------------------------------- ### Local Development with ICRC Ledger Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/canisters/README.md Configure the agent for local development, connecting to a local replica and specifying custom canister IDs. Requires an agent created with createAgent. ```typescript import { IcrcLedgerCanister } from "@icp-sdk/canisters/ledger/icrc"; import { createAgent } from "@dfinity/utils"; const agent = await createAgent({ identity, host: "http://localhost:4943", fetchRootKey: true, }); const { metadata } = IcrcLedgerCanister.create({ agent, canisterId: MY_CANISTER_ID, }); const data = await metadata({}); ``` -------------------------------- ### createUrlSchema Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/zod-schemas/README.md Creates a Zod schema for validating URLs with customizable protocol and local HTTP allowances. ```APIDOC ## createUrlSchema ### Description Creates a Zod schema for validating URLs. By default, it enforces HTTPS and allows HTTP only locally. ### Signature `createUrlSchema({ additionalProtocols, allowHttpLocally, }: { additionalProtocols?: `${string}:`[] | undefined; allowHttpLocally?: boolean | undefined; }) => ZodURL` ### Parameters * `options` - Configuration options for the schema. * `additionalProtocols` ( `${string}:`[] | undefined) - Additional protocols to allow (e.g., "wss:" or "ftp:"). Usage of insecure protocols is discouraged. * `allowHttpLocally` (boolean | undefined) - Whether to allow HTTP for localhost and 127.0.0.1. Defaults to true. ### Returns * The Zod schema with URL validation. ### Example ```typescript const schema = createUrlSchema({ additionalProtocols: ["wss:"] }); schema.parse("https://example.com"); // Valid schema.parse("wss://example.com"); // Valid const schemaAllowHttp = createUrlSchema({ allowHttpLocally: false }); schemaAllowHttp.parse("http://localhost"); // Invalid if allowHttpLocally is false ``` ``` -------------------------------- ### AgentManager Class Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Manages HttpAgent instances for different identities, caching them for efficiency. ```APIDOC ## AgentManager AgentManager class manages HttpAgent instances for different identities. It caches agents by identity to optimise resource usage and avoid unnecessary agent creation. Provides functionality to create new agents, retrieve cached agents, and clear the cache when needed. ### Static Methods #### create Static factory method to create a new AgentManager instance. ##### Method Signature `create(config: AgentManagerConfig) => AgentManager` ##### Parameters - `config` (AgentManagerConfig): Configuration options for the AgentManager instance. - `config.fetchRootKey` (boolean): Whether to fetch the root key for certificate validation. - `config.host` (string): The host to connect to. ##### Returns A new instance of `AgentManager`. ### Methods #### getAgent Get or create an HTTP agent for a given identity. If the agent for the specified identity has been created and cached, it is retrieved from the cache. If no agent exists for the identity, a new one is created, cached, and then returned. ##### Method Signature `getAgent({ identity, }: { identity: Identity; }) => Promise` ##### Parameters - `identity` (Identity): The identity to be used to create the agent. ##### Returns The HttpAgent associated with the given identity. #### clearAgents Clear the cache of HTTP agents. This method removes all cached agents, forcing new agent creation on the next request for any identity. Useful when identities have changed or if you want to reset all active connections. ##### Method Signature `clearAgents() => void` ``` -------------------------------- ### UrlSchema Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/zod-schemas/README.md Default URL schema that enforces HTTPS and allows HTTP locally. ```APIDOC ## UrlSchema ### Description Default URL schema that enforces HTTPS and allows HTTP locally. ### Type `ZodURL` ### Example ```typescript UrlSchema.parse("https://example.com"); // Valid UrlSchema.parse("http://127.0.0.1"); // Valid (localhost exception) ``` ``` -------------------------------- ### Query Icp to Cycles Conversion Rate Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/cmc/README.md Instantiate CmcCanister with an agent and canister ID to query the current ICP to cycles conversion rate. Ensure an agent is created with appropriate identity and host. ```typescript import { CmcCanister } from "@dfinity/cmc"; import { createAgent } from "@dfinity/utils"; const agent = await createAgent({ identity, host: HOST, }); const { getIcpToCyclesConversionRate } = CmcCanister.create({ agent, canisterId: CYCLES_MINTING_CANISTER_ID, }); const rate = await getIcpToCyclesConversionRate(); ``` -------------------------------- ### smallerVersion Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Compares the current version against a minimum version. Returns true if the current version is strictly smaller than the minimum version, ignoring patch versions and pre-release tags. ```APIDOC ## smallerVersion ### Description Returns true if the current version is smaller than the minVersion, false if equal or bigger. Tags after patch version are ignored, e.g. 1.0.0-beta.1 is considered equal to 1.0.0. ### Parameters - `params.minVersion` (string) - The minimum version string to compare against. Ex: "1.0.0" - `params.currentVersion` (string) - The current version string to compare. Ex: "2.0.0" ### Returns - `boolean` - True if `currentVersion` is smaller than `minVersion`, false otherwise. ``` -------------------------------- ### Accessing ICRC Ledger DID Types via Namespace Source: https://github.com/dfinity/icp-js-canisters/blob/main/docs/src/content/docs/upgrading/v3.md Demonstrates how to import and use DID types from the ICRC ledger canister through its dedicated namespace. This pattern improves code readability and helps avoid name clashes. ```typescript import { type IcrcLedgerDid, IcrcLedgerCanister, } from "@icp-sdk/canisters/ledger/icrc"; const { balance } = IcrcLedgerCanister.create({ agent, canisterId, }); const data: IcrcLedgerDid.Tokens = await balance({ owner }); ``` -------------------------------- ### hashText Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Generates a SHA-256 hash from a plain text string. ```APIDOC ## hashText ### Description Generates a SHA-256 hash from a plain text string. The string is UTF-8 encoded and hashed using the SubtleCrypto API. The resulting hash is returned as a hexadecimal string. ### Function Signature `(text: string) => Promise` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```json { "example": "Not applicable for this function" } ``` ### Response #### Success Response (200) - **string**: A promise that resolves to the hex string of the SHA-256 hash. ### Response Example ```json { "example": "Not applicable for this function" } ``` ``` -------------------------------- ### principalToSubAccount Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Convert a principal to a Uint8Array 32 length. ```APIDOC ## principalToSubAccount ### Description Convert a principal to a Uint8Array 32 length. e.g. Useful to convert a canister ID when topping up cycles with the Cmc canister. ### Function Signature `principalToSubAccount(principal: Principal): Uint8Array` ### Parameters #### Path Parameters - **principal** (Principal) - Required - The principal that needs to be converted to Subaccount. ### Returns - `Uint8Array`: A 32-length Uint8Array representing the subaccount. ``` -------------------------------- ### queryAndUpdate Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Performs a query (not-certified) call and/or an update (certified) call, and handles the results. Useful for security reasons to ensure certified results. ```APIDOC ## queryAndUpdate ### Description This service performs a query (not-certified) call and/or an update (certified) call, and handles the results. It is useful because it can do both type of calls for security reasons. For example, malicious nodes can forge transactions and balance when calling an Index canister, if no update is performed to certify the results. Furthermore, it can handle the results of the calls in different ways: `query` only performs a query call, `update` only performs an update call, `query_and_update` performs both calls. The resolution can be: `all_settled` waits for all calls to settle, `race` waits for the first call to settle (typically, `query` is the fastest one). Once the call(s) are done, the response is handled by the `onLoad` callback. However, if an error occurs, it is handled by the error callbacks, if provided: one for the query call and one for the update call. If no error callback is provided for the update call, the error is logged to the console. ### Parameters - `params` (object) - The parameters to perform the request. - `params.request` (object) - The request to perform. - `params.onLoad` (function) - The callback to handle the response of the request. - `params.onQueryError` (function) - The callback to handle the error of the `query` request. - `params.onUpdateError` (function) - The callback to handle the error of the `update` request. - `params.strategy` (string) - The strategy to use. Default is `query_and_update`. - `params.identity` (object) - The identity to use for the request. - `params.resolution` (string) - The resolution to use. Default is `race`. ### Returns A promise that resolves when the request is done. ``` -------------------------------- ### TokenAmountV2 Class Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Represents an amount of tokens, supporting decimals other than 8. ```APIDOC ## TokenAmountV2 ### Description Represents an amount of tokens. ### Static Methods #### fromUlps Initialize from a bigint. Bigint are considered ulps. ##### Parameters - `params.amount` (bigint) - The amount in bigint format. - `params.token` (Token) - The token type. ##### Returns - `TokenAmountV2` #### fromString Initialize from a string. ##### Parameters - `params.amount` (string) - The amount in string format. - `params.token` (Token) - The token type. ##### Returns - `TokenAmountV2` #### fromNumber Initialize from a number. ##### Parameters - `params.amount` (number) - The amount in number format. - `params.token` (Token) - The token type. ##### Returns - `TokenAmountV2` ``` -------------------------------- ### encodeBase32 Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Encodes a Uint8Array to a base32 string. ```APIDOC ## encodeBase32 ### Description Encode an Uint8Array to a base32 string. ### Signature `encodeBase32(input: Uint8Array) => string` ### Parameters #### Path Parameters - **input** (Uint8Array) - Required - The input array to encode. ### Returns A Base32 string encoding the input. ``` -------------------------------- ### isEmptyString Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Checks if a given value is null, undefined, or an empty string. ```APIDOC ## isEmptyString ### Description Checks if a given value is null, undefined, or an empty string. ### Parameters - `value` (string or null or undefined) - The value to check. ### Returns Type predicate indicating if the value is null, undefined, or an empty string. ``` -------------------------------- ### PrincipalSchema Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/zod-schemas/README.md Zod schema to validate and transform a value into a `Principal` instance. ```APIDOC ## PrincipalSchema ### Description Zod schema to validate and transform a value into a `Principal` instance. This schema checks if the provided value is an instance or an object representing a `Principal` and transforms it into a valid `Principal` instance. ### Type `ZodPipe, ZodTransform>` ### Example ```typescript const result = PrincipalSchema.safeParse(Principal.fromText("aaaaa-aa")); console.log(result.success); // true or false ``` ``` -------------------------------- ### Create URL Schema with Custom Protocols Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/zod-schemas/README.md Creates a Zod schema for URL validation. Allows specifying additional protocols and controlling HTTP allowance locally. By default, it validates HTTPS and allows HTTP locally. ```typescript const schema = createUrlSchema({ additionalProtocols: ["wss:"], allowHttpLocally: false }); schema.parse("https://example.com"); // Valid schema.parse("wss://example.com"); // Valid schema.parse("http://localhost"); // Invalid if allowHttpLocally is false ``` -------------------------------- ### decodeBase32 Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Decodes a base32 string to a Uint8Array. ```APIDOC ## decodeBase32 ### Description Decode a base32 string to Uint8Array. ### Signature `decodeBase32(input: string) => Uint8Array` ### Parameters #### Path Parameters - **input** (string) - Required - The input string to decode. - **input** (string) - Required - The base32 encoded string to decode. ### Returns A Uint8Array representing the decoded data. ``` -------------------------------- ### inferOptionSchema Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/zod-schemas/README.md Infers a Zod schema for optional values based on an existing schema. ```APIDOC ## inferOptionSchema ### Description Infers a Zod schema that represents an optional value. ### Signature `inferOptionSchema(schema: T) => ZodOptional` ### Parameters * `schema` (z.ZodType) - The base Zod schema to make optional. ``` -------------------------------- ### uint8ArrayToBigInt Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Converts a Uint8Array to a BigInt. ```APIDOC ## uint8ArrayToBigInt ### Description Converts a `Uint8Array` to a `bigint`. ### Type Signature `(array: Uint8Array) => bigint` ``` -------------------------------- ### notEmptyString Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Checks if a given value is not null, not undefined, and not an empty string. ```APIDOC ## notEmptyString ### Description Checks if a given value is not null, not undefined, and not an empty string. ### Parameters - `value` (string or null or undefined) - The value to check. ### Returns `true` if the value is not null, not undefined, and not an empty string; otherwise, `false`. ``` -------------------------------- ### uint8ArrayToBase64 Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Converts a Uint8Array (binary data) to a base64 encoded string. ```APIDOC ## uint8ArrayToBase64 ### Description Converts a Uint8Array (binary data) to a base64 encoded string. ### Signature `uint8ArrayToBase64(uint8Array: Uint8Array) => string` ### Parameters #### Path Parameters - **uint8Array** (Uint8Array) - Required - The Uint8Array containing binary data to be encoded. ### Returns - The base64 encoded string representation of the binary data. ``` -------------------------------- ### uint8ArraysEqual Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Compares two Uint8Arrays for byte-level equality. ```APIDOC ## uint8ArraysEqual ### Description Compare two Uint8Arrays for byte-level equality. ### Signature `uint8ArraysEqual({ a, b }: { a: Uint8Array; b: Uint8Array; }) => boolean` ### Parameters #### Path Parameters - **a** (Uint8Array) - Required - First Uint8Array to compare. - **b** (Uint8Array) - Required - Second Uint8Array to compare. ### Returns True if both arrays have the same length and identical contents. ``` -------------------------------- ### isNullish Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Checks if a given argument is either null or undefined. ```APIDOC ## isNullish ### Description Checks if a given argument is null or undefined. ### Function Signature `isNullish(argument: T | null | undefined): argument is null | undefined` ### Parameters - `argument` (T | null | undefined): The argument to check. ### Returns - `boolean`: `true` if the argument is null or undefined; otherwise, `false`. ``` -------------------------------- ### debounce Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Creates a debounced version of the provided function. ```APIDOC ## debounce ### Description Creates a debounced version of the provided function. The debounced function postpones its execution until after a certain amount of time has elapsed since the last time it was invoked. This is useful for limiting the rate at which a function is called (e.g. in response to user input or events). ### Function Signature `debounce(func: Function, timeout?: number | undefined): (...args: unknown[]) => void` ### Parameters #### Path Parameters - **func** (Function) - Required - The function to debounce. It will only be called after no new calls happen within the specified timeout. - **timeout** (number | undefined) - Optional - The debounce delay in milliseconds. Defaults to 300ms if not provided or invalid. ### Returns - `(...args: unknown[]) => void`: A debounced version of the original function. ``` -------------------------------- ### Uint8ArraySchema Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/zod-schemas/README.md Zod schema to validate a value is a `Uint8Array` instance. ```APIDOC ## Uint8ArraySchema ### Description Zod schema to validate a value is a `Uint8Array` instance. ### Type `ZodCustom, Uint8Array>` ### Example ```typescript const result = Uint8ArraySchema.safeParse(new Uint8Array([1, 2, 3])); console.log(result.success); // true or false ``` ``` -------------------------------- ### TokenAmount Class Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Represents an amount of tokens. This class is deprecated and TokenAmountV2 should be used instead. ```APIDOC ## TokenAmount ### Description Deprecated. Use TokenAmountV2 instead which supports decimals !== 8. Represents an amount of tokens. ### Static Methods #### fromE8s Initialize from a bigint. Bigint are considered e8s. ##### Parameters - `params.amount` (bigint) - The amount in bigint format. - `params.token` (Token) - The token type. ##### Returns - `TokenAmount` #### fromString Initialize from a string. Accepted formats: 1234567.8901, 1'234'567.8901, 1,234,567.8901. ##### Parameters - `params.amount` (string) - The amount in string format. - `params.token` (Token) - The token type. ##### Returns - `FromStringToTokenError | TokenAmount` #### fromNumber Initialize from a number. 1 integer is considered E8S_PER_TOKEN. ##### Parameters - `params.amount` (number) - The amount in number format. - `params.token` (Token) - The token type. ##### Returns - `TokenAmount` ### Methods #### toE8s Returns the amount of e8s. ##### Returns - `bigint` ``` -------------------------------- ### Configure TypeScript Module Resolution Source: https://github.com/dfinity/icp-js-canisters/blob/main/docs/src/content/docs/upgrading/v1.md Set 'moduleResolution' to 'node16', 'nodenext', or 'bundler' in your tsconfig.json when using TypeScript with the new package. ```json { "compilerOptions": { "moduleResolution": "node16" } } ``` -------------------------------- ### hashObject Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Generates a SHA-256 hash from an object after stringifying it with jsonReplacer. ```APIDOC ## hashObject ### Description Generates a SHA-256 hash from the given object. The object is first stringified using a custom `jsonReplacer`, then hashed using the SubtleCrypto API. The resulting hash is returned as a hex string. ### Function Signature `(params: T) => Promise` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **params** (T) - Required - The object to hash. ### Request Example ```json { "example": "Not applicable for this function" } ``` ### Response #### Success Response (200) - **string**: A promise that resolves to the hex string of the SHA-256 hash. ### Response Example ```json { "example": "Not applicable for this function" } ``` ``` -------------------------------- ### assertNever Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Utility to enforce exhaustiveness checks in TypeScript. ```APIDOC ## assertNever ### Description Utility to enforce exhaustiveness checks in TypeScript. This function should only be called in branches of a `switch` or conditional that should be unreachable if the union type has been fully handled. By typing the parameter as `never`, the compiler will emit an error if a new variant is added to the union but not covered in the logic. ### Parameters - `_`: A value that should be of type `never`. If this is not the case, the TypeScript compiler will flag a type error. - `message`: Optional custom error message to include in the thrown error. ### Type Signature `(_: never, message?: string or undefined) => never` ``` -------------------------------- ### asNonNullish Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Returns a value if it's not null or undefined, otherwise throws an error. ```APIDOC ## asNonNullish ### Description Returns a value if it's not null or undefined. If the value is nullish, it throws an error with an optional message. ### Type Signature `(value: T, message?: string or undefined) => NonNullable` ``` -------------------------------- ### Validate URL with HTTPS Enforcement Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/zod-schemas/README.md This schema validates URLs, enforcing HTTPS for general use and allowing HTTP for localhost connections. ```typescript UrlSchema.parse("https://example.com"); // Valid UrlSchema.parse("http://127.0.0.1"); // Valid (localhost exception) ``` -------------------------------- ### secondsToDuration Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Converts a duration in seconds to a human-readable string format. ```APIDOC ## secondsToDuration ### Description Convert seconds to a human-readable duration, such as "6 days, 10 hours." ### Function Signature `({ seconds, i18n, }: { seconds: bigint; i18n?: I18nSecondsToDuration or undefined; }) => string` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **options** (object) - Required - The options object. - **seconds** (bigint) - Required - The number of seconds to convert. - **i18n** (I18nSecondsToDuration or undefined) - Optional - The i18n object for customizing language and units. Defaults to English. ### Request Example ```json { "example": "Not applicable for this function" } ``` ### Response #### Success Response (200) - **string**: The human-readable duration string. ### Response Example ```json { "example": "Not applicable for this function" } ``` ``` -------------------------------- ### nowInBigIntNanoSeconds Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Returns the current timestamp in nanoseconds as a bigint. ```APIDOC ## nowInBigIntNanoSeconds ### Description Returns the current timestamp in nanoseconds as a `bigint`. ### Function Signature `nowInBigIntNanoSeconds(): bigint` ### Returns - `bigint`: The current timestamp in nanoseconds. ``` -------------------------------- ### nonNullish Source: https://github.com/dfinity/icp-js-canisters/blob/main/packages/utils/README.md Checks if a given argument is neither null nor undefined. ```APIDOC ## nonNullish ### Description Checks if a given argument is neither null nor undefined. ### Function Signature `nonNullish(argument: T | null | undefined): argument is NonNullable` ### Parameters - `argument` (T | null | undefined): The argument to check. ### Returns - `boolean`: `true` if the argument is not null or undefined; otherwise, `false`. ```