The Token Plugin provides comprehensive token management for ICP and ICRC-1/ICRC-2 tokens, including transfers, balance queries, and metadata operations.

Overview

The Token Plugin supports:
  • ICP Operations: Native ICP token transfers and balance queries
  • ICRC-1 Standard: Fungible token transfers and metadata
  • ICRC-2 Standard: Approve and transferFrom operations
  • Account Management: Principal and subaccount handling
  • Transaction Utilities: Amount parsing, formatting, and validation

ICP Operations

getBalance(account?)

Get ICP balance for the current identity or a specific account. Parameters:
  • account (optional): string - Account identifier (defaults to current identity)
Returns: Promise<bigint> - Balance in e8s (1 ICP = 100,000,000 e8s) Example:
// Get current identity's balance
const balance = await agent.tokenPlugin.getBalance();
console.log(`Balance: ${agent.tokenPlugin.formatAmount(balance, 8)} ICP`);

// Get balance for specific account
const specificBalance = await agent.tokenPlugin.getBalance('account-id-here');

transfer(to, amount, options?)

Transfer ICP tokens. Parameters:
  • to: string - Recipient account identifier
  • amount: bigint | number | string - Amount to transfer
  • options (optional): ITransferOptions
    • memo: bigint - Transaction memo
    • fee: bigint - Custom fee (optional)
    • fromSubaccount: Uint8Array - Source subaccount
Returns: Promise<ITransferResult>
  • blockHeight: bigint - Block height of the transaction
Example:
// Transfer 1 ICP with memo
const memo = agent.tokenPlugin.createMemo('Payment for services');
const result = await agent.tokenPlugin.transfer(
  'recipient-account-id',
  100_000_000n, // 1 ICP in e8s
  { memo }
);

console.log('Transaction block height:', result.blockHeight);

queryBlocks(start, length)

Query ICP ledger blocks. Parameters:
  • start: bigint - Starting block height
  • length: bigint - Number of blocks to query
Returns: Promise<unknown> - Block data

ICRC-1 Operations

icrc1Balance(canisterId, account?)

Get ICRC-1 token balance. Parameters:
  • canisterId: string - Token canister ID
  • account (optional): string | IAccount - Account to query (defaults to current identity)
Returns: Promise<bigint> - Token balance Example:
const tokenBalance = await agent.tokenPlugin.icrc1Balance(
  'token-canister-id',
  { 
    owner: Principal.fromText('principal-id'),
    subaccount: new Uint8Array(32) // Optional subaccount
  }
);

icrc1Transfer(canisterId, to, amount, options?)

Transfer ICRC-1 tokens. Parameters:
  • canisterId: string - Token canister ID
  • to: string | IAccount - Recipient account
  • amount: bigint | number | string - Amount to transfer
  • options (optional): Partial<ITransferOptions>
Returns: Promise<ITransferResult> Example:
const result = await agent.tokenPlugin.icrc1Transfer(
  'token-canister-id',
  { owner: Principal.fromText('recipient-principal'), subaccount: [] },
  1_000_000n,
  { memo: new Uint8Array([1, 2, 3, 4]) }
);

ICRC-2 Operations

icrc1Approve(canisterId, spender, amount, options?)

Approve a spender to use tokens on your behalf. Parameters:
  • canisterId: string - Token canister ID
  • spender: string | IAccount - Spender account
  • amount: bigint | number | string - Amount to approve
  • options (optional): Partial<IApproveArgs>
Returns: Promise<bigint> - Approval transaction ID Example:
const approvalId = await agent.tokenPlugin.icrc1Approve(
  'token-canister-id',
  { owner: Principal.fromText('spender-principal'), subaccount: [] },
  500_000n
);

icrc1Allowance(canisterId, owner, spender)

Check allowance between owner and spender. Parameters:
  • canisterId: string - Token canister ID
  • owner: string | IAccount - Token owner
  • spender: string | IAccount - Approved spender
Returns: Promise<IAllowance>
  • allowance: bigint - Approved amount
  • expires_at: bigint[] - Expiration time (optional)
Example:
const allowance = await agent.tokenPlugin.icrc1Allowance(
  'token-canister-id',
  { owner: ownerPrincipal, subaccount: [] },
  { owner: spenderPrincipal, subaccount: [] }
);

console.log('Approved amount:', allowance.allowance);

Account Utilities

getAccountId(principal?, subaccount?)

Get ICP account identifier. Parameters:
  • principal (optional): string | Principal - Principal (defaults to current identity)
  • subaccount (optional): Uint8Array - Subaccount bytes
Returns: string - Account identifier Example:
// Get current identity's account ID
const accountId = agent.tokenPlugin.getAccountId();

// Get account ID for specific principal with subaccount
const subaccount = new Uint8Array(32);
subaccount[0] = 1; // First subaccount
const specificAccountId = agent.tokenPlugin.getAccountId(
  'principal-id',
  subaccount
);

createAccount(principal, subaccount?)

Create an account object. Parameters:
  • principal: string | Principal - Account owner principal
  • subaccount (optional): Uint8Array - Subaccount bytes
Returns: IAccount
  • owner: Principal - Account owner
  • subaccount: Uint8Array - Subaccount
Example:
const account = agent.tokenPlugin.createAccount(
  'principal-id',
  new Uint8Array(32)
);

