@console-wallet/dapp-sdk

中文文档
3.0.0发布于 2026/10/09ISCTypeScriptESM + CJS近 30 天下载 3323

Console DApp SDK allows dApps to connect to a Console Wallet account. The Console wallet is a browser extension. All interaction happens inside the dApp. For signing, users will be prompted to sign in their Console Wallet browser extension.

原始使用文档
文档目录40 节
  1. Installation
  2. Usage Guide
  3. 1. Import the SDK
  4. 2. Check Wallet Availability
  5. 3. Check Connection Status
  6. 4. Connect to the Wallet
  7. 4.1 Mobile Connect and QR Code Flow
  8. 5. Get Active Account
  9. API Methods
  10. Connection & Account Management
  11. Signing & Transactions
  12. Balance & History Queries
  13. Usage Examples
  14. Sign a Message
  15. Encrypt / Decrypt Message
  16. Send Canton Coin Transaction
  17. Sign a Batch of Transactions
  18. Get Balance
  19. Get Traffic Balance
  20. Convert Traffic
  21. Top Up Traffic
  22. Get Coins Balance with Prices
  23. Get Coins List by Network
  24. Get Transaction History
  25. Subscriptions
  26. Example: Watch Account Changes
  27. Example: Watch Connection Status
  28. Example: Watch Transaction Status
  29. Example: Auto-Render Connected State on SDK Load
  30. Example: Tear Down UI State When Session Dies
  31. Error Handling
  32. ConsoleWalletError Interface
  33. Common Error Codes
  34. Transaction Metadata
  35. Transaction Costs
  36. How It Works
  37. API Reference
  38. Type Exports
  39. Utility Functions
  40. Changelog

Console DApp SDK

Console DApp SDK allows dApps to connect to a Console Wallet account. The Console wallet is a browser extension. All interaction happens inside the dApp. For signing, users will be prompted to sign in their Console Wallet browser extension.

This SDK is compatible with the CIP-0103 standard.

Installation

To use the Console DApp SDK, you first need to install it from NPM:

npm install @console-wallet/dapp-sdk
# or
yarn add @console-wallet/dapp-sdk

Note that, if you don't want to implement a build process, you can include the file directly with unpkg:

<script type="module">
  import { consoleWalletPixelplex } from 'https://unpkg.com/@console-wallet/dapp-sdk@latest/dist/esm/index.js';
</script>

Usage Guide

1. Import the SDK

import { consoleWalletPixelplex } from '@console-wallet/dapp-sdk';

2. Check Wallet Availability

Before attempting to connect, check if the Console Wallet extension is installed and capable by version:

const checkWallet = async () => {
  try {
    const availability = await consoleWalletPixelplex.checkExtensionAvailability();
    if (availability.status === 'installed') {
      console.log('Console Wallet is installed');
    } else {
      console.log('Console Wallet is not installed');
      // Show installation instructions to the user
    }

    if (availability.isExtensionCapableByVersion) {
      console.log('Console Wallet is capable by version');
    } else {
      console.log('Console Wallet is not capable by version');
    }
  } catch (error) {
    console.error('Error checking wallet availability:', error);
  }
};

3. Check Connection Status

You can check the current connection status at any time:

const checkStatus = async () => {
  try {
    const status = await consoleWalletPixelplex.status();
    console.log('Connection status:', status.isConnected); // 'connected' or 'disconnected'
  } catch (error) {
    console.error('Error checking status:', error);
  }
};

4. Connect to the Wallet

To initiate the connection, call connect() with optional dApp metadata:

const handleConnect = async () => {
  try {
    const status = await consoleWalletPixelplex.connect({
      name: 'My Awesome dApp',
      icon: 'https://example.com/icon.png', // Optional: absolute URL to your dApp icon
    });

    if (status === 'connected') {
      console.log('Successfully connected to Console Wallet');
      // Proceed with your dApp logic
    }
  } catch (error) {
    console.error('Connection rejected or failed:', error);
  }
};

4.1 Mobile Connect and QR Code Flow

