Complete canister management functionality for ICP Agent Kit
The Canister Plugin provides comprehensive canister management capabilities for the ICP Agent Kit. It enables creating, deploying, managing, and interacting with canisters on the Internet Computer Protocol.
The Canister Plugin requires the @dfinity/ic-management package and integrates with the IC Management Canister for all operations.
The Canister Plugin now features improved TypeScript support with strict type checking, better error handling, and full compatibility with the latest @dfinity packages.
// Stop a running canisterawait canister.stop(canisterId);// Start a stopped canister await canister.start(canisterId);// Delete and recover cyclesawait canister.delete(canisterId);// Uninstall code from a canister (keeps the canister but removes code)await canister.uninstallCode(canisterId);// Check if a canister existsconst exists = await canister.exists(canisterId);console.log(`Canister exists: ${exists}`);// Check if you're a controllerconst isController = await canister.isController(canisterId);console.log(`You are ${isController ? 'a' : 'not a'} controller`);
The Canister Plugin provides powerful methods to interact with any deployed canister on the Internet Computer, whether it’s your own or a third-party canister.
To interact with a canister, you need its Interface Description Language (IDL) factory. This TypeScript code describes the canister’s methods and types:
Copy
// Example IDL factory for a simple greeting canisterexport const idlFactory = ({ IDL }) => { return IDL.Service({ 'greet': IDL.Func([IDL.Text], [IDL.Text], ['query']), 'setGreeting': IDL.Func([IDL.Text], [], []), });};
IDL factories are typically generated from .did files using dfx generate or the didc tool.
Handle common errors when interacting with canisters:
Copy
try { const result = await canister.call({ canisterId, methodName: 'riskyOperation', args: [param], idlFactory, });} catch (error) { if (error.message.includes('trapped')) { console.error('Canister trapped:', error.message); } else if (error.code === 'METHOD_NOT_FOUND') { console.error('Method does not exist on canister'); } else if (error.message.includes('out of cycles')) { console.error('Canister is out of cycles'); }}
// Take a snapshotconst snapshot = await canister.takeSnapshot(canisterId);console.log(`Snapshot created with ID: ${snapshot.id}`);// List all snapshotsconst snapshots = await canister.listSnapshots(canisterId);snapshots.forEach(snap => { console.log(`Snapshot ${snap.id} taken at ${snap.taken_at_timestamp}`);});// Restore from snapshotawait canister.loadSnapshot(canisterId, snapshot.id);
// Format cycles for displaycanister.formatCycles(5_000_000_000_000n); // "5T"// Parse cycles from stringcanister.parseCycles('1.5T'); // 1_500_000_000_000n// Format canister settingsconst formatted = canister.formatSettings(settings);