Skip to content

Adapter API Reference

Adapter

The Adapter class defines the common interface for all adapters of specified wallets.

Constructor

  • constructor(config): adapter constructor method, an optional config is valid. For detailed config type, refer to the following adapter section.

Properties

PropertyDescription
readyStateThe wallet's state in type of WalletReadyState shown as below.
nameThe name of the adapter.
urlThe website of the adapter's wallet.
iconThe icon of the adapter's wallet.
addressThe address of current account when the adapter is connected.
connectingWhether the adapter is trying to connect to the wallet.
connectedWhether the adapter is connected to the wallet.

Methods

Here is the selected markdown text converted into a table format:

MethodDescription
connect(): Promise<void>Connect to the wallet.
disconnect(): Promise<void>Disconnect from the wallet.
signMessage(message): Promise<string>Sign a string, return the signature result. An optional privateKey can be provided.
signTransaction(transaction: Transaction): Promise<SignedTransaction>Sign a transaction, return the signature result of the transaction.
multiSign(transaction: Transaction, privateKey: null, permissionId?: number): Promise<SignedTransaction>Sign a multi-sign transaction.
If permissionId is not provided, will use 0(OwnerPerssion) as default.
Please refer to here for more about Multi-Sign.
switchChain(chainId: string): Promise<void>;Request wallet to switch chain by chainId.

Events

Adapter extends the EventEmitter class in eventemitter3 package. So you can listen to the events by adapter.on('connect', function() {}).

Here is the selected markdown text converted into a table format:

EventDescription
readyStateChanged(state: WalletReadyState)Emit when the wallet's readyState is changed. The parameter is of type WalletReadyState.
connect(address: string)Emit when adapter is connected to the wallet. The parameter is the address of the current account.
disconnect()Emit when adapter is disconnected from the wallet.
accountsChanged(addr: string, preAddr?: string)Emit when users change the currently selected account in the wallet. The parameter is the address of the new account.
chainChanged(chainInfo: ChainInfo)Emit when users change the currently selected chain in the wallet. The parameter is the new network configuration.
error(error: WalletError)Emit when there are errors while calling the adapter's methods. The WalletError types are defined as follows.

Types definitions

ts
enum WalletReadyState {
  /**
   * Adapter will start to check if wallet exists after adapter instance is created.
   */
  Loading = 'Loading',
  /**
   * When checking ends and wallet is not found, readyState will be NotFound.
   */
  NotFound = 'NotFound',
  /**
   * When checking ends and wallet is found, readyState will be Found.
   */
  Found = 'Found',
}
interface ChainInfo {
  chainId: string;
}

WalletError

WalletError is a superclass which defines the error when using adapter. All error types are extended from this class. Developers can check the error type according to the error instance.

typescript
try {
  // do something here
} catch (error: WalletError) {
  if (error instanceof WalletNotFoundError) {
    console.log('Wallet is not found');
  }
}

All errors are as follows:

Error TypeDescription
WalletNotFoundErrorOccurs when wallet is not installed.
WalletNotSelectedErrorOccurs when connect but there is no selected wallet.
WalletDisconnectedErrorOccurs when wallet is disconnected. Used by some wallets which won't connect automatically when call signMessage() or signTransaction().
WalletConnectionErrorOccurs when try to connect a wallet.
WalletDisconnectionErrorOccurs when try to disconnect a wallet.
WalletSignMessageErrorOccurs when call signMessage().
WalletSignTransactionErrorOccurs when call signTransaction().

Following exmaple shows how to get original error information with WalletError:

js
const adapter = new TronLinkAdapter();
try {
    await adapter.connect();
} catch (e: any) {
    const originalError = e.error;
}

Constructor parameters

TronLinkAdapter

  • Constructor(config: TronLinkAdapterConfig)

    typescript
    interface TronLinkAdapterConfig {
      /**
       * Set if open Wallet's website url when wallet is not installed.
       * Default is true.
       */
      openUrlWhenWalletNotFound?: boolean;
      /**
       * Timeout in millisecond for checking if TronLink wallet exists.
       * Default is 30 * 1000ms
       */
      checkTimeout?: number;
      /**
       * Set if open TronLink app using DeepLink on mobile device.
       * Default is true.
       */
      openTronLinkAppOnMobile?: boolean;
      /**
       * The icon of your dapp. Used when open TronLink app in mobile device browsers.
       * Default is current website icon.
       */
      dappIcon?: string;
      /**
       * The name of your dapp. Used when open TronLink app in mobile device browsers.
       * Default is `document.title`.
       */
      dappName?: string;
      /**
       * Optional security check config. Available on every adapter.
       * @see Security Check section below
       */
      securityOptions?: SecurityOptions;
    }
  • network() method is supported to get current network information. The type of returned value is Network as follows:

    typescript
    export enum NetworkType {
      Mainnet = 'Mainnet',
      Shasta = 'Shasta',
      Nile = 'Nile',
      /**
       * When use custom node
       */
      Unknown = 'Unknown',
    }
    
    export type Network = {
      networkType: NetworkType;
      chainId: string;
      fullNode: string;
      solidityNode: string;
      eventServer: string;
    };
  • TronLink doesn't support disconnect by dApp. As TronLinkAdapter doesn't support disconnect by dApp website, call adapter.disconnect() won't disconnect from TronLink extension really.

  • Auto open TronLink app in mobile browser. If developers call connect() method in mobile browser, it will open dApp in TronLink app.

Other adapters

Other adapters Constructor config api can be found in their source code README.

Security Check

Every adapter accepts an optional securityOptions in its constructor config. When enabled, the adapter fetches a remote risk list on connect() and calls onRiskDetected if the connecting wallet has configured risk entries. It is disabled by default. See the Security Check guide for usage and examples.

ts
interface SecurityOptions {
  /** Enable the security check. Default: false. */
  enabled?: boolean;
  /** Remote risk-list JSON URL(s). Required when `enabled` is true. */
  configUrls?: string[];
  /** Called when the connecting wallet has risks. Throw to block the connection. */
  onRiskDetected?: (result: SecurityCheckResult) => Promise<void>;
  /** Per-request timeout in ms. Default: 2000. */
  timeout?: number;
  /** Extra attempts per URL on failure. Default: 0. */
  retries?: number;
  /** Fallback config when all URLs fail and nothing is cached. */
  onConfigFallback?: () => RiskConfig | Promise<RiskConfig>;
  /** Cache duration per URL in ms. Default: 600000 (10 min). */
  cacheTTL?: number;
}

interface SecurityCheckResult {
  risks: Risk[];
}

interface Risk {
  /** Message shown to the user. */
  title: string;
  /** Notice level your dApp maps to its own styling. */
  noticeType: 1 | 2 | 3;
  /** Browser-extension version(s) affected by this risk entry. */
  ext?: string;
  /** iOS app version(s) affected by this risk entry. */
  ios?: string;
  /** Android app version(s) affected by this risk entry. */
  and?: string;
}

interface RiskConfig {
  v: string;
  ts: number;
  wallets: { [walletName: string]: Risk[] };
}

The configuration can also be changed at runtime with adapter.updateSecurityOptions(securityOptions).