generateSubaccount()

Generate a random subaccount. Returns: Uint8Array - 32-byte subaccount Example:
const subaccount = agent.tokenPlugin.generateSubaccount();
const accountId = agent.tokenPlugin.getAccountId(undefined, subaccount);

validateAccount(account)

Validate an account identifier. Parameters:
  • account: string - Account identifier to validate
Returns: boolean - Whether account is valid

Transaction Utilities

parseAmount(amount, decimals?)

Parse amount string to bigint. Parameters:
  • amount: string - Amount as string (e.g., “1.5”)
  • decimals (optional): number - Token decimals (default: 8)
Returns: bigint - Parsed amount Example:
const amount = agent.tokenPlugin.parseAmount('1.5', 8);
// Returns: 150000000n (1.5 * 10^8)

formatAmount(amount, decimals?)

Format bigint amount to string. Parameters:
  • amount: bigint - Amount in smallest units
  • decimals (optional): number - Token decimals (default: 8)
Returns: string - Formatted amount Example:
const formatted = agent.tokenPlugin.formatAmount(150000000n, 8);
// Returns: "1.5"

createMemo(input)

Create a transaction memo. Parameters:
  • input: string | number | bigint - Memo input
Returns: bigint - Memo as bigint Example:
const memo = agent.tokenPlugin.createMemo('Payment #123');
await agent.tokenPlugin.transfer('recipient', 100000000n, { memo });

estimateFee(canisterId?, priority?)

Estimate transaction fee. Parameters:
  • canisterId (optional): string - Token canister ID (for ICRC tokens)
  • priority (optional): boolean - Priority transaction
Returns: Promise<IFeeEstimate>
  • amount: bigint - Estimated fee
  • currency: string - Fee currency
Example:
const fee = await agent.tokenPlugin.estimateFee();
console.log(`Estimated fee: ${fee.amount} ${fee.currency}`);

Metadata Operations

getTokenMetadata(canisterId?)

Get token metadata. Parameters:
  • canisterId (optional): string - Token canister ID (omit for ICP)
Returns: Promise<ITokenMetadata>
  • name: string - Token name
  • symbol: string - Token symbol
  • decimals: number - Token decimals
  • fee: bigint - Transfer fee
  • totalSupply: bigint - Total supply (if available)
Example:
// Get ICP metadata
const icpMetadata = await agent.tokenPlugin.getTokenMetadata();

// Get ICRC-1 token metadata
const tokenMetadata = await agent.tokenPlugin.getTokenMetadata('token-canister-id');
console.log(`${tokenMetadata.name} (${tokenMetadata.symbol})`);

getSupportedStandards(canisterId)

Get supported token standards. Parameters:
  • canisterId: string - Token canister ID
Returns: Promise<string[]> - Supported standards Example:
const standards = await agent.tokenPlugin.getSupportedStandards('token-canister-id');
console.log('Supported standards:', standards); // ['ICRC-1', 'ICRC-2']

Types

IAccount

ICRC account structure.
interface IAccount {
  owner: Principal;
  subaccount: Uint8Array;
}

ITransferResult

Transfer operation result.
interface ITransferResult {
  blockHeight: bigint;
}

ITransferOptions

Transfer operation options.
interface ITransferOptions {
  memo?: bigint;
  fee?: bigint;
  fromSubaccount?: Uint8Array;
}

ITokenMetadata

Token metadata information.
interface ITokenMetadata {
  name: string;
  symbol: string;
  decimals: number;
  fee: bigint;
  totalSupply?: bigint;
}

Usage Patterns

Multi-Token Portfolio Management

// Check balances across multiple tokens
const icpBalance = await agent.tokenPlugin.getBalance();
const token1Balance = await agent.tokenPlugin.icrc1Balance('token1-canister');
const token2Balance = await agent.tokenPlugin.icrc1Balance('token2-canister');

console.log('Portfolio:');
console.log(`ICP: ${agent.tokenPlugin.formatAmount(icpBalance, 8)}`);
console.log(`Token1: ${agent.tokenPlugin.formatAmount(token1Balance, 6)}`);
console.log(`Token2: ${agent.tokenPlugin.formatAmount(token2Balance, 18)}`);

Automated Trading Operations

// Approve DEX to spend tokens
await agent.tokenPlugin.icrc1Approve(
  'token-canister',
  'dex-canister-principal',
  1000000n
);

// Execute trade through DEX
// ... DEX interaction code ...

// Check remaining allowance
const remaining = await agent.tokenPlugin.icrc1Allowance(
  'token-canister',
  myAccount,
  dexAccount
);

Subaccount Management

// Create multiple subaccounts for organization
const tradingSubaccount = agent.tokenPlugin.generateSubaccount();
const savingsSubaccount = agent.tokenPlugin.generateSubaccount();

const tradingAccountId = agent.tokenPlugin.getAccountId(undefined, tradingSubaccount);
const savingsAccountId = agent.tokenPlugin.getAccountId(undefined, savingsSubaccount);

// Transfer to subaccounts
await agent.tokenPlugin.transfer(tradingAccountId, 50000000n); // 0.5 ICP
await agent.tokenPlugin.transfer(savingsAccountId, 100000000n); // 1 ICP