The SDK supports three connection targets:

  • local — browser extension only
  • remote — mobile app session only (QR / deep link)
  • combined — chooses the best available connector (extension or mobile)

Use target: 'remote' when you want to force the mobile/QR flow:

const connectWithMobile = async () => {
  try {
    const status = await consoleWalletPixelplex.connect({
      name: 'My Awesome dApp',
      icon: 'https://example.com/icon.png',
      target: 'remote',
    });

    if (status.isConnected) {
      console.log('Connected through mobile flow');
    }
  } catch (error) {
    console.error('Mobile connect failed:', error);
  }
};

How the remote flow behaves:

  • Desktop browser: SDK renders a QR modal in the page; user scans with Console Wallet mobile app.
  • Android browser: SDK opens Console Wallet mobile directly via deep link.
  • iOS browser: SDK shows modal with a mobile button that opens deep link.

Notes for integration:

  • The QR/deep-link modal is injected into document.body.
  • Root container id is console-wallet-connect-placeholder.
  • If user closes the modal, the session is canceled and the request is rejected.
  • You can force extension-first behavior by using target: 'local'.
  • You can allow automatic selection by using target: 'combined'.

5. Get Active Account

Once connected, retrieve the active account:

const getAccount = async () => {
  try {
    const account = await consoleWalletPixelplex.getPrimaryAccount();
    if (account) {
      console.log('Active account:', account.partyId);
      console.log('Network:', account.networkId);
      console.log('Public key:', account.publicKey);
    }
  } catch (error) {
    console.error('Error getting account:', error);
  }
};

API Methods

The SDK exposes several high-level request methods that communicate with the Console Wallet Extension through secure message passing. Each request is automatically tagged with a unique request ID to ensure reliable response matching.

Connection & Account Management

MethodDescriptionRequest PayloadResponse
connect(data)Prompts the user to connect their Console Wallet to the DApp (target: local / remote / combined).ConnectRequestConnectResponse
status()Returns current connection status for the dApp origin.—StatusEvent
disconnect()Disconnects the DApp from the wallet.—DisconnectResponse
checkExtensionAvailability()Checks whether the wallet browser extension is installed.—AvailabilityResponse
getWalletMetadata()Returns the wallet metadata.—MetadataResponse
isConnected()Checks if the network is available.—ConnectResponse
getAccounts()Retrieves all account(s) basic data.—GetAccountsResponse
getPrimaryAccount()Returns the currently selected account in the Wallet.—GetAccountResponse
getActiveNetwork()Returns the currently selected network metadata.—Network
getWalletVersion()Fetches wallet version.—WalletVersion
ledgerAuth(request)Request to get Ledger API access token.LedgerAuthRequestLedgerAuthResponse
ledgerRefresh(request)Refresh Ledger API access token.LedgerRefreshRequestLedgerRefreshResponse
ledgerApi(request)Raw data request to ledger API.LedgerApiRequestLedgerApiResponse
getContracts(request)Fetch active contracts filtered by party and template IDs.ContractsRequestContractsResponse

Signing & Transactions

MethodDescriptionRequest PayloadResponse
signMessage(message)Requests the user to sign a message (hex/base64).SignMessageRequestSignedMessageResponse
encrypt(data)Requests wallet-side encryption with active account keys.EncryptMessageRequestEncryptMessageResponse
decrypt(data)Requests wallet-side decryption with active account keys.DecryptMessageRequestDecryptMessageResponse
submitCommands(data)Signs and broadcasts a transaction to send Canton Coin.SignSendRequestSignSendResponse
signBatch(data)Signs and broadcasts a batch of transactions.SignBatchRequestSignBatchResponse
submitInstructionChoice(data)Request user to interact with pending Transfer Instruction.SignInstructionChoiceRequestSignInstructionChoiceResponse
topUpTraffic(data)Tops up traffic for the sender by spending CC (wallet prepares, signs, and submits).TopUpTrafficRequestTopUpTrafficResponse

Balance & History Queries

