@icp-sdk/core/candid
JavaScript and TypeScript module to work with Candid interfaces
Usage
import { IDL } from '@icp-sdk/core/candid';
API Reference
Additional API Documentation can be found here.
JavaScript and TypeScript library to work with candid interfaces
JavaScript and TypeScript module to work with Candid interfaces
import { IDL } from '@icp-sdk/core/candid';
Additional API Documentation can be found here.
effectiveCanisterId
(if provided) instead of the canisterId
to verify the certificate of an update call.Rec()
s are present in the same struct.Publishes the new @icp-sdk/core
package.
This package unifies the following packages:
@dfinity/agent
@dfinity/candid
@dfinity/identity
@dfinity/identity-secp256k1
@dfinity/principal
and re-exports them as @icp-sdk/core/*
submodules.
The @icp-sdk/core
package does not contain any other changes.
See the upgrading guide for more information.
@dfinity/use-auth-client
: this package has been deprecated. We recommend using one of the following alternatives:
bigint
to the JsonValue
types in @dfinity/candid
.GenericIdlFuncArgs
, GenericIdlFuncRets
, and GenericIdlServiceFields
types from @dfinity/candid
.clockDriftMs
optional parameter to Expiry.fromDeltaInMilliseconds
to add to the current time, typically used to specify the clock drift between the IC network clock and the client's clock.FuncClass
.ServiceClass
.Certificate
instance.agent
optional field to the CreateCertificateOptions
interface, which is used to sync time with the IC network if the certificate fails the freshness check, if provided.getTimeDiffMsecs
method to the HttpAgent
class, which returns the time difference in milliseconds between the IC network clock and the client's clock.hasSyncedTime
method to the HttpAgent
class, which returns true
if the time has been synced at least once with the IC network, false
otherwise.disableCertificateTimeVerification
optional field to the CanisterStatus.request
function argument, which allows you to control the disableTimeVerification
option for the internal Certificate.create
call.UncertifiedRejectUpdateErrorCode
error code.UncertifiedRejectUpdateErrorCode
when throwing an error in v2 responses.UncertifiedRejectUpdateErrorCode
if the reply from the update call was returned undefined and the method has no return type.getCrc32
function from @dfinity/principal
instanceof
in Candid IDL types to avoid issues when importing IDL
from multiple locations.pnpm dlx tsx
for version management scriptsingressExpiryInMinutes
option (taking into account the clock drift).AuthClient.create
's options now have an additional loginOptions
optional parameter, which is merged with the options passed to login
when calling it.lebEncode
and slebEncode
from @dfinity/candid
. As a result, @dfinity/candid
now correctly encodes large bigints as Nat
values..ts
extension required for all relative imports. This is required to avoid the "Module not found" error when importing the packages in Node.js (ESM).@noble/*
dependencies@noble/hashes
as a dependency rather than a dev dependencyUint8Array<ArrayBuffer>
instead of ArrayBuffer
to make the API more consistent.fromHex
, toHex
, concat
utils with bytesToHex
, hexToBytes
, and concatBytes
from @noble/hashes/utils
respectively, to take advantage of existing dependencies.read_state
requests to support presigned requests. By default, read_state
requests will create a new signature with a new ingress expiry each time they are made. However, the new preSignReadStateRequest
will make one signature and use it for all polling requests. This is useful for hardware wallets or other external signing solutions that make signing cumbersome.strategy
, request
, and preSignReadStateRequest
to the options: PollingOptions
objectPollingOptions
typepollingOptions
object that can be passed to the actor
function and will be passed to the pollForResponse
methoddefaultAgent
global concept and the getDefaultAgent
function. The HttpAgent
constructor is now the only way to create an agent.ProxyAgent
class.feat!: removes the following errors in favor of the new AgentError
:
AgentHTTPResponseError
AgentCallError
AgentQueryError
AgentReadStateError
CertificateVerificationError
ActorCallError
QueryCallRejectedError
UpdateCallRejectedError
The new AgentError
error uses the code
and kind
props to enable a better programmatic error handling.
feat!: refactors Expiry
class to use static factory methods and add JSON serialization/deserialization.
lookup_path
compliant with the IC Interface Specification. Renames the lookup
method of the Certificate
class into lookup_path
, for consistency.lookup_label
method from the Certificate
class.hash
with sha256
from @noble/hashes/sha2
to take advantage of existing dependencieschore!: drops support for Node.js v19 or lower, and Node.js v21
feat: replaces borc
and simple-cbor
with @dfinity/cbor
.
bs58check
dependency from @dfinity/identity-secp256k1
isAuthenticated
now correctly returns false if the delegation chain is invalid; eg: expired sessionlookup_subtree
standalone function and Certificate
class method.Actor
with v1
HttpAgent due to breaking interface changes.toRaw
where the output was not an ArrayBufferpocket-ic
by querying for the default_effective_canister_id
before calling the management canisterPrincipal
library where the management canister id util was incorrectly importing using fromHex
opt
types up to Candid spec:
In particular, when decoding at an opt
type:opt
type, decode its payload at the expected content type
(as before).null
wire type as IDL value null
(i.e. JS []
).reserved
wire type, defaulting to IDL value null
(i.e. JS []
).null
(i.e. JS []
).null
or reserved
or (nested) opt
, return IDL value null
(i.e. JS []
).null
, reserved
or nested opt
:
allow decoding of the non-optioned value v
as opt v
(JS [v*]
) if compatible with
the expected content type; if incompatible, return IDL value null
(JS []
).HttpAgent
constructorshouldFetchRootKey
is settarget_canister
is used only for install_chunked_code
of management canister, complying with internet computer specificationAuthClient
during authentication.AuthClient
during authentication.feat: allow for setting HttpAgent ingress expiry using ingressExpiryInMinutes
option
feat: improved assertion options for agent errors using prototype
, name
, and instanceof
AgentError: Call failed:
Canister: hbrpn-74aaa-aaaaa-qaaxq-cai
Method: Throw (update)
"Request ID": "ae107dfd7c9be168a8ebc122d904900a95e3f15312111d9e0c08f136573c5f13"
"Error code": "IC0406"
"Reject code": "4"
"Reject message": "foo"
UpdateCallRejected
error now exposes reject_code: ReplicaRejectCode
, reject_message: string
, and error_code?: string
properties directly on the error object.Expiry
when polling for read_state
requests. This prevents the request from exceeding the maximum_ingress_expiry
when the replica is slow to respond.@dfinity/assets
Certificate
for inspection or use in raw calls. Certificate.cert
is now a public propertyuseAuthClient
by passing a record to actorOptions
with the actor name as the key, and CreateActorOptions
as the valueHttpAgent.call
, which defaults to true
rootKey
to HttpAgentOptions
to allow for a custom root key to be used for verifying signatures from other networks@dfinity/agent
for use in other packagespollForResponse
now uses the default strategy by defaultbls-verify
jsdoc comment to accurately reflect that the default strategy now uses @noble/curveseffectiveCanisterId
in CallOptions
@scure/bip39
and @scure/bip32
due to vulnerability and lack of maintenance for elliptic
request
correctly during pollForResponse Processing
statusHttpAgent
constructor in favor of new create
and createSync
methods.create
is async and returns a promise. It will sync time with the replica and fetch the root key if the host is not https://icp-api.io
source
option with a from
and fromSync
methods, similar to Principal.from
update-management-idl
automation to update the management canister IDL in @dfinity/agent
log
method is renamed to print
to avoind calling log.log
.package-lock.json
file with the correct dependencies when making a new releasenpm audit
check to PRsHttpAgent
option: backoffStrategy
- allows you to set a custom delay strategy for retries. The default is a newly exported exponentialBackoff
, but you can pass your own function to customize the delay between retries.IdbStorage
get/set
methods genericfetch_canister_logs
in the actor provided by getManagementCanister
Logging
// Agent should not use an anonymous identity for this call, and should ideally be a canister controller
const management = await getManagementCanister({ agent });
const logs = await management.fetch_canister_logs({ canister_id: canisterId });
Bitcoin
// For now, the verifyQuerySignatures option must be set to false
const agent = await makeAgent({ host: 'https://icp-api.io', verifyQuerySignatures: false });
const management = getManagementCanister({
agent,
});
const result = await management.bitcoin_get_balance_query({
address: 'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh',
network: { mainnet: null },
min_confirmations: [6],
});
allowPinAuthentication?: boolean;
authnMethod: 'passkey' | 'pin' | 'recovery';
customValues
optionfix: pads date numbers in changelog automation. E.G. 2024-3-1 -> 2024-03-01
feat: allow passing DBCreateOptions
to IdbStorage
constructor
PublicKeyCredential
not being enumerablefromPem
method for identity-secp256k1
ArrrayBuffer
checks from WebAuthnIdentity
to resolve issues with the Bitwarden password managerEd25519KeyIdentity
was not generating unique identities when no seed was provided. This issue was introduced in v0.20.0-beta.0
. If your code was affected please upgrade to >=1.0.1
AuthClientStorage
to aid with custom implementationsCustomPath
class, better docs, and deprecating metadata path type for CanisterStatus
CustomPath
class, better docs, and deprecating metadata path type for CanisterStatus
ObservableLog
to HttpAgent
. Allows subscribers to be notified of events from the agent without sending them directly to the console.from
methods on public key classes to support unknown types, including PublicKey instances, ArrayBuffer-like objects, DER encoded public keys, and hex strings. Also introduces a new bufFromBufLike
utilsecp256k1
npm package with @noble/curves
github.dev
and gitpod.io
to known hostsagent-js
, with a timeout of 1 hourHttpAgent
option - verifyQuerySignatures
. Defaults to true, but allows you to opt out of verification. Useful for testing against older replica versions
Introducing ed25519
logic to agent for validating node signatures
Standardizing around @noble/curves
instead of tweetnacl in @dfinity/identity
new export - hashOfMap from agent, matching the naming used in the interface specification
new unit tests
new Verify export on ed25519 because why not
Adds support for Uint8Arrays
in Principal.from()
feat: introduces ExpirableMap
, a utility class that will return values up until a configured expiry
chore: increases size limit for agent-js
to allow for Ed25519
support for node key signature verification
feat!: replaces disableNonce
feature with useQueryNonces
. Going forward, updates will use nonces, but queries and readstate calls will not. Queries and readsatate calls will use nonces if useQueryNonces
is set to true
feat: adds subnet metrics decoding to canisterStatus for /subnet
path
feat!: sets expiry to 1 minute less than the configured expiry, and then down to the nearest second. This matches existing behaviour, but adds the roundingagent-js
canisterStatus
returns full list of controllerslocalhost
with 127.0.0.1
for better node 18 support. Also swaps Jest for vitest, runs mitm against mainnet, and updates some packageslookup\_path
to allow returning a HashTree
, but also constrains lookup
response to an ArrayBuffer
using a new lookupResultToBuffer
exportPrincipal
JSON is compatible with @dfinity/utils ``jsonReviver
helperPrincipal
class serializes to JSONleb
decoding utils added to @dfinity/agent/utils/leb
to make it simpler to decode leb values and time from a certificate treeicp0.io
and ic0.app
were incorrectly sending requests to icp-api
and encountering CSP issuesjs-sha256
library with @noble/hashes
due to a breaking bug in Chrome@dfinity/principal
as a peerDependency to assets
and candid
.HttpAgent
now uses a default address of https://icp-api.io. Users will be warned for not setting a host, but the code will default to mainnet.JsonnableWebAuthnIdentitiy
, breaking change that requires users to update their imports to JsonnableWebAuthnIdentity
when this type is usedcomposite_query
in candidDo not use Headers
struct during init of HttpAgent for Node compatibility. Note: still supports use of Headers in application code
fix: finish all tasks before calling onSuccess auth callback in @dfinity/auth-client
read\_state
requestsAuthClient
, allowing users to specify whether to use an ed25519
or ECDSAKey
. This is important for custom storage providers that can't store CryptoKey
objectsHttpAgent
X-IC-Request-ID header
until we coordinate cors support with icx-proxyauth-client
package.jsonX-IC-Request-ID header
to more easily identify retried requests. Also uses a standard Headers constructor to manage headersChanges default stored key for auth-client
to use ECDSAKey* Also updates the storage interface types to support CryptoKeyPair
identity-secp256k1
in docs site@dfinity/identity-secp256k1
Secp256k1KeyIdentity
to its own package. @dfinity/identity-secp256k1
Breaking change: Deprecates @dfinity/authentication
. If you relied on the isDelegationValid
check, it has been moved to @dfinity/identity
Deprecates @dfinity/identity-ledgerhq
. Use @zondax/ledger-icp
instead.
secp256k1
now supports a fromSeedPhrase
method that will reproduce the same identity across agent-js
, dfx
, and quill
unpkg
to use esmodulesjs-sha256
dependency to principalcreateOptions.identity
or authClient.login
to be called before starting idle timeoutHttpAgent
. By default, retries three times before throwing an error, to offer a more cohesive workflowfetchCandid()
function which retrieves the Candid interface for a given canister id.auth-client
expose storage constant keysauth-client
resolves window.open issue in login function in safari due to async storage callauth-client
storage wrapper returns after resolve to avoid idb to be recreated@dfinity/bls-verify
. This package provides a pure-js implementation of BLS verification using the miracl-core
package. This can be used to polyfill BLS verification for agent-js
, but it is notably very slow (~3s per verification). Optimization may be possible with a significant refactoring\_key
non-nullable. This fixes a regression with async window.open behavior in SafariHttpAgent
now offers a method to sync time with the replica, provided a specific canister. This can be used to set proper Expiry
times when a device has fallen out of sync with the replica.auth-client
avoids localstorage global and can be used in a web worker or nodejsauth-client
logout now awaits clearing storageAuthClient now uses IndexedDb
by default. To use localStorage, import LocalStorage provider and pass it during AuthClient.create()
.
Also offers a generic IndexedDb
keyval store, IdbKeyVal
AuthClient
migrates gracefully from localstorage to IDB when upgrading
SubtleCrypto
interface in @dfinity/identity
using the new ECDSAKeyIdentity
CanisterStatus
no longer suppresses rootKey errorsUTF-8
as an encoding option for CanisterStatus
custom pathscreateReadStateRequest
that creates the request for readState
.readState
to pass a created request. If this parameter is passed, the method does the request directly without creating a new one.createReadStateRequest
and the extra parameter when polling for the response to avoid signing requests during polling.derivationOrigin
to auth-client
login to support the ability to login using the identity derived from a different origin. See proposed changesIdleManager
that will refresh the page after clearing the storageAdds a new utility method, canisterStatus
, to agent-js
. Canister status now allows you to query paths from the canister certificate with a simple interface, using the API from theinterface specification
Comes with nicely configured options for
time
, controllers
, subnet
, module_hash
, candid
. Additionally, has a utility for reading custom MetaData set using ic-wasm, as well as generic custom paths in the format of ArrayBuffers.
updates to package.json files for metadata in npm
IdleManager
to the auth-client
. You can now use it to detect when the user has been idle for a configurable amount of time, and then to register callbacks for the sake of logging the user out and prompting re-authentication. See the @dfinity/auth-client
Readme for more detailsmaxTimeToLive
default setting from 24 hours to 8HttpAgent
now generates a nonce to ensure that calls are unique by default. If you want to opt out or provide your own nonce logic, you can now pass an option of disableNonce: true
during the agent initialization.
If you are currently using agent.addTransform(makeNonceTransform())
, please note that you should remove that logic, or add the disableNonce
option to your agent when upgrading.
auth-client
, login onSuccess
callback and onError
callback now supports async pattern.Security enhancement - adds a rewrite for urls to subdomains of
\*.ic0.app/api
to
ic0.app/api
Improves error messages for when HttpAgent
cannot infer fetch
implementation
auth-client
identity option and added JSDOC comment for the timeToLive
optionauthClient
, up from 15 minutesPrincipal
in @dfinity/agent
, which should allow non-identical versions of packages to interoperate, as long as they share the same APIagent-js
packagesBuffer
and Pipe
refactorBuffer
, a polyfilled version of the Node.js Buffer
utility. In a significant refactor, we have removed all cases of this, along with Pipe
and the nonstandard Blob
packages, in favor of ArrayBuffer
, Uint8Array
, and DataView
blobToUint8Array
have been removed.Buffer
and related packages have been updated to accept ArrayBuffer
, and the type interfaces are updated to reflect thisSecp256k1
Support@dfinity/identity
- Secp256k1KeyIdentity
and Secp256k1PublicKey
ed25519
components, and relies on the secp256k1 npm package for signing and verification.