Skip to main content

Portal Class

The Portal class is the main entry point for the Portal Web SDK. It provides methods for wallet management, transaction signing, and blockchain interactions.

Constructor

Creates a new Portal instance with the specified configuration.
Parameters Example Usage

Public Properties

Feature flags

The featureFlags option controls optional SDK behavior. Pass it when creating a Portal instance. Example

Logging Methods

setLogLevel

Sets the SDK log level at runtime. All SDK messages (e.g. deprecation warnings, provider messages) respect this level.
Parameters Example Usage
See Logging Configuration for full details.

getLogLevel

Returns the current SDK log level.
Returns LogLevel — The current level: 'none' | 'error' | 'warn' | 'info' | 'debug' Example Usage

Initialization Methods

onReady

Registers a callback to be executed when the Portal instance is ready.
Parameters Returns A cleanup function that removes the callback when called. Example Usage

onInitializationError

Registers a callback to be executed if initialization fails.
Parameters Returns A cleanup function that removes the callback when called. Example Usage

onWalletNotOnDevice

Registers a callback to be executed when the user’s wallet signing share is no longer in device storage (for example, after Safari ITP clears localStorage). The callback is replayed immediately if the event already fired before this method was called, so it is safe to register at any point during initialization.
Parameters Returns A cleanup function that removes the callback when called. Payload — WalletNotOnDevicePayload Example Usage

Wallet Lifecycle Methods

createWallet

Creates a new wallet and generates addresses for supported chains.
Parameters Returns Promise<string> - The wallet address Example Usage

configureFirebaseStorage

Registers Firebase Authentication for wallet backup and recovery. The Web SDK runs MPC inside an iframe; your parent page implements getToken, and the iframe requests Firebase ID tokens over a postMessage bridge when storing or reading encryption keys on Portal’s token backup service (TBS). Call this method before backupWallet or recoverWallet with BackupMethods.firebase.
Parameters FirebaseStorageConfigOptions
Example usage
Errors and behavior
  • If getToken is not configured and the iframe requests a token, the bridge rejects with Firebase storage is not configured (getToken missing).
  • If getToken returns null, backup/recovery fails with messages such as [FirebaseStorage] Firebase ID token is required or [FirebaseStorage] Firebase ID token is null.
  • After HTTP 401, the iframe retries once with getToken({ forceRefresh: true }). If that still returns null, you may see [FirebaseStorage] Firebase ID token is null after 401 retry.
  • TBS HTTP failures surface as [FirebaseStorage] Failed to store encryption key: … or [FirebaseStorage] Failed to read encryption key: ….
Firebase ID tokens are sent as the X-Firebase-Token header together with your Portal Client API key (Authorization: Bearer … from the iframe’s configured apiKey).
validateOperations on the iframe side only checks that a Firebase ID token is available; it does not verify TBS connectivity.

backupWallet

Creates a backup of the wallet using the specified backup method.
Parameters Returns Promise<BackupResponse> containing:
  • cipherText: Encrypted backup data
  • storageCallback: Function to finalize storage
Example Usage

recoverWallet

Recovers a wallet from a backup.
Parameters Returns Promise<string> - The recovered wallet address Example Usage

provisionWallet

Alias for recoverWallet. Provisions a wallet from a backup.

clearLocalWallet

Clears the local wallet data from device storage.
Returns Promise<boolean> - true if successful Example Usage

Wallet Status Methods

doesWalletExist

Checks if a wallet exists for the client.
Parameters Returns Promise<boolean> - true if wallet exists Example Usage

isWalletOnDevice

Checks if wallet shares are stored on the current device.
Parameters Returns Promise<boolean> - true if wallet is on device

isWalletBackedUp

Checks if the wallet has been backed up.
Parameters Returns Promise<boolean> - true if wallet is backed up

isWalletRecoverable

Checks if the wallet can be recovered.
Returns Promise<boolean> - true if wallet is recoverable

availableRecoveryMethods

Gets the available recovery methods for the wallet.
Returns Promise<BackupMethods[]> - Array of available backup methods Example Usage

Address Methods

getEip155Address

Gets the EIP-155 (Ethereum-compatible) address.
Returns Promise<string> - The Ethereum address Example Usage

getSolanaAddress

Gets the Solana address.
Returns Promise<string> - The Solana address Example Usage

getTronAddress

Gets the TRON address.
Returns Promise<string> - The TRON address, or an empty string if no TRON wallet exists yet Example Usage

Eject Methods