MethodDescriptionRequest PayloadResponse
getBalance()Check party balance; includes current Canton Coin price.GetBalanceRequestGetBalanceResponse
getCoinsBalance()Check balances and prices for supported coins.GetBalanceRequestGetCoinsResponse
getCoinsList()Fetch available coins list for a selected network.GetCoinsListRequestGetCoinsListResponse
getTrafficBalance()Check party traffic account balance (bytes; divide by 1024 for KB).GetTrafficBalanceRequestGetTrafficBalanceResponse
convertTraffic()Convert between traffic (KB) and CC using the current traffic price.ConvertTrafficRequestConvertTrafficResponse
getTokenTransfers()Check party token transfers with pagination (indexer).TokenTransfersRequestTokenTransfersResponse
getTransfer()Check party token transfer details (indexer).TransferRequestTransferResponse
getOffers()Check party offers with pagination (indexer).OffersRequestOffersResponse
getNodeTransfers()Check standard coin transfers with pagination (wallet node).CoinTransfersFromNodeRequestCoinTransfersFromNodeResponse
getNodeTransfer()Check single transfer details (wallet node).TransferFromNodeRequestTransferFromNodeResponse
getNodeOffers()Check pending transactions/offers with pagination (wallet node).OffersFromNodeRequestOffersFromNodeResponse

Usage Examples

Sign a Message

Request the user to sign an arbitrary message:

const signMessage = async () => {
  try {
    // Sign a hex-encoded message
    const signature = await consoleWalletPixelplex.signMessage({
      message: { hex: '0x48656c6c6f20576f726c64' }, // "Hello World" in hex
      metaData: {
        purpose: 'authentication',
        timestamp: new Date().toISOString(),
      },
    });
    console.log('Signature:', signature);
  } catch (error) {
    console.error('Signing failed:', error);
  }
};

// Or sign a base64-encoded message
const signBase64Message = async () => {
  try {
    const signature = await consoleWalletPixelplex.signMessage({
      message: { base64: 'SGVsbG8gV29ybGQ=' }, // "Hello World" in base64
    });
    console.log('Signature:', signature);
  } catch (error) {
    console.error('Signing failed:', error);
  }
};

Encrypt / Decrypt Message

Request wallet-side encryption and decryption (same active account context):

import { CryptMechanism } from '@console-wallet/dapp-sdk';

const encryptDecrypt = async () => {
  const message = new TextEncoder().encode('Hello secure world');

  const encrypted = await consoleWalletPixelplex.encrypt({
    cryptMechanism: CryptMechanism.X25519_XSALSA20_POLY1305,
    message,
  });

  if (!encrypted) throw new Error('Encryption failed');

  const decrypted = await consoleWalletPixelplex.decrypt({ encrypted });

  if (!decrypted) throw new Error('Decryption failed');

  console.log(new TextDecoder().decode(decrypted));
};

Send Canton Coin Transaction

Submit a transaction to send Canton Coin:

const sendTransaction = async () => {
  try {
    // Get the active account first
    const activeAccount = await consoleWalletPixelplex.getPrimaryAccount();

    if (!activeAccount) {
      throw new Error('No active account found');
    }

    // Submit the transaction
    const result = await consoleWalletPixelplex.submitCommands({
      from: activeAccount.partyId,
      to: 'receiver::fingerprint',
      token: 'CC', // or 'CBTC', 'USDCx'
      amount: '10.5',
      expireDate: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(), // 24 hours from now
      memo: 'Payment for services', // Optional memo
      waitForFinalization: 5000, // Optional: wait up to 5 seconds for finalization (between 2000-10000 ms)
    });

    if (result?.status) {
      console.log('Transaction submitted successfully');
      if (result.signature) {
        console.log('Transaction signature:', result.signature);
      }
      if (result.confirmationData) {
        console.log('Confirmation data:', result.confirmationData);
      }
    } else {
      console.error('Transaction failed');
    }
  } catch (error) {
    console.error('Error sending transaction:', error);
  }
};

Sign a Batch of Transactions

Sign and send multiple transactions in a batch:

