WDK logoWDK documentation
StartWalletsDeFi & FiatAI & CLITools

WDK Core API Reference

Complete API documentation for @tetherto/wdk

This reference documents @tetherto/wdk@1.0.0-beta.23. The base-wallet contracts identify their separate package versions. For the standalone policy API and migration, see Transaction Policies.

Table of Contents

ClassDescriptionMethods
WDKMain class for managing wallets across multiple blockchains. Orchestrates wallet managers, protocols, and middleware.Constructor, Methods
Base wallet signer contractsSigner capabilities, account configuration, ownership and disposal contracts.Interfaces and migration notes
IWalletAccountBase single-signer writable wallet account interface from @tetherto/wdk-wallet.Methods
Multisig account contractsImplementation contracts exported from @tetherto/wdk-wallet/multisig.Interfaces and types
IWalletAccountWithProtocolsProtocol registration and access surface added to a wallet account.Methods
WdkAccountConsumer-facing account type returned by getAccount() and getAccountByPath().Type alias

WDK

The main class for managing wallets across multiple blockchains. This class serves as an orchestrator that allows you to register different wallet managers and protocols, providing a unified interface for multi-chain operations.

Constructor

Constructor
new WDK(seed)

Parameters:

  • seed (string | Uint8Array): BIP-39 mnemonic seed phrase or seed bytes

For base WalletManager implementations, @tetherto/wdk-wallet@1.0.0-beta.20 clarifies that byte input is a raw BIP-32 master seed of 16–64 bytes. It need not have been generated from a BIP-39 mnemonic. This is a declaration clarification, not a new derivation algorithm; check each concrete wallet's seed and derivation requirements.

Throws: Error if the seed is invalid.

Example:

Initialize WDK
import WDK from '@tetherto/wdk'

// With seed phrase
const wdk = new WDK('abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about')

// With seed bytes
const seedBytes = new Uint8Array([...])
const wdk2 = new WDK(seedBytes)

Methods

MethodDescriptionReturnsThrows
registerWallet(blockchain, wallet, config)Registers a new wallet manager for a blockchainWDKIf a wallet is already registered for that blockchain
registerProtocol(blockchain, label, protocol, ...config)Registers a protocol globally for a blockchainWDK-
registerMiddleware(blockchain, middleware)Registers middleware for account decorationWDK-
getAccount(blockchain, index?)Returns a wallet account for a blockchain and indexPromise<WdkAccount>If wallet not registered
getAccountByPath(blockchain, path)Returns a wallet account for a blockchain and derivation pathPromise<WdkAccount>If wallet not registered
getFeeRates(blockchain)Returns current fee rates for a registered blockchainPromise<FeeRates>If wallet not registered
dispose(blockchains?)Calls cleanup on selected wallets and unregisters themvoidErrors from wallet cleanup

registerWallet(blockchain, wallet, config)

Registers a new wallet manager for a specific blockchain.

Type Parameters:

  • W: typeof WalletManager - A class that extends the @tetherto/wdk-wallet's WalletManager class

Parameters:

  • blockchain (string): The name of the blockchain (e.g., "ethereum", "ton", "bitcoin")
  • wallet (W): The wallet manager class
  • config (ConstructorParameters<W>[1]): The configuration object for the wallet

Returns: WDK - The WDK instance (supports method chaining)

Throws: Error if a wallet is already registered for the same blockchain. Call dispose([blockchain]) before registering a replacement wallet for that blockchain.

Example:

Register Wallets
import WDK from '@tetherto/wdk'
import WalletManagerEvm from '@tetherto/wdk-wallet-evm'
import WalletManagerTon from '@tetherto/wdk-wallet-ton'

const wdk = new WDK(seedPhrase)

// Register EVM wallet
wdk.registerWallet('ethereum', WalletManagerEvm, {
  provider: 'https://eth.drpc.org'
})

// Register TON wallet
wdk.registerWallet('ton', WalletManagerTon, {
  tonApiKey: 'YOUR_TON_API_KEY',
  tonApiEndpoint: 'https://tonapi.io'
})

// Method chaining
const wdk2 = new WDK(seedPhrase)
  .registerWallet('ethereum', WalletManagerEvm, ethereumWalletConfig)
  .registerWallet('ton', WalletManagerTon, tonWalletConfig)

registerProtocol(blockchain, label, protocol, ...config)

Registers a protocol globally for all accounts of a specific blockchain.

For swidge or Smart Deposit Address (SDA) integrations, pass a concrete provider class that extends the corresponding base class from @tetherto/wdk-wallet/protocols.

Type Parameters:

  • A extends any[]: The tuple of constructor arguments after the account, inferred from ProtocolConstructor<A>

Parameters:

  • blockchain (string): The name of the blockchain
  • label (string): Registry label for the protocol. Registering the same blockchain, protocol type, and label again replaces the previous global registration.
  • protocol (ProtocolConstructor<A>): A class extending a supported @tetherto/wdk-wallet/protocols base class
  • ...config (NoInfer<A>): The remaining constructor arguments, passed in order after the account

Returns: WDK - The WDK instance (supports method chaining)

Global registration stores the provider class and config without constructing or validating the provider. Provider-constructor errors therefore surface when an account retrieves the protocol. A global registration takes precedence over an account-scoped registration with the same type and label.

Starting in Core beta.19, registration accepts zero, one, or multiple constructor arguments after the protocol class, as required by that class. A provider taking one configuration object keeps the same call shape. Pass multiple arguments separately; an array passed as one argument is not spread automatically. See ProtocolConstructor<A>.

The documented Velora, USD₮0 bridge, and Aave adapters require EIP-1193 request() on non-string provider inputs. An account whose manager supplies a shared ethers provider without request() cannot initialize these adapters. Use the corresponding direct account constructor with its original RPC URL or genuine EIP-1193 input; never mutate internal provider fields. Direct accounts do not receive WDK Core middleware or attached policies, so retain required application checks and account-level controls.