Providing the custodian backup share to the client device puts both MPC shares on a single device, removing the multi-party security benefits of MPC. This operation should only be done for users who want to move off of MPC and into a single private key. Use portal.eject() or portal.ejectPrivateKeys() at your own risk!

eject

Ejects the SECP256K1 private key from MPC custody. For eject examples see here
Parameters Returns Promise<EjectResult> containing:
  • SECP256K1: The private key as a string

ejectPrivateKeys

Ejects all private keys (both SECP256K1 and ED25519) from MPC custody.
Parameters Returns Promise<EjectPrivateKeysResult> containing:
  • SECP256K1: The SECP256K1 private key
  • ED25519: The ED25519 private key

Transaction Methods

request

Makes an RPC request to a blockchain network. This is the primary method for interacting with blockchains.
Parameters Returns Promise<any> - Response from the RPC call Example Usage

sendAsset

Helper method to send assets to another address. Supports EVM (eip155:*), Solana (solana:*), and TRON (tron:*) chains.
Parameters Returns Promise<string> — transaction hash (EVM / Solana) or transaction ID (TRON) Example Usage
TRON transaction confirmation polling is not supported. portal.waitForConfirmation always returns false for tron:* chains. Verify the transaction status directly via TRON RPC using the transaction ID returned by sendAsset.

sendSol

Helper method to send SOL tokens.
Parameters Returns Promise<string> - Transaction signature Example Usage

sendEth

Helper method to send ETH.
Parameters Returns Promise<any> - Transaction hash Example Usage

rawSign

Signs data directly using the specified cryptographic curve. An optional third argument accepts signatureApprovalMemo which is shown to the user during the approval flow.
Parameters Returns Promise<string> - Signature Example Usage

sendBatchUserOp

Builds, signs, and broadcasts a batch of token transfers as a single ERC-4337 UserOperation. Only available on Account Abstraction clients. Chain must be eip155:-prefixed.
SendBatchUserOpRequest fields: SendBatchUserOpTransaction fields: Returns Promise<BroadcastBatchedUserOpResponse>{ data: { userOpHash: string }, metadata: { chainId: string } } Example Usage
See Batch User Operations for the full guide.

sendBatchedAssets

Builds, signs, and broadcasts a gas-subsidized batch that includes a reimbursement transfer — in a fee token you supply — to recover the paymaster gas cost. Requires an AA client. Chain must be eip155:-prefixed.
SendBatchedAssetsRequest fields: GasReimbursement fields: Returns Promise<BroadcastBatchedUserOpResponse> See Batch User Operations for the full guide including the two-pass build flow.

buildBatchedUserOp

Low-level: builds an ERC-4337 UserOperation from an ordered list of raw calls without signing or broadcasting it. Use this when you need direct control over the sign/broadcast steps.
BuildBatchedUserOpRequest fields: UserOperationCall fields: BuildBatchedUserOpResponse.metadata fields (all optional — backends that predate this change omit them):

broadcastBatchedUserOp

Low-level: broadcasts a signed UserOperation to the bundler.
BroadcastBatchedUserOpRequest fields:
When signing userOpHash manually with rawSign, strip the 0x prefix before passing it: userOpHash.replace(/^0x/, '').

Delegations

portal.delegations exposes approve, revoke, status, transfer, and high-level sign-and-submit helpers for token delegations on supported EVM and Solana chains. See Manage Token Delegations for walkthroughs. The interfaces below match the types exported from @portal-hq/web (for example import type { ApproveDelegationRequest } from '@portal-hq/web').

portal.delegations methods

Request and options types

ApproveDelegationRequest

RevokeDelegationRequest

GetDelegationStatusRequest

TransferFromRequest

DelegationSubmitOptions

Optional second argument for approveAndSubmit, revokeAndSubmit, and transferAndSubmit.

DelegationSubmitProgress


Yield Types

Types used by the high-level deposit and withdraw methods on portal.yield.yieldXyz. All types are exported from @portal-hq/web.

YieldDepositParams

Union type — provide either yieldId or chain + token. A non-empty yieldId takes precedence.

YieldWithdrawParams

Same union as YieldDepositParams.

YieldSubmitOptions

YieldSubmitProgress

YieldDepositResult

YieldWithdrawResult

Same shape as YieldDepositResult.

YieldXyzValidator


API Methods

getClient

Gets information about the client and their wallets.
Returns Promise<ClientResponse> with client information including:
  • id: Client ID
  • address: Primary address
  • wallets: Array of wallet information
  • metadata: Namespace metadata with addresses
Example Usage

getAssets

Gets the assets (tokens) held by the wallet.
Parameters Returns Promise<GetAssetsResponse> with asset information Example Usage