const signBatchTransactions = async () => {
  try {
    const activeAccount = await consoleWalletPixelplex.getPrimaryAccount();

    if (!activeAccount) {
      throw new Error('No active account found');
    }

    const result = await consoleWalletPixelplex.signBatch({
      batchType: 'SEND',
      requests: [
        {
          from: activeAccount.partyId,
          to: 'receiver1::fingerprint',
          token: 'CC',
          amount: '5.0',
          expireDate: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
          type: 'OFFER',
        },
        {
          from: activeAccount.partyId,
          to: 'receiver2::fingerprint',
          token: 'CC',
          amount: '3.5',
          expireDate: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
          type: 'DIRECT_TRANSFER',
        },
      ],
    });

    if (result?.status) {
      console.log('Batch signed successfully');
      if (result.signatures) {
        console.log('Signatures:', result.signatures);
      } else if (result.signature) {
        console.log('Signature:', result.signature);
      }
    }
  } catch (error) {
    console.error('Error signing batch:', error);
  }
};

Get Balance

Check the balance for a party (CC balance only):

const checkBalance = async () => {
  try {
    const activeAccount = await consoleWalletPixelplex.getPrimaryAccount();
    const activeNetwork = await consoleWalletPixelplex.getActiveNetwork();

    if (!activeAccount || !activeNetwork) {
      throw new Error('No active account or network found');
    }

    const balance = await consoleWalletPixelplex.getBalance({
      party: activeAccount.partyId,
      network: activeNetwork.id,
    });

    console.log('CC utxos:', balance.tokens);
    console.log('Is split balance:', balance.isSplitedBalance);
    console.log('1 CC price:', balance.price);
    // Access individual token balances
    balance.tokens.forEach((token) => {
      console.log(`${token.symbol}: ${token.balance} (USD: ${token.balanceUsd || 'N/A'})`);
    });
  } catch (error) {
    console.error('Error getting balance:', error);
  }
};

Get Traffic Balance

Check the traffic account balance for a party (returned in bytes; divide by 1024 for KB):

const checkTrafficBalance = async () => {
  try {
    const activeAccount = await consoleWalletPixelplex.getPrimaryAccount();
    const activeNetwork = await consoleWalletPixelplex.getActiveNetwork();

    if (!activeAccount || !activeNetwork) {
      throw new Error('No active account or network found');
    }

    const traffic = await consoleWalletPixelplex.getTrafficBalance({
      party: activeAccount.partyId,
      network: activeNetwork.id,
    });

    console.log('Traffic balance (bytes):', traffic.balance);
    console.log('Traffic balance (KB):', traffic.balance / 1024);
  } catch (error) {
    console.error('Error getting traffic balance:', error);
  }
};

Convert Traffic

Convert between traffic (KB) and Canton Coin using the current traffic price. Provide exactly one of trafficAmountKB or ccAmount:

const convertTrafficAmount = async () => {
  try {
    const activeNetwork = await consoleWalletPixelplex.getActiveNetwork();

    if (!activeNetwork) {
      throw new Error('No active network found');
    }

    const fromKb = await consoleWalletPixelplex.convertTraffic({
      trafficAmountKB: 1024,
      network: activeNetwork.id,
    });
    console.log('CC for 1024 KB:', fromKb.ccAmount);

    const fromCc = await consoleWalletPixelplex.convertTraffic({
      ccAmount: '1.5',
      network: activeNetwork.id,
    });
    console.log('KB for 1.5 CC:', fromCc.trafficAmountKB);
  } catch (error) {
    console.error('Error converting traffic:', error);
  }
};

Top Up Traffic

Request the wallet to top up traffic for the connected party by spending CC. The wallet prepares, signs, and submits the transfer (network fee is shown in the wallet UI):

const topUpTraffic = async () => {
  try {
    const activeAccount = await consoleWalletPixelplex.getPrimaryAccount();
    const activeNetwork = await consoleWalletPixelplex.getActiveNetwork();

    if (!activeAccount || !activeNetwork) {
      throw new Error('No active account or network found');
    }

    // Optional: convert desired KB into CC first
    const quote = await consoleWalletPixelplex.convertTraffic({
      trafficAmountKB: 20480,
      network: activeNetwork.id,
    });

    const result = await consoleWalletPixelplex.topUpTraffic({
      party: activeAccount.partyId,
      amount: quote.ccAmount,
      network: activeNetwork.id,
    });

    console.log('Top-up status:', result?.status);
    console.log('Submission:', result?.submission);
  } catch (error) {
    console.error('Error topping up traffic:', error);
  }
};