Example:

Register Protocols
// Register an illustrative swap provider for Ethereum
wdk.registerProtocol('ethereum', 'swap', MySwapProtocol, swapProtocolConfig)

// Register a concrete swidge provider for Ethereum
wdk.registerProtocol('ethereum', 'swidge', MySwidgeProtocol, swidgeProtocolConfig)

// Register an illustrative SDA provider for Ethereum
wdk.registerProtocol('ethereum', 'deposits', MySdaProtocol, sdaProtocolConfig)

// Method chaining
const wdk2 = new WDK(seedPhrase)
  .registerWallet('ethereum', WalletManagerEvm, ethereumWalletConfig)
  .registerProtocol('ethereum', 'swap', MySwapProtocol, swapProtocolConfig)

MySwapProtocol is an illustrative class that extends SwapProtocol; use a concrete provider whose constructor supports the account and provider shape supplied by your wallet.

registerMiddleware(blockchain, middleware)

Registers middleware for a wallet identifier. After attaching protocol methods, WDK runs the callbacks in registration order on every retrieval. A callback can update the account in place and return nothing, or return an account or wrapper for the next callback and the caller.

Parameters:

  • blockchain (string): The wallet identifier passed to registerWallet().
  • middleware (MiddlewareFunction): Receives the current account and MiddlewareContext. Core uses any non-nullish return as the replacement.

Returns: WDK for chaining.

Example:

Register Middleware
wdk.registerMiddleware('ethereum', async (account, context) => {
  console.log('Accessed account:', context.blockchain, context.index)
  await recordAccountAccess(account)
})

Here recordAccountAccess() is an app callback. The middleware returns nothing so the account is preserved. See Configure Middleware for callback order and policy attachment.

getAccount(blockchain, index?)

Returns a wallet account for a specific blockchain and index using BIP-44 derivation.

Parameters:

  • blockchain (string): The name of the blockchain (e.g., "ethereum")
  • index (number, optional): The index of the account to get (default: 0)

Returns: Promise<WdkAccount> - The account with protocol methods, or the last replacement supplied by middleware.

Throws: Error if no wallet has been registered for the identifier. Errors from the wallet or middleware propagate to the caller.

Example:

Get Account
// Get first account (index 0)
const account = await wdk.getAccount('ethereum', 0)

// Get second account (index 1)
const account1 = await wdk.getAccount('ethereum', 1)

// Default index (0)
const defaultAccount = await wdk.getAccount('ethereum')

// This will throw an error if no wallet registered for 'tron'
try {
  const tronAccount = await wdk.getAccount('tron', 0)
} catch (error) {
  console.error('No wallet registered for tron blockchain')
}

getAccountByPath(blockchain, path)

Returns a wallet account for a specific blockchain and BIP-44 derivation path.

Parameters:

  • blockchain (string): The name of the blockchain (e.g., "ethereum")
  • path (string): The derivation path (e.g., "0'/0/0")

Returns: Promise<WdkAccount> - The account with protocol methods, or the last replacement supplied by middleware.

Throws: Error if no wallet has been registered for the identifier. Errors from the wallet or middleware propagate to the caller.

Example:

Get Account by Path
// Full path: m/44'/60'/0'/0/1
const account = await wdk.getAccountByPath('ethereum', "0'/0/1")

// Different derivation path
const customAccount = await wdk.getAccountByPath('ton', "1'/2/3")

getFeeRates(blockchain)

Returns current fee rates for a registered blockchain.

Parameters:

  • blockchain (string): The blockchain identifier passed to registerWallet()

Returns: Promise<FeeRates> - The fee rates in base units

Throws: Error if no wallet has been registered for the given blockchain.

Example:

Get Fee Rates
const feeRates = await wdk.getFeeRates('ethereum')
console.log('Fee rates:', feeRates)

dispose(blockchains?)

Disposes all registered wallets when called without arguments, or only the wallets for the named blockchains when you pass a string array.

For each selected wallet, WDK calls the manager's dispose() and unregisters the wallet. A later account lookup fails until a wallet is registered again. If manager cleanup throws, the error propagates before that wallet is unregistered. Dispose attached policies separately.

Signer cleanup follows the installed concrete wallet's ownership behavior; the base contract alone does not establish which supplied signers survive disposal. WDK itself does not overwrite the seed passed to new WDK(seed). See disposal and signer ownership and Seed Lifecycle before sharing signer or seed references.

Parameters:

  • blockchains (string[], optional): The blockchain identifiers to dispose. Omit this parameter to dispose every registered wallet.

Example:

Dispose WDK
// Dispose all registered wallets
wdk.dispose()

// Dispose only one registered wallet
wdk.dispose(['ethereum'])

Static Methods

MethodDescriptionReturns
getRandomSeedPhrase(wordCount?)Returns a random BIP-39 seed phrase (12 or 24 words)string
isValidSeed(seed)Checks if a seed phrase or seed bytes value is validboolean

getRandomSeedPhrase(wordCount?)

Returns a random BIP-39 seed phrase. Supports both 12-word (128-bit entropy) and 24-word (256-bit entropy) seed phrases.

Parameters:

  • wordCount (12 | 24, optional): The number of words in the seed phrase. Defaults to 12.

Returns: string - The seed phrase

Example:

Generate Random Seed
// Generate 12-word seed phrase (default)
const seedPhrase12 = WDK.getRandomSeedPhrase()
await presentSeedPhraseForSecureBackup(seedPhrase12)

// Generate 24-word seed phrase (higher security)
const seedPhrase24 = WDK.getRandomSeedPhrase(24)
await presentSeedPhraseForSecureBackup(seedPhrase24)