getNFTAssets

Gets NFT assets held by the wallet.
Parameters Returns Promise<NFTAsset[]> - Array of NFT assets Example Usage

getTransactionHistory

Returns the transaction history for a wallet across supported chains. Replaces the legacy getTransactions method with pagination and extended support for modern transaction types (including ERC-4337 UserOperations on EVM chains). EVM responses use the normalized format documented below, while Solana currently returns its legacy response shape and will be unified in a future update.
Parameters Default behavior (userOperations)
  • EVM (eip155:*) — If the authenticated client has Account Abstraction enabled (isAccountAbstracted), the SDK automatically sends userOperations=only. If the client is an EOA, the SDK does not send the parameter.
  • Non-EVM chains (e.g. solana:*, Bitcoin, Tron, Stellar) — The SDK never injects userOperations; the filter does not apply to those namespaces.
If userOperations is provided, it always overrides this behavior. Returns Promise<GetTransactionHistoryResponse> For Solana chains (solana:*):
For EVM, Bitcoin, Tron, Stellar chains:
TransactionHistoryItem is a discriminated union:
  • RegularTransaction: type: 'transaction' with optional token metadata (asset, tokenAddress, tokenDecimals)
  • UserOperationTransaction: type: 'userOperation' with UserOp fields (userOpHash, entryPoint, actualGasCost, actualGasUsed)
Example Usage

getTransactions

Deprecated: Use getTransactionHistory() instead, which provides improved type safety with discriminated unions for regular transactions and UserOperations, and proper polymorphic response types for Solana vs unified formats.
Gets transaction history for the wallet.
Parameters Returns Promise<Transaction[]> - Array of transactions Example Usage

evaluateTransaction

Evaluates a transaction before execution to check if the transaction can be executed, and perform security validations.
Parameters Returns Promise<EvaluatedTransaction> with security analysis Example Usage

buildTransaction

Builds a transaction for sending tokens.
Parameters Returns Promise<BuiltTransaction> with the built transaction object Example Usage

receiveTestnetAsset

Requests testnet assets from a faucet.
Parameters Returns Promise<FundResponse> with funding details Example Usage

Swap Methods

getQuote

Gets a quote for an in-chain token swap.
Deprecated: Use the portal.trading.zerox.getQuote method instead.

getSources

Gets available swap sources for in-chain swaps.
Deprecated: Use the portal.trading.zerox.getSources method instead.

Utility Methods

updateChain

Updates the current chain ID for the provider.
Parameters Example Usage

getRpcUrl

Gets the configured RPC URL for a chain.
Parameters Returns string - The RPC URL Throws Error if chain ID is not configured

storedClientBackupShare

Notifies Portal that a backup share has been stored.
Parameters Returns Promise<void> Example Usage

Integration Classes

portal.yield (Yield)

The Yield class provides access to Yield.xyz integration for yield farming opportunities. Properties

getValidators

Fetches validator addresses for a specific yieldId. Delegates to portal.yield.yieldXyz.getValidators. Throws if the response does not contain a valid validators array.
Parameters Returns Promise<YieldXyzValidator[]> — Array of validator objects. Each entry includes at minimum address: string plus optional name, commission, apy, and any additional provider-specific fields. Example Usage

portal.yield.yieldXyz (YieldXyz)

Access yield farming features through the Yield.xyz integration. Includes low-level methods (discover, enter, exit, manage, track, getTransaction, getBalances, getHistoricalActions) and high-level helpers (deposit, withdraw). See the Yield.xyz guide for walkthroughs.

deposit

High-level deposit: resolves the yield, builds the enter action, signs and sends each transaction in order, waits for confirmation between steps when configured, and reports hashes to Yield.xyz — all in one call. See the Yield.xyz guide for parameter tables and examples.
Parameters Returns Promise<YieldDepositResult> with fields:

withdraw

High-level withdraw: same dual-input modes, yieldId resolution, signer fallback, and confirmation behavior as deposit, but calls the Yield.xyz exit action. See the Yield.xyz guide for parameter tables and examples.
Parameters Returns Promise<YieldWithdrawResult> — Same shape as YieldDepositResult.

discover

Discovers available yield opportunities.
Parameters Returns Promise<YieldXyzGetYieldsResponse> - Available yield opportunities Example Usage

getBalances

Retrieves yield balances for specified addresses and networks.
Parameters Returns Promise<YieldXyzGetBalancesResponse> - Balance information

getHistoricalActions

Retrieves historical yield actions with optional filtering.
Returns Promise<YieldXyzGetHistoricalActionsResponse> - Historical actions