Get Coins Balance with Prices

Get detailed balance information with prices for CC and all CIP-56 tokens:

const getCoinsBalance = async () => {
  try {
    const activeAccount = await consoleWalletPixelplex.getPrimaryAccount();
    const activeNetwork = await consoleWalletPixelplex.getActiveNetwork();

    if (!activeAccount || !activeNetwork) {
      throw new Error('No active account or network found');
    }

    const coinsBalance = await consoleWalletPixelplex.getCoinsBalance({
      party: activeAccount.partyId,
      network: activeNetwork.id,
    });

    console.log('Tokens:', coinsBalance.tokens);
    console.log('Prices:', coinsBalance.prices);
  } catch (error) {
    console.error('Error getting coins balance:', error);
  }
};

Get Coins List by Network

Fetch all available coins for the selected network:

const getCoinsList = async () => {
  try {
    const activeNetwork = await consoleWalletPixelplex.getActiveNetwork();

    if (!activeNetwork) {
      throw new Error('No active network found');
    }

    const coinsList = await consoleWalletPixelplex.getCoinsList({
      network: activeNetwork.id,
    });

    console.log('Available coins:', coinsList.items);
  } catch (error) {
    console.error('Error getting coins list:', error);
  }
};

Get Transaction History

Query transaction history with pagination:

const getTransactionHistory = async () => {
  try {
    const activeAccount = await consoleWalletPixelplex.getPrimaryAccount();

    if (!activeAccount) {
      throw new Error('No active account found');
    }

    // Get token transfers from indexer (only CC)
    const transfers = await consoleWalletPixelplex.getTokenTransfers({
      party: activeAccount.partyId,
      limit: 10,
      cursor: '0',
    });

    console.log('Transfers:', transfers.data);

    // Get token transfers directly from node (separated by token) *Preferred
    const cip56Transfers = await consoleWalletPixelplex.getNodeTransfers({
      query: { partyId: partyId, limit: 10, coin: 'CBTC', offset: 0 },
      network,
    });

    console.log('Transfers', cip56Transfers?.items);

    // Get offers from indexer (Only CC)
    const offers = await consoleWalletPixelplex.getOffers({
      party: activeAccount.partyId,
      limit: 10,
      cursor: '0',
    });

    console.log('Offers:', offers.data);

    // Get offers from node (All tokens) *Preferred
    const nodeOffers = await consoleWalletPixelplex.getNodeOffers({
      query: { party_id: partyId, limit: 10, cursor: '0' },
      network,
    });

    console.log('nodeOffers', nodeOffers?.items);
  } catch (error) {
    console.error('Error getting transaction history:', error);
  }
};

Subscriptions

The SDK provides subscription-style helpers to watch for changes from the Console Wallet. These functions register a callback and invoke it whenever the corresponding state changes.

MethodDescriptionCallback Payload
onAccountsChanged(onChange)Subscribes to active account changesGetAccountResponse
onConnectionStatusChanged(onChange)Subscribes to wallet connection status changesConnectResponse
onTxStatusChanged(onChange)Subscribes to transaction status lifecycle updatesTxChangedEvent
onSessionRestored(options, onChange)Subscribes to the automatic recovery of a previously persisted WC session from IndexedDB on SDK loadSessionRestoredEvent { sessionId, transport }
onSessionDead(options, onChange)Subscribes to any event that makes the current WC session unusable (no stored session, restore error, server dead/closed, reconnect exhausted, user-initiated disconnect, idle timeout)SessionDeadEvent { reason, sessionId?, error? }

Example: Watch Account Changes

// Subscribe to account changes
consoleWalletPixelplex.onAccountsChanged((account) => {
  if (account) {
    console.log('Active account changed:', account.partyId);
    // Update your UI with the new account
  } else {
    console.log('No active account');
  }
});

Example: Watch Connection Status