presentSeedPhraseForSecureBackup() represents an application-owned, non-logging backup flow. Never send a generated seed phrase to console output, telemetry, crash reports, or a remote service.

isValidSeed(seed)

Checks if a seed phrase or seed bytes value is valid.

Parameters:

  • seed (string | Uint8Array): The seed phrase or seed bytes to validate

Returns: boolean - True if the seed is valid

Example:

Validate Seed
const isValid = WDK.isValidSeed('abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about')
console.log('Seed phrase valid:', isValid) // true

const isInvalid = WDK.isValidSeed('invalid seed phrase')
console.log('Seed phrase valid:', isInvalid) // false

Base Wallet Signer Contracts

These contracts cover @tetherto/wdk-wallet@1.0.0-beta.26, with the release-specific changes identified below. They describe the base package used by module authors; a concrete wallet must implement the relevant support before applications can use it. Updating a direct base-wallet dependency does not upgrade the separate copy pinned by another wallet package.

The concrete wallet versions below use separate base-package versions. Installing base wallet directly does not add its config getter to a wallet pinned to an older base package. Disposal checks also depend on the concrete module's implementation.

Base-wallet dependencyConcrete wallet versions
1.0.0-beta.17Bitcoin beta.18, Aptos beta.7, TON beta.20, TON Gasless beta.17, TRON GasFree beta.13
1.0.0-beta.19Solana Gasless beta.8, Safe beta.3, Squads beta.5
1.0.0-beta.25EVM beta.26, ERC-4337 beta.26, EIP-7702 beta.13, Spark beta.32, Solana beta.21
1.0.0-beta.26TRON beta.18

When Core beta.23 resolves base wallet beta.26 and EVM beta.26 resolves beta.25, the TypeScript declarations can reject registerWallet() with TS2345 because the base classes declare separate private _seed fields. JavaScript construction and registration work with this package set.

Module authors can declare @tetherto/wdk-wallet@1.0.0-beta.26 directly for the base contracts below. Applications using a concrete wallet should use its documented dependencies.

Import Base Wallet Contracts
import WalletManager, { DisposalError, IDisposable, ISigner } from '@tetherto/wdk-wallet'

IDisposable, introduced in beta.21, declares dispose(): void. Beta.22 adds a read-only disposed: boolean getter. Both base members throw NotImplementedError; implementations provide their own state and cleanup. ISigner extends this contract and requires these capabilities in addition to derive(path) and getAddress():

MemberContract
disposedboolean indicating whether the implementation has been disposed. Added to IDisposable in beta.22.
isDerivableboolean indicating whether the signer supports child derivation.
keyPairKeyPair | null; null when key material cannot be retrieved, for example from a hardware signer.
pathstring | null; null when the signer is not bound to a derivation position.
sign(message)Signs a string message and returns Promise<string>.

The base WalletManager constructor rejects a default signer whose isDerivable is false with InvalidSignerError. Register non-derivable signers by name with addSigner(name, signer) in a supporting concrete wallet. WalletManager<TSigner> preserves the signer type through getSigner() and getSigners(), and addSigner() returns this for chaining.

Account Configuration

The exported abstract WalletAccountReadOnly base class exposes the configuration supplied by a module implementation:

MemberContract
constructor(address?, config?)Accepts address?: string and config?: Record<string, unknown>. Omitted configuration defaults to an empty object.
configGetter returning Readonly<Record<string, unknown>>.

Subclass constructors can pass their configuration with super(address, config). The getter returns the supplied object without cloning or freezing it; treat the returned value as read-only.

Module implementations of IWalletAccountReadOnly must expose a read-only config property. The writable IWalletAccount TypeScript interface inherits that requirement; the multisig interfaces do not. When upgrading an implementation that provides its own read-only methods rather than extending WalletAccountReadOnly, add a compatible property or getter.

Disposal And Signer Ownership

Distinguish signers created by a wallet from signers supplied by your app. A manager can create a default signer from a seed and derive child signers for its accounts; a signer passed to a constructor or registered with addSigner() is application-owned. Concrete managers and accounts implement that ownership boundary. The base interface does not guarantee that a particular wallet release preserves supplied signers when disposed.

Before sharing a signer, check the concrete wallet's version and cleanup options. Arrange cleanup of application-owned signers after their final use, accounting for whether the wallet already disposes them, and keep any seed buffer alive until every wallet that retains it has finished. Do not treat disposal as proof that every secret copy or hardware session has been cleared.

Disposal In Base Wallet Beta.21

The base manager's dispose() calls dispose() on cached accounts only when account.keyPair?.privateKey is present, then clears its account cache. It no longer directly disposes or removes its default or named signers. Concrete managers must provide any additional cleanup for a default signer they create; account implementations determine how derived or supplied signers are handled.

When constructed from a mnemonic or raw seed bytes, the base manager retains seed bytes; with raw Uint8Array input, it retains that same buffer. A signer-based manager can consume the seed into a default signer before calling the base constructor, in which case wallet.seed is undefined. Do not use this getter as seed storage or recovery: store the seed securely in your application and follow seed lifecycle.

Disposal State In Base Wallet Beta.22

WalletManager.disposed starts as false. After the base dispose() completes, it becomes true; subsequent calls return immediately. This state describes the base manager. Its cached-account cleanup is unchanged from beta.21; concrete managers and accounts remain responsible for their signer ownership behavior. A true value does not prove that caller-owned secrets or external signer resources were cleared.

Beta.22 exports DisposalError from both @tetherto/wdk-wallet and @tetherto/wdk-wallet/protocols. It extends WdkError and identifies operations rejected because an object has been disposed. The signer, account, and protocol contracts describe disposal failures; concrete implementations supply the checks.

Signer Registration After Disposal In Base Wallet Beta.23