enter

Enters a yield opportunity.
Parameters Returns Promise<YieldXyzEnterYieldResponse> - Action details Example Usage

exit

Exits a yield opportunity.
Parameters Returns Promise<YieldXyzExitResponse> - Action details

manage

Manages a yield opportunity with specified parameters.
Parameters Returns Promise<YieldXyzManageYieldResponse> - Action details

track

Tracks a transaction by submitting its hash.
Parameters Returns Promise<YieldXyzTrackTransactionResponse> - Tracking confirmation

getTransaction

Retrieves a single yield action transaction by its ID.
Parameters Returns Promise<YieldXyzGetTransactionResponse> - Transaction details

portal.trading (Trading)

The Trading class provides access to:
  • Li.Fi integration for cross-chain swaps and bridges
  • 0x integration for in-chain swaps
Properties

portal.trading.lifi (LiFi)

Access cross-chain swap and bridge features through the Li.Fi integration. Includes tradeAsset for end-to-end trades and lower-level methods for manual flows. See the Li.Fi guide for walkthroughs.

tradeAsset

Runs the end-to-end Li.Fi flow in one call: discover routes, select a route, build each step, sign and broadcast, wait for confirmation, poll Li.Fi status for cross-chain steps, and return hashes. See the Li.Fi guide for parameter tables, progress lifecycle, and examples.
Parameters Returns Promise<LifiTradeAssetResult> with fields:

pollStatus

Built-in Li.Fi status polling with retries and exponential backoff. Use when you already have a tx hash and want the same polling behavior as inside tradeAsset. See the Li.Fi guide for option defaults and examples.
Parameters Returns Promise<LifiStatusRawResponse> — Terminal status response.

getRoutes

Retrieves available routes for cross-chain swaps and bridges.
Parameters Returns Promise<LifiRoutesResponse> - Available routes Example Usage

getQuote

Retrieves a quote for a swap or bridge operation.
Parameters Returns Promise<LifiQuoteResponse> - Quote details including fees and estimated time Example Usage

getStatus

Retrieves the status of a cross-chain transaction.
Parameters Returns Promise<LifiStatusResponse> - Transaction status Example Usage

getRouteStep

Retrieves an unsigned transaction for a specific route step.
Parameters Returns Promise<LifiStepTransactionResponse> - Unsigned transaction ready to be signed Example Usage

portal.trading.zeroX (0x)

Access in-chain swap features through the 0x integration. See the 0x guide for full walkthroughs.

tradeAsset

Fetches a 0x quote, signs and broadcasts the transaction, waits for on-chain confirmation, and returns hashes. See the 0x guide for parameter tables and examples.

getPrice

Retrieves an indicative price for a token swap without generating executable transaction data.

getQuote

Gets a swap quote with executable transaction data.

getSources

Gets available liquidity sources for a chain.

portal.ramps (Ramps)

The Ramps class groups fiat on/off-ramp integrations. Properties See the Noah Web SDK guide and the Meld Web SDK guide for end-to-end flows and prerequisites.

portal.ramps.noah (Noah)

Noah methods forward to the embedded Portal iframe, which calls https://api.portalhq.io/api/v3/clients/me/integrations/noah/... with the authenticated client session. Responses follow the { data, metadata? } envelope used across Client API integrations.

initiateKyc

ReturnsPromise<NoahInitiateKycResponse> with data.hostedUrl for hosted onboarding.

initiatePayin

ReturnsPromise<NoahInitiatePayinResponse> with data.payinId and data.bankDetails.

simulatePayin

ReturnsPromise<NoahSimulatePayinResponse> (sandbox simulation payload).

getPayoutCountries

ReturnsPromise<NoahGetPayoutCountriesResponse> with data.countries.

getPayoutChannels

ReturnsPromise<NoahGetPayoutChannelsResponse> (data shape is provider-specific).

getPayoutChannelForm

ReturnsPromise<NoahGetPayoutChannelFormResponse> (dynamic form schema).

getPayoutQuote

ReturnsPromise<NoahGetPayoutQuoteResponse> including payoutId, formSessionId, cryptoAmountEstimate, totalFee.

initiatePayout

ReturnsPromise<NoahInitiatePayoutResponse> with destinationAddress and conditions for deposit legs when applicable.

getPaymentMethods

ReturnsPromise<NoahGetPaymentMethodsResponse> with data.paymentMethods and optional pageToken.

portal.ramps.meld (Meld)