// Subscribe to connection status changes
consoleWalletPixelplex.onConnectionStatusChanged((status) => {
  console.log('Connection status changed:', status);
  if (status === 'connected') {
    // User connected, enable features
  } else {
    // User disconnected, disable features
  }
});

Example: Watch Transaction Status

// Subscribe to transaction status updates
consoleWalletPixelplex.onTxStatusChanged((event) => {
  console.log('Transaction status update:', event);
  // Handle transaction lifecycle events (pending, confirmed, failed, etc.)
});

Example: Auto-Render Connected State on SDK Load

// When the SDK rehydrates a stored mobile/WC session from IndexedDB,
// render the "connected" UI without waiting for the user to press Connect.
// Pass a stable `id` so re-renders / HMR never double-register the listener.
consoleWalletPixelplex.onSessionRestored(
  { id: 'connected-banner' },
  ({ sessionId, transport }) => {
    console.log('WC session restored:', sessionId, 'via', transport);
    setIsConnected(true);
    setBannerMessage(`Session restored over ${transport}`);
  },
);

Example: Tear Down UI State When Session Dies

// Fire cleanup whenever the session becomes unusable, regardless of cause.
// Known `reason` values: 'no_stored_session' | 'restore_error' | 'expired' |
// 'closed' | 'user_initiated' | 'timeout' | 'server_initiated' |
// 'reconnect_exhausted' | 'unknown'.
consoleWalletPixelplex.onSessionDead(
  { id: 'connected-banner' },
  ({ reason, sessionId, error }) => {
    console.warn('WC session died:', reason, sessionId, error);
    setIsConnected(false);
    clearSessionCaches();
    if (reason === 'reconnect_exhausted') {
      showToast('Network unavailable — session expired. Please reconnect.');
    }
  },
);

Error Handling

All request helpers return Promises and can reject with a ConsoleWalletError when something goes wrong.

The ConsoleWalletError is fully compatible with EIP-1474 error codes, ensuring a standardized error handling experience similar to other blockchain ecosystems.

ConsoleWalletError Interface

type ConsoleWalletError = Error & {
  name: string;
  message: string;
  code: number; // EIP-1474 error code
  data?: unknown;
};

Common Error Codes

CodeNameDescription
4001UserRejectedUser rejected the request.
4100UnauthorizedUnauthorized.
4200UnsupportedMethodUnsupported method.
4900DisconnectedDisconnected from the wallet.
4901ChainDisconnectedDisconnected from the chain.
-32700ParseErrorParse error.
-32600InvalidRequestInvalid request.
-32601MethodNotFoundMethod not found.
-32602InvalidParamsInvalid params.
-32603InternalErrorInternal error.
-32000InvalidInputInvalid input.
-32001ResourceNotFoundResource not found.
-32002ResourceUnavailableResource unavailable.
-32003TransactionRejectedTransaction rejected.
-32004MethodNotSupportedMethod not supported.
-32005LimitExceededLimit exceeded.
  • User-driven errors (rejection, invalid input, permission issues) are reported by the wallet and surfaced as rejected Promises with a ConsoleWalletError payload.
  • Transport-level issues (extension not installed, no response within the timeout) are also represented as ConsoleWalletError rejections where applicable (for example, account and network queries).
  • Some helpers, such as checkAvailability(), internally handle timeouts and resolve with a best-effort status instead of rejecting.

You should always wrap calls in try/catch and handle both expected and unexpected errors:

try {
  const accounts = await consoleWalletPixelplex.getAccounts();
  // happy path
} catch (error) {
  const err = error as ConsoleWalletError;
  if (err.code === 4001) {
    console.log('User rejected the request');
  } else {
    console.error('An error occurred:', err.message);
  }
}

Transaction Metadata

When submitting transactions, you can include optional metadata:

const transactionWithMetadata = await consoleWalletPixelplex.submitCommands({
  from: activeAccount.partyId,
  to: 'receiver::fingerprint',
  token: 'CC',
  amount: '10.0',
  expireDate: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
  memo: 'Payment for services', // Optional memo stored as transfer metadata
});