The base manager's addSigner(name, signer) now throws DisposalError when disposed is true, before validating the name or storing the signer. Create a fresh manager instead of registering another signer on a disposed one. This check applies to the base implementation; verify which base version a concrete wallet uses and whether it overrides the method.

IWalletAccount

Base single-signer writable wallet account interface exposed by @tetherto/wdk-wallet. Blockchain modules implement this interface and may narrow the transaction type accepted by signTransaction() and sendTransaction().

In base wallet beta.21, path is string | null and keyPair is KeyPair | null. The base interface no longer requires index, and its TypeScript contract extends IDisposable. A concrete wallet can still expose an index or non-null key material; code written against the base interface must handle null values and cannot assume an index exists.

Beta.22 adds disposed: boolean through that TypeScript contract. Its runtime IWalletAccount base class no longer inherits from IWalletAccountReadOnly, while the published TypeScript interface retains its read-only and disposable inheritance. Implementations must provide the declared read and write methods.

Methods

The Throws column summarizes the base interface contract; each concrete module implements its own checks. DisposalError is available from base wallet beta.22. Concrete modules pinned to earlier base releases do not gain these checks from a direct base-wallet upgrade.

MethodDescriptionReturnsThrows
getAddress()Returns the account addressPromise<string>-
sign(message)Signs a message using the account's signing implementationPromise<string>DisposalError
signTransaction(tx)Signs a transaction without broadcasting itPromise<unknown>DisposalError or an invalid-transaction error
verify(message, signature)Verifies a message signaturePromise<boolean>-
getTransaction(hash)Returns a normalized transaction receiptPromise<TransactionReceipt>ValueError, NoSuchElementError, ProviderRequiredError, or ProviderError
waitForTransaction(hash, options?)Polls until the requested finality or a stable dropped statePromise<TransactionReceipt>Transaction lookup errors or TimeoutError
sendTransaction(tx)Signs, broadcasts, and returns the transaction resultPromise<TransactionResult>DisposalError, provider, broadcast, or fee errors
transfer(options)Transfers a token where supported by the modulePromise<TransferResult>DisposalError or a token-transfer error
toReadOnlyAccount()Returns a read-only account copyPromise<IWalletAccountReadOnly>-
dispose()Initiates the account cleanup processvoid-
signTransaction(tx)

Signs a transaction and returns the signed transaction payload without broadcasting it. Use this when your app needs offline signing, external transaction submission, or a separate review step before broadcast.

Parameters:

  • tx (Transaction): Module-specific transaction object. For example, EVM accounts accept EvmTransaction, and Bitcoin accounts accept BtcTransaction.

Returns: Promise<unknown> - The signed transaction payload. Wallet modules may narrow this return type, such as a hex string for EVM and Bitcoin transactions.

Example:

Sign Without Broadcasting
const account = await wdk.getAccount('ethereum', 0)

const signedTransaction = await account.signTransaction({
  to: '0x71C7656EC7ab88b098defB751B7401B5f6d8976F',
  value: 1000000000000000n
})

Treat signedTransaction as a sensitive, potentially broadcastable authorization payload. Do not log it; pass it only to the reviewed storage, transport, or submission path that needs it.

getTransaction(hash)

Returns one normalized lookup for a transaction. The common receipt includes hash, finality, and optional success, block, and fee fields; a concrete wallet module can add chain-native fields.

Parameters:

  • hash (string): The chain-specific transaction identifier, such as a hash, signature, or lt:hash value.

Returns: Promise<TransactionReceipt> - The current normalized receipt.

Throws: NoSuchElementError when the transaction has not been found. Invalid identifiers and provider failures use the corresponding base-wallet error classes.

getTransactionReceipt() is marked deprecated in the base package. Current first-party Bitcoin, standard EVM, ERC-4337, EIP-7702, Solana, Solana Gasless, Spark, TON, TON Gasless, TRON, TRON Gasfree, and Aptos wallet releases implement getTransaction() and inherit waitForTransaction(). Use the concrete module's extended TransactionReceipt when you also need chain-native receipt fields.

The base class still throws NotImplementedError when a third-party or older wallet module does not override getTransaction(). Confirm support in the concrete module before relying on normalized transaction tracking.

waitForTransaction(hash, options?)

Calls getTransaction() until the receipt reaches the requested confirmed or final target, is reported as dropped on two consecutive polls, or times out. It returns reverted receipts too; inspect success instead of treating resolution as proof of successful execution.

Parameters:

  • hash (string): The transaction identifier.
  • options (WaitForTransactionOptions, optional): Polling and finality settings.
OptionDefaultDescription
target'confirmed'Finality level to wait for: 'confirmed' or 'final'
timeoutModule defaultPolling deadline checked between completed polls; the base account default is 60000 milliseconds
intervalModule defaultPoll cadence in milliseconds; the base account default is 4000
maxPollErrors3Consecutive ProviderError results tolerated before the next one is rethrown

Returns: Promise<TransactionReceipt> - A receipt at the target finality, or a stable dropped receipt.

Throws: TimeoutError when the polling loop regains control and observes that the deadline has elapsed. NoSuchElementError is treated as a transient not-found while polling; other non-provider errors are rethrown immediately.

timeout is not a hard wall-clock bound and does not cancel getTransaction(). The helper awaits each provider lookup, does not shorten the final sleep to the remaining time, and checks a returned target receipt before checking the deadline again. A slow or hung lookup can therefore exceed the configured timeout, and a target receipt can resolve after it. Configure provider-level request timeouts or cancellation separately.

Wait For Confirmation
// `account` must come from a concrete module that implements getTransaction().
const receipt = await account.waitForTransaction(transactionHash, {
  target: 'confirmed',
  timeout: 120000
})

if (receipt.finality === 'dropped') {
  console.error('Transaction dropped')
} else if (receipt.success === false) {
  console.error('Transaction reverted')
}