Meld methods forward to the embedded Portal iframe, which calls https://api.portalhq.io/api/v3/clients/me/integrations/meld/... with the authenticated client session. Responses follow the { data, metadata? } envelope used across Client API integrations. See the Meld Web SDK guide for end-to-end flows with full examples.

createCustomer

ReturnsPromise<MeldCreateCustomerResponse> with data: MeldCustomer (id, externalId, accountId, name, email, type, status).

searchCustomer

ReturnsPromise<MeldSearchCustomerResponse> with data: { customers: MeldCustomer[]; count: number; remaining: number }.

getRetailQuote

ReturnsPromise<MeldGetRetailQuoteResponse> with data: { quotes: MeldQuote[]; message?: string; error?: string; timestamp?: string }. Each MeldQuote includes required fields: serviceProvider, transactionType, sourceAmount, sourceCurrencyCode, destinationAmount, destinationCurrencyCode, exchangeRate, transactionFee, totalFee, paymentMethodType; and optional nullable fields: sourceAmountWithoutFees, destinationAmountWithoutFees, networkFee, partnerFee, fiatAmountWithoutFees, countryCode, customerScore, institutionName, isNativeAvailable, rampIntelligence.

createRetailWidget

ReturnsPromise<MeldCreateRetailWidgetResponse> with data: { id, token, customerId, externalCustomerId, externalSessionId, widgetUrl }.

searchRetailTransactions

ReturnsPromise<MeldSearchRetailTransactionsResponse> with data: { transactions: MeldTransaction[]; count: number; remaining: number; totalCount: number }.

getRetailTransaction

ReturnsPromise<MeldGetRetailTransactionResponse> with data: { transaction: MeldTransaction }.

getRetailTransactionBySession

ReturnsPromise<MeldGetRetailTransactionResponse> with data: { transaction: MeldTransaction }.

getServiceProviders

ReturnsPromise<MeldGetServiceProvidersResponse> with data: MeldServiceProvider[].

getCountries

ReturnsPromise<MeldGetCountriesResponse> with data: MeldCountry[].

getFiatCurrencies

ReturnsPromise<MeldGetFiatCurrenciesResponse> with data: MeldFiatCurrency[].

getCryptoCurrencies

ReturnsPromise<MeldGetCryptoCurrenciesResponse> with data: MeldCryptoCurrency[].

getPaymentMethods

ReturnsPromise<MeldGetPaymentMethodsResponse> with data: MeldPaymentMethod[].

getDefaults

ReturnsPromise<MeldGetDefaultsResponse> with data: MeldCountryDefault[] (countryCode, defaultCurrencyCode, defaultPaymentMethods).

getBuyLimits

ReturnsPromise<MeldGetBuyLimitsResponse> with data: MeldFiatCurrencyPurchaseLimit[] (currencyCode, minimumAmount, maximumAmount, defaultAmount).

getSellLimits

ReturnsPromise<MeldGetSellLimitsResponse> with data: MeldCryptoCurrencySellLimit[] (currencyCode, chainCode, minimumAmount, maximumAmount, defaultAmount).

getKycLimits

ReturnsPromise<MeldGetKycLimitsResponse> with data: MeldKycFiatLevel[]. Each entry includes currencyCode and optional level1, level2, level3 of type MeldKycLimitTier with dailyLimit, weeklyLimit, monthlyLimit, yearlyLimit, transactionLimit.

Deprecated Methods

The following methods are deprecated. Use portal.request() instead.

ethEstimateGas

Deprecated: Use portal.request({ method: 'eth_estimateGas', ... }) instead.

ethGasPrice

Deprecated: Use portal.request({ method: 'eth_gasPrice', ... }) instead.

ethGetBalance

Deprecated: Use portal.request({ method: 'eth_getBalance', ... }) instead.

ethSendTransaction

Deprecated: Use portal.request({ method: 'eth_sendTransaction', ... }) instead.

ethSignTransaction

Deprecated: Use portal.request({ method: 'eth_signTransaction', ... }) instead.

ethSignTypedData

Deprecated: Use portal.request({ method: 'eth_signTypedData', ... }) instead.

ethSignTypedDataV3

Deprecated: Use portal.request({ method: 'eth_signTypedData_v3', ... }) instead.

ethSignTypedDataV4

Deprecated: Use portal.request({ method: 'eth_signTypedData_v4', ... }) instead.

personalSign

Deprecated: Use portal.request({ method: 'personal_sign', ... }) instead.

getBalances

Deprecated: Use portal.getAssets() instead.

getNFTs

Deprecated: Use portal.getNFTAssets() instead.

simulateTransaction

Deprecated: Use portal.evaluateTransaction() instead.