The memo field allows you to attach additional information to the transaction, which is stored as transfer metadata and can be retrieved when querying transaction history.

Transaction Costs

All transactions on Canton are free. There are no transaction fees, traffic consumption costs, or native token costs for transaction processing.

How It Works

The Console DApp SDK provides a communication layer between your Web3 application and the Console Wallet Extension using the browser's native window.postMessage API.

It handles all low-level messaging logic automatically, so you can focus on building your DApp — not managing communication details.

  1. When your DApp sends a request (e.g., connect(), signMessage(), or submitCommands()), the SDK transmits a structured message to the Console Wallet Extension via window.postMessage.

  2. Each outgoing request is assigned a unique request ID, which is included in both the request and the extension's response.

  3. The SDK listens for incoming responses from the extension, matches them to their original request using the ID, and automatically resolves the corresponding Promise in your application.

This approach ensures reliable, asynchronous communication between the DApp and the extension — preventing race conditions, mismatched responses, or orphaned message handlers.

API Reference

For detailed API reference, see the TypeScript type definitions in src/types/. All methods are fully typed and include JSDoc comments.

Type Exports

The SDK exports all relevant types:

import type {
  ConnectRequest,
  ConnectResponse,
  GetAccountResponse,
  SignMessageRequest,
  SignedMessageResponse,
  SignSendRequest,
  SignSendResponse,
  SignBatchRequest,
  SignBatchResponse,
  GetBalanceRequest,
  GetBalanceResponse,
  GetTrafficBalanceRequest,
  GetTrafficBalanceResponse,
  ConvertTrafficRequest,
  ConvertTrafficResponse,
  TopUpTrafficRequest,
  TopUpTrafficResponse,
  // ... and more
} from '@console-wallet/dapp-sdk';

Utility Functions

The SDK provides utility functions for correct data format conversion required for working with the network and extension:

import { utils } from '@console-wallet/dapp-sdk';

// Parsers for format conversion
utils.toHex(u8: Uint8Array): string
utils.toBase64(u8: Uint8Array): string
utils.hexToBytes(hex: string): Uint8Array
utils.hexToBase64(hex: string): string
utils.base64ToBytes(base64: string): Uint8Array
utils.base64toHex(base64: string): string

// Checks
utils.equalBytes(a: Uint8Array, b: Uint8Array): boolean

These utilities are essential for converting data between different formats (hex, base64, bytes) that the network and extension expect.

Changelog

See CHANGELOG.md for a list of changes and version history.

版本与发布记录

@console-wallet/dapp-sdk 共发布 48 个版本,首次发布于 2025/10/28;过去 12 个月发布了 46 个版本。

版本发布日期距今
3.0.0latest2026/10/091 个月前
3.0.0-beta-4beta2026/10/081 个月前
3.0.0-beta-32026/10/021 个月前
3.0.0-beta-22026/09/301 个月前
3.0.0-beta-12026/09/281 个月前
2.4.02026/09/221 个月前

关于 @console-wallet/dapp-sdk 的常见问题

@console-wallet/dapp-sdk 是什么?

Console DApp SDK allows dApps to connect to a Console Wallet account. The Console wallet is a browser extension. All interaction happens inside the dApp. For signing, users will be prompted to sign in their Console Wallet browser extension.

如何安装 @console-wallet/dapp-sdk?

在项目目录运行 npm install @console-wallet/dapp-sdk,或使用 pnpm add / yarn add / bun add。

@console-wallet/dapp-sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@console-wallet/dapp-sdk 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@console-wallet/dapp-sdk 可以商用吗?

@console-wallet/dapp-sdk 使用 ISC 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@console-wallet/dapp-sdk 的下载量有多少?

根据 npm 官方下载统计,@console-wallet/dapp-sdk 在 2026/10/11 – 2026/11/09 这 30 天内被下载 3,323 次,日均约 111 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@console-wallet/dapp-sdk 还在维护吗?

最新版本 3.0.0 发布于 2026/10/09(1 个月前);至今共发布 48 个版本,其中过去 12 个月发布了 46 个;首次发布于 2025/10/28。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。