Base Wallet Error Exports

The root @tetherto/wdk-wallet entrypoint exports WdkError and these specialized subclasses: AssertionError, InvalidSignerError, InvalidTokenError, MaximumFeeExceededError, NoSuchElementError, NotImplementedError, ProviderError, ProviderRequiredError, TimeoutError, TransactionError, TransferError, UnsupportedOperationError, and ValueError. It also exports SignerError as an alias of InvalidSignerError; both names refer to the same constructor.

ProviderError, TransactionError, and TransferError expose a reason field. Compare it with ProviderErrorReason, TransactionErrorReason, or TransferErrorReason rather than parsing the message. See Error Handling for the reason values and migration notes.

These exports do not retroactively normalize errors in a concrete wallet package built against an older base version. Check that package's release and documented error behavior before relying on instanceof WdkError.

Multisig Account Contracts

@tetherto/wdk-wallet/multisig exports contracts for chain-specific multisig wallet implementations. The package does not include a concrete multisig account or add these methods to WdkAccount. The Transaction and TransactionResult types remain type exports of the root @tetherto/wdk-wallet package.

For concrete implementations, use Multisig (Safe) on EVM or Multisig (Squads) on Solana. Their supported operations, fees, coordination, and execution status differ; follow the implementation's guide before proposing or approving a transaction.

Import Multisig Contracts
import {
  IWalletAccountReadOnlyMultisig,
  IWalletAccountMultisig,
  IMultisigOwnerManagement,
  IMultisigMessageSigningReadOnly,
  IMultisigMessageSigning
} from '@tetherto/wdk-wallet/multisig'

These runtime exports are interface base classes. Their methods throw NotImplementedError until a wallet module overrides them.

IWalletAccountReadOnlyMultisig

The read-only contract shares the base address, signature-verification, balance, token-balance, and transaction-tracking methods, then adds multisig state and transaction-proposal reads:

Read-only Multisig Contract
interface IWalletAccountReadOnlyMultisig {
  getMultisigInfo(): Promise<MultisigInfo>
  getProposals(ids: string[]): Promise<Record<string, MultisigProposal | null>>
  getProposal(id: string): Promise<MultisigProposal | null>
  quoteExecuteProposal(id: string): Promise<Omit<TransactionResult, 'hash'>>
}

Missing proposal IDs return null. quoteExecuteProposal() throws NoSuchElementError when the proposal does not exist.

IWalletAccountMultisig

In base wallet beta.24, the writable TypeScript contract extends the read-only contract and IDisposable, with signer identity, proposal actions, and execution:

Writable Multisig Contract
interface IWalletAccountMultisig extends IWalletAccountReadOnlyMultisig, IDisposable {
  readonly path: string | null
  readonly keyPair: KeyPair | null

  getSignerAddress(): Promise<string>
  propose(
    tx: Transaction,
    options?: MultisigTransactionOptions
  ): Promise<MultisigProposal & MultisigInteractionResult>
  approveProposal(id: string): Promise<MultisigProposal & MultisigInteractionResult>
  rejectProposal(id: string): Promise<MultisigProposal>
  executeProposal(id: string): Promise<TransactionResult>
}

Migration from beta.23: index is no longer part of this base interface. Handle a null path for a signer without a derivation position and a null keyPair when the signer cannot expose key material. Implementations must provide disposed: boolean and dispose(): void through IDisposable. The runtime interface class does not supply those disposal implementations; check the concrete multisig module's release and cleanup behavior separately.

propose() creates a proposal rather than executing the transaction directly. executeProposal() requires the approval threshold and throws ThresholdNotMetError when the proposal is not ready. Proposal quote, mutation, and execution methods can throw NoSuchElementError for an unknown ID; getter methods return null.

propose() and approveProposal() return the proposal together with an optional transaction field. The field contains the on-chain transaction produced by that call when the call itself settles on-chain: it can be the execution transaction when a call triggers execution, or the proposal/approval transaction when a backend represents those calls on-chain. It is undefined when the call only updates off-chain state. A transaction value does not prove that the proposal executed; inspect status, which is the sole execution indicator.

Optional Message-Signing Contracts

Message proposals are optional capabilities in v1.0.0-beta.17. They are no longer members of IWalletAccountReadOnlyMultisig or IWalletAccountMultisig. A chain-specific module that supports them can expose these separate contracts:

Optional Multisig Message Signing
interface IMultisigMessageSigningReadOnly {
  getMessageProposals(ids: string[]): Promise<Record<string, MultisigMessageProposal | null>>
  getMessageProposal(id: string): Promise<MultisigMessageProposal | null>
}

interface IMultisigMessageSigning extends IMultisigMessageSigningReadOnly {
  proposeMessage(message: string): Promise<MultisigMessageProposal & MultisigSignature>
  approveMessageProposal(id: string): Promise<MultisigMessageProposal & MultisigSignature>
}

Check the concrete multisig wallet module before calling these methods. Missing message proposal IDs return null; approveMessageProposal() can throw NoSuchElementError for an unknown ID.

IMultisigOwnerManagement

Implement this separate contract when a chain-specific account supports proposal-based owner and threshold changes:

Owner Management Contract
interface IMultisigOwnerManagement {
  addOwner(owner: string, options?: MultisigOptions): Promise<MultisigProposal>
  removeOwner(owner: string, options?: MultisigOptions): Promise<MultisigProposal>
  swapOwner(oldOwner: string, newOwner: string): Promise<MultisigProposal>
  changeThreshold(newThreshold: number): Promise<MultisigProposal>
}

Multisig Types

Multisig Result Types
interface MultisigInfo {
  address: string
  owners: string[]
  threshold: number
}

interface MultisigProposal {
  proposalId: string
  confirmations: number
  threshold: number
  status: 'pending' | 'executed'
}

interface MultisigMessageProposal {
  messageId: string
  message: string
  confirmations: number
  threshold: number
  combinedSignature: string | null
}

interface MultisigTransactionOptions {
  autoExecute?: boolean
}

interface MultisigSignature {
  signature: string
}

interface MultisigOptions {
  threshold: number
}

interface MultisigInteractionResult {
  transaction?: TransactionResult
}

The subpath also re-exports the base wallet KeyPair type. In v1.0.0-beta.19, a breaking rename replaces beta.18's MultisigAutoExecuteResult with MultisigInteractionResult; the old type name is not exported. The propose() and approveProposal() return types use MultisigInteractionResult as shown above.

IWalletAccountWithProtocols

Protocol registration and access surface that WDK adds to a wallet account. The consumer-facing WdkAccount type combines this interface with IWalletAccount from @tetherto/wdk-wallet.

Methods

MethodDescriptionReturnsThrows
registerProtocol(label, protocol, ...config)Registers a protocol for this specific accountIWalletAccountWithProtocols-
getSwapProtocol(label)Returns the swap protocol with the given labelISwapProtocolIf protocol not found
getBridgeProtocol(label)Returns the bridge protocol with the given labelIBridgeProtocolIf protocol not found
getLendingProtocol(label)Returns the lending protocol with the given labelILendingProtocolIf protocol not found
getFiatProtocol(label)Returns the fiat protocol with the given labelIFiatProtocolIf protocol not found
getSwidgeProtocol(label)Returns the swidge protocol with the given labelISwidgeProtocolIf protocol not found
getSdaProtocol(label)Returns the SDA protocol with the given labelISdaProtocolIf protocol not found
registerProtocol(label, protocol, ...config)

Registers a new protocol for this specific account.

Type Parameters:

  • A extends any[]: The tuple of constructor arguments after the account, inferred from ProtocolConstructor<A>

Parameters:

  • label (string): Registry label for the protocol. Registering the same protocol type and label again replaces the account-scoped registration.
  • protocol (ProtocolConstructor<A>): A class extending a supported @tetherto/wdk-wallet/protocols base class
  • ...config (NoInfer<A>): The remaining constructor arguments, passed in order after the account; introduced in Core beta.19

Returns: IWalletAccountWithProtocols - The account instance (supports method chaining)

Example:

Register Protocol for Account
const account = await wdk.getAccount('ethereum', 0)

// Register protocol for this specific account
account.registerProtocol('deposits', MySdaProtocol, sdaProtocolConfig)

// Method chaining on the resolved account
const account2 = (await wdk.getAccount('ethereum', 1))
  .registerProtocol('deposits', MySdaProtocol, sdaProtocolConfig)

MySdaProtocol is an illustrative class that extends SdaProtocol; replace it with the concrete provider used by your application.

In Core beta.20, per-account registration stores the class and constructor arguments. Each getter call constructs a fresh protocol instance, so constructor errors surface at retrieval and instance-local state is not preserved between getter calls. Retain the retrieved instance when subsequent calls need its state. A governed account passes its policy proxy to the constructor, so nested calls through that account need their own policy permissions. Constructors that require protected account internals may be incompatible. Global registrations with the same protocol category and label take precedence and construct against the raw account. See Runtime Caveats before choosing a registration path.

getSwapProtocol(label)

Returns the swap protocol with the given label.

Parameters:

  • label (string): The protocol label

Returns: ISwapProtocol - The swap protocol instance

Throws: Error if no swap protocol with the given label has been registered

Example:

Get Swap Protocol
// Register swap protocol
account.registerProtocol('swap', MySwapProtocol, swapProtocolConfig)

// Get swap protocol
const swap = account.getSwapProtocol('swap')

// Use the protocol
const swapResult = await swap.swap({
  tokenIn: '0x...',
  tokenOut: '0x...',
  tokenInAmount: 1000000n
})

// This will throw an error
// try {
//   const uniswap = account.getSwapProtocol('uniswap')
// } catch (error) {
//   console.error('No swap protocol with label "uniswap" found')
// }

MySwapProtocol is an illustrative class that extends SwapProtocol.

getBridgeProtocol(label)

Returns the bridge protocol with the given label.

Parameters:

  • label (string): The protocol label

Returns: IBridgeProtocol - The bridge protocol instance

Throws: Error if no bridge protocol with the given label has been registered

Example:

Get Bridge Protocol
// Register bridge protocol
account.registerProtocol('bridge', MyBridgeProtocol, bridgeProtocolConfig)

// Get bridge protocol
const bridge = account.getBridgeProtocol('bridge')

// Use the protocol
const bridgeResult = await bridge.bridge({
  targetChain: 'arbitrum',
  recipient: '0x...',
  token: '0x...',
  amount: 1000000n
})

MyBridgeProtocol is an illustrative class that extends BridgeProtocol. Follow the concrete provider's approval and configuration requirements before execution.

getLendingProtocol(label)

Returns the lending protocol with the given label.

Parameters:

  • label (string): The protocol label

Returns: ILendingProtocol - The lending protocol instance

Throws: Error if no lending protocol with the given label has been registered

Example:

Get Lending Protocol
// Register lending protocol
account.registerProtocol('lending', MyLendingProtocol, lendingProtocolConfig)

// Get lending protocol
const lending = account.getLendingProtocol('lending')

// Use the protocol
const supplyResult = await lending.supply({
  token: '0x...',
  amount: 1000000n
})

MyLendingProtocol is an illustrative class that extends LendingProtocol.

getFiatProtocol(label)

Returns the fiat protocol with the given label.

Parameters:

  • label (string): The protocol label

Returns: IFiatProtocol - The fiat protocol instance

Throws: Error if no fiat protocol with the given label has been registered

Example:

Get Fiat Protocol
import MoonPayProtocol from '@tetherto/wdk-protocol-fiat-moonpay'

// Register fiat protocol
account.registerProtocol('moonpay', MoonPayProtocol, moonpayProtocolConfig)

// Get fiat protocol
const moonpay = account.getFiatProtocol('moonpay')

const buyUrl = await moonpay.buy({
  cryptoAsset: 'usdt',
  fiatCurrency: 'usd',
  fiatAmount: 10000n
})
getSwidgeProtocol(label)

Returns the swidge protocol with the given label.

The examples below use MySwidgeProtocol as the concrete provider class supplied by your swidge provider module.

Parameters:

  • label (string): The protocol label

Returns: ISwidgeProtocol - The swidge protocol instance

Throws: Error if no swidge protocol with the given label has been registered

Example:

Get Swidge Protocol
// Register a concrete provider class that extends SwidgeProtocol
account.registerProtocol('swidge', MySwidgeProtocol, swidgeProtocolConfig)

// Get swidge protocol
const swidge = account.getSwidgeProtocol('swidge')

const quote = await swidge.quoteSwidge({
  fromToken: '0xdAC17F958D2ee523a2206206994597C13D831ec7',
  toToken: '0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9',
  toChain: 'arbitrum',
  fromTokenAmount: 1000000n
})
getSdaProtocol(label)

Returns the Smart Deposit Address protocol with the given label.

The example uses MySdaProtocol as an illustrative provider class extending SdaProtocol; it does not imply that a provider package is available in the WDK documentation catalog.

Parameters:

  • label (string): The protocol label

Returns: ISdaProtocol - The SDA protocol instance

Throws: Error with No sda protocol registered for label: <label>. if no SDA protocol has been registered under that label

Example:

Register And Retrieve An SDA Protocol
const account = await wdk.getAccount('ethereum', 0)

account.registerProtocol('deposits', MySdaProtocol, sdaProtocolConfig)

const deposits = account.getSdaProtocol('deposits')
const routes = await deposits.getSupportedRoutes({ outputAsset: 'USDT' })

Both global and account-scoped SDA registrations construct a fresh protocol when retrieved. Constructor and configuration failures surface at retrieval, rather than registration. If both scopes use the same label, the global provider is returned.

Complete Example

Complete WDK Flow
import WDK from '@tetherto/wdk'
import WalletManagerEvm from '@tetherto/wdk-wallet-evm'
import WalletManagerTon from '@tetherto/wdk-wallet-ton'

// Initialize WDK Manager
const wdk = new WDK(seedPhrase)
  .registerWallet('ethereum', WalletManagerEvm, {
    provider: 'https://eth.drpc.org'
  })
  .registerWallet('ton', WalletManagerTon, {
    tonApiKey: 'YOUR_TON_API_KEY',
    tonApiEndpoint: 'https://tonapi.io'
  })
  .registerProtocol('ethereum', 'swap', MySwapProtocol, swapProtocolConfig)

// Get accounts
const accountEth = await wdk.getAccount('ethereum', 3)
const accountTon = await wdk.getAccountByPath('ton', "1'/2/3")

// Use wallet account methods
const { hash, fee } = await accountEth.sendTransaction({
  to: '0x...',
  value: 1000000000000000000n // 1 ETH
})

// Use protocols
const swap = accountEth.getSwapProtocol('swap')
const swapResult = await swap.swap(swapOptions)

// Clean up
wdk.dispose()

MySwapProtocol is illustrative and must support the manager account's provider shape. Do not substitute the documented Velora, USD₮0 bridge, or Aave adapters when the manager account's shared ethers provider lacks their required EIP-1193 request() method. Their direct standard-account guides cover Velora setup, bridge setup, and Aave setup. Preserve application checks and account-level controls because WDK Core middleware, including attached policies, does not decorate those separate accounts.

Types

Protocol Constructor Types

Core beta.19 adds the type-only exports Protocol and ProtocolConstructor<A> to @tetherto/wdk. Protocol is the union of the supported swap, bridge, lending, fiat, swidge, and SDA protocol base classes. ProtocolConstructor<A extends any[]> describes new (account: IWalletAccount, ...config: A) => Protocol; the account is supplied by Core and A contains only the arguments your app supplies at registration.

Import these names with TypeScript's import type syntax; neither is a runtime value:

Import Protocol Constructor Types
import type { Protocol, ProtocolConstructor } from '@tetherto/wdk'

WdkAccount

WdkAccount is the exported type returned by getAccount() and getAccountByPath(). It combines the writable wallet methods with the protocol registration and lookup surface. This is a type-only export; there is no runtime WdkAccount value.

Use WdkAccount
import WDK, { type WdkAccount } from '@tetherto/wdk'

async function getBitcoinAccount(wdk: WDK): Promise<WdkAccount> {
  return wdk.getAccount('bitcoin')
}

The published definition is IWalletAccount & IWalletAccountWithProtocols. Concrete wallet packages can expose additional methods beyond this shared shape. The declared return type of IWalletAccountWithProtocols.registerProtocol() remains IWalletAccountWithProtocols, so assigning the result of that chained call can narrow away the writable-account methods in TypeScript.

Transaction Tracking Types

Normalized Transaction Tracking
type Finality = 'pending' | 'confirmed' | 'final' | 'dropped'
type WaitForTransactionTarget = 'confirmed' | 'final'

interface TransactionReceipt {
  hash: string
  finality: Finality
  success?: boolean
  block?: number
  fee?: bigint
}

interface WaitForTransactionOptions {
  target?: WaitForTransactionTarget
  timeout?: number
  interval?: number
  maxPollErrors?: number
}

Concrete wallet modules can extend TransactionReceipt with native chain fields. success is absent while a transaction is pending or dropped; a resolved wait can still have success: false when execution reverted.

FeeRates

Type: FeeRates
interface FeeRates {
  [blockchain: string]: {
    normal: number;
    fast: number;
  };
}

Middleware Function

Types: Middleware
type MiddlewareContext = {
  blockchain: string
  index?: number
  path: string | null
}

type MiddlewareFunction = <A extends IWalletAccount>(
  account: A,
  context: MiddlewareContext
) => Promise<IWalletAccount | void>

The context identifies the original retrieval. blockchain is the registered wallet identifier. index is supplied by getAccount() and omitted for getAccountByPath(). path is the original account's full derivation path and can be null for a signer without a derivation position. WDK captures a defined path, including null, before middleware runs and reuses it for subsequent retrievals of that account object. If a custom account has an undefined path, Core can pass undefined at runtime and reads it again on a later retrieval.

Protocol Types

Types: Protocol Interfaces
// Swap Protocol
interface ISwapProtocol {
  swap(options: SwapOptions): Promise<SwapResult>;
}

// Bridge Protocol
interface IBridgeProtocol {
  bridge(options: BridgeOptions): Promise<BridgeResult>;
}

// Lending Protocol
interface ILendingProtocol {
  supply(options: LendingOptions): Promise<LendingResult>;
  withdraw(options: LendingOptions): Promise<LendingResult>;
  borrow(options: LendingOptions): Promise<LendingResult>;
  repay(options: LendingOptions): Promise<LendingResult>;
}

// Swidge Protocol (unified swap + bridge + route)
interface ISwidgeProtocol extends ISwapProtocol, IBridgeProtocol {
  quoteSwidge(options: SwidgeOptions): Promise<SwidgeQuote>;
  swidge(options: SwidgeOptions, config?: SwidgeProtocolConfig): Promise<SwidgeResult>;
  getSwidgeStatus(id: string, options?: SwidgeStatusOptions): Promise<SwidgeStatusResult>;
  getSupportedChains(): Promise<SwidgeSupportedChain[]>;
  getSupportedTokens(options?: SwidgeSupportedTokensOptions): Promise<SwidgeSupportedToken[]>;
}

// Smart Deposit Address Protocol
interface ISdaProtocol {
  getSupportedRoutes(options?: SdaRoutesOptions): Promise<SdaRoute[]>;
  createDepositAddress(options: SdaCreateDepositAddressOptions): Promise<SdaDepositAddress[]>;
  quoteDeposit(options: SdaDepositOptions): Promise<SdaDepositQuote>;
  deriveDepositAddress(options: SdaCreateDepositAddressOptions): Promise<string>;
  getDepositAddress(id: string): Promise<SdaDepositAddress>;
  renewDepositAddress(id: string): Promise<SdaDepositAddress>;
  getTransfers(address: string, options?: SdaTransfersOptions): Promise<SdaTransfer[]>;
  getTransfersByRecipient(destinationChain: string | number, recipient: string, options?: SdaTransfersOptions): Promise<SdaTransfer[]>;
  getTransfer(id: string): Promise<SdaTransfer>;
  recoverDepositAddress(options: SdaRecoveryOptions): Promise<SdaRecoveryResult>;
  disableDepositAddress(id: string): Promise<void>;
}

SdaProtocol requires provider subclasses to implement getSupportedRoutes() and createDepositAddress(). The remaining methods are optional in the base class and throw UnsupportedOperationError unless the provider implements them. Output assets are provider- and route-specific; USD₮ is a common example, not a base-interface guarantee.

Swidge Protocol

SwidgeProtocol is an abstract base class exported from @tetherto/wdk-wallet/protocols for provider packages that implement a single, route-aware surface for same-chain swaps and cross-chain bridges. It implements ISwidgeProtocol, which extends both ISwapProtocol and IBridgeProtocol, so the base class derives swap(), quoteSwap(), bridge(), and quoteBridge() by delegating to swidge() and quoteSwidge(). Provider subclasses implement the abstract methods below.

MethodDescriptionReturns
quoteSwidge(options)Returns a non-binding quote for a swap/bridge operationPromise<SwidgeQuote>
swidge(options, config?)Executes a swap/bridge operationPromise<SwidgeResult>
getSwidgeStatus(id, options?)Returns the current status of an in-flight operationPromise<SwidgeStatusResult>
getSupportedChains()Returns the chains the provider supportsPromise<SwidgeSupportedChain[]>
getSupportedTokens(options?)Returns the tokens the provider supports, optionally route-scopedPromise<SwidgeSupportedToken[]>

The SwidgeOptions input combines common fields (fromToken, toToken, optional toChain, recipient, refundAddress, slippage) with either an exact-in (fromTokenAmount) or exact-out (toTokenAmount) amount. The optional SwidgeProtocolConfig accepts maxNetworkFeeBps and maxProtocolFeeBps to cap acceptable fees.

See the provider catalog in Swidge modules, then use the selected provider's API reference for its released discovery, quote, execution, status, fee, and result behavior.

Type: ISwidgeProtocol Options and Results
type SwidgeProtocolConfig = {
  maxNetworkFeeBps?: number | bigint;
  maxProtocolFeeBps?: number | bigint;
};

type SwidgeOptions = {
  fromToken: string;
  toToken: string;
  toChain?: string | number;     // defaults to the source chain (same-chain swap)
  recipient?: string;
  refundAddress?: string;
  slippage?: number;             // decimal, e.g. 0.01 for 1%
  minAmountOut?: number | bigint; // destination-token base units; provider-defined enforcement
} & (
  | { fromTokenAmount: number | bigint }  // exact-in
  | { toTokenAmount: number | bigint }    // exact-out
);

type SwidgeStatus =
  | 'pending' | 'action-required' | 'completed' | 'failed'
  | 'refund-pending' | 'refunded' | 'cancelled' | 'expired' | 'partial';

Next Steps


Need Help?

On this page