Skip to main content
The @portal-hq/core package is the main entry point for integrating Portal’s MPC wallet infrastructure into your React Native application. It includes the Portal class, React Context utilities (PortalContextProvider, usePortal), and exports for types, enums, and error handling.

Installation

npm install @portal-hq/core
# or
yarn add @portal-hq/core

The Portal Class

The Portal class is the primary interface for interacting with Portal’s MPC wallet infrastructure.

Properties

PropertyTypeDescription
apiIPortalApiPortal API client for REST API interactions
apiKeystringYour Portal Client API Key
backupBackupOptionsConfigured backup storage adapters
chainIdnumberDeprecated.
featureFlagsFeatureFlagsFeature flag configuration
gatewayConfigGatewayLikeGateway/RPC configuration
mpcPortalMpcMPC operations client
providerIPortalProviderEIP-1193 compliant provider

Getters

GetterTypeDescription
addressPromise<string | undefined>The primary wallet address (EIP-155)
addressesPromise<AddressesByNamespace | undefined>All wallet addresses by namespace
autoApprovebooleanWhether auto-approve is enabled

Constructor

import { Portal, BackupMethods } from '@portal-hq/core'
import Keychain from '@portal-hq/keychain'
import GDriveStorage from '@portal-hq/gdrive-storage'
import ICloudStorage from '@portal-hq/icloud-storage'

const portal = new Portal({
  // Required
  apiKey: 'YOUR_PORTAL_CLIENT_API_KEY',
  backup: {
    [BackupMethods.GoogleDrive]: new GDriveStorage(),
    [BackupMethods.iCloud]: new ICloudStorage(),
  },
  gatewayConfig: 'https://mainnet.infura.io/v3/YOUR_INFURA_API_KEY',

  // Optional
  isSimulator: false,
  autoApprove: false,
  keychain: new Keychain(),
  apiHost: 'api.portalhq.io',
  mpcHost: 'mpc.portalhq.io',
    featureFlags: {},
})

PortalOptions

PropertyTypeRequiredDefaultDescription
apiKeystringYes-Portal Client API Key
backupBackupOptionsYes-Backup storage adapters keyed by BackupMethods
gatewayConfigGatewayLikeYes-RPC URL string or chain-specific config object
chainIdnumberNo-Deprecated.
isSimulatorbooleanNofalseRunning in simulator/emulator
autoApprovebooleanNofalseAuto-approve signing requests
keychainKeychainAdapterNonew Keychain()Keychain storage adapter
apiHoststringNo'api.portalhq.io'Portal API host
mpcHoststringNo'mpc.portalhq.io'MPC server host
featureFlagsFeatureFlagsNo{}Feature flags

Wallet Management Methods

createWallet

Creates a new MPC wallet with both SECP256K1 (EVM) and ED25519 (Solana) key pairs.
createWallet(progress?: ProgressCallback): Promise<AddressesByNamespace>
Parameters:
ParameterTypeRequiredDescription
progressProgressCallbackNoCallback for progress updates
Example:
const addresses = await portal.createWallet((status) => {
  console.log('Status:', status.status, 'Done:', status.done)
})
console.log('EVM Address:', addresses.eip155)
console.log('Solana Address:', addresses.solana)

backupWallet

Creates encrypted backup shares for the wallet.
backupWallet(
  method: BackupMethods,
  progress?: ProgressCallback,
  backupConfig?: BackupConfigs
): Promise<string>
Parameters:
ParameterTypeRequiredDescription
methodBackupMethodsYesBackup storage method
progressProgressCallbackNoProgress callback
backupConfigBackupConfigsNoAdditional config (e.g., password)
Example:
// Google Drive backup
const cipherText = await portal.backupWallet(BackupMethods.GoogleDrive)

// Password backup
const cipherText = await portal.backupWallet(
  BackupMethods.Password,
  undefined,
  { passwordStorage: { password: 'user-password' } }
)

recoverWallet

Recovers a wallet from backup shares.
recoverWallet(
  cipherText?: string,
  method: BackupMethods,
  progress?: ProgressCallback,
  backupConfig?: BackupConfigs
): Promise<AddressesByNamespace>
Parameters:
ParameterTypeRequiredDescription
cipherTextstringNoEncrypted backup (if not using Portal backup)
methodBackupMethodsYesBackup method used
progressProgressCallbackNoProgress callback
backupConfigBackupConfigsNoAdditional config
Example:
const addresses = await portal.recoverWallet(
  '',
  BackupMethods.GoogleDrive,
  (status) => console.log(status.status)
)

provisionWallet

Alias for recoverWallet. Provisions a wallet on a new device.
provisionWallet(
  cipherText: string,
  method: BackupMethods,
  progress?: ProgressCallback,
  backupConfig?: BackupConfigs
): Promise<AddressesByNamespace>

Wallet State Methods

doesWalletExist

Checks if a wallet exists on the Portal backend.
doesWalletExist(chainId?: string): Promise<boolean>
Example:
const exists = await portal.doesWalletExist()
const evmExists = await portal.doesWalletExist('eip155:1')
const solanaExists = await portal.doesWalletExist('solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp')

isWalletOnDevice

Checks if wallet signing shares exist on the current device.
isWalletOnDevice(chainId?: string): Promise<boolean>
Example:
const onDevice = await portal.isWalletOnDevice()

isWalletBackedUp

Checks if the wallet has a completed backup.
isWalletBackedUp(chainId?: string): Promise<boolean>
Example:
const backedUp = await portal.isWalletBackedUp()

isWalletRecoverable

Checks if the wallet can be recovered (has at least one backup method).
isWalletRecoverable(chainId?: string): Promise<boolean>
Example:
const recoverable = await portal.isWalletRecoverable()

availableRecoveryMethods

Returns the list of backup methods available for recovery.
availableRecoveryMethods(chainId?: string): Promise<BackupMethods[]>
Example:
const methods = await portal.availableRecoveryMethods()
// ['gdrive', 'icloud']

Signing Methods

personalSign

Signs a message using personal_sign.
personalSign(message: string, chainId?: string): Promise<any>
Example:
const signature = await portal.personalSign('Hello, World!')

ethSign

Signs a message using eth_sign.
ethSign(message: string, chainId?: string): Promise<any>
Example:
const signature = await portal.ethSign('0x...')

ethSignTypedData

Signs typed data (EIP-712) using eth_signTypedData_v4.
ethSignTypedData(typedData: string, chainId?: string): Promise<any>
Example:
const typedData = JSON.stringify({
  types: { ... },
  primaryType: 'Mail',
  domain: { ... },
  message: { ... }
})
const signature = await portal.ethSignTypedData(typedData)

rawSign

Signs raw data without any prefix.
rawSign(message: string, chainId?: string): Promise<any>
Example:
const signature = await portal.rawSign('0xabcdef...')

Transaction Methods

ethSendTransaction

Sends a signed transaction to the network.
ethSendTransaction(
  transaction: SigningRequestParams,
  chainId?: string
): Promise<any>
Example:
const txHash = await portal.ethSendTransaction({
  to: '0x...',
  value: '0x1',
  data: '0x',
})

ethSignTransaction

Signs a transaction without broadcasting.
ethSignTransaction(
  transaction: SigningRequestParams,
  chainId?: string
): Promise<any>
Example:
const signedTx = await portal.ethSignTransaction({
  to: '0x...',
  value: '0x1',
})

sendAsset

High-level method to send tokens or native assets.
sendAsset(
  to: string,
  token: string,
  amount: string,
  chain?: string
): Promise<any>
Parameters:
ParameterTypeRequiredDescription
tostringYesRecipient address
tokenstringYesToken symbol or contract address
amountstringYesAmount to send
chainstringNoChain name or CAIP-2 ID
Supported chains: ethereum, sepolia, base, polygon, solana, optimism, arbitrum, avalanche Example:
// Send ETH on Sepolia
const txHash = await portal.sendAsset(
  '0xRecipient...',
  'ETH',
  '0.1',
  'sepolia'
)

// Send SOL on Solana
const txHash = await portal.sendAsset(
  'SolanaRecipientAddress...',
  'SOL',
  '1',
  'solana'
)

evaluateTransaction

Evaluates a transaction for security risks using Blockaid.
evaluateTransaction(
  params: EvaluateTransactionParam,
  chainId: string,
  operationType?: EvaluateTransactionOperationType
): Promise<BlockaidValidateTrxRes>
Example:
const evaluation = await portal.evaluateTransaction(
  { to: '0x...', value: '0x1', data: '0x' },
  'eip155:1'
)

Provider Methods

request

Generic method to make JSON-RPC requests.
request(
  method: string,
  params: unknown[] | SigningRequestParams,
  chainId?: string
): Promise<any>
Example:
const balance = await portal.request(
  'eth_getBalance',
  ['0xAddress...', 'latest'],
  'eip155:1'
)

ethGetBalance

Gets the native token balance.
ethGetBalance(chainId?: string): Promise<string>

ethGasPrice

Gets the current gas price.
ethGasPrice(chainId?: string): Promise<string>

ethEstimateGas

Estimates gas for a transaction.
ethEstimateGas(
  transaction: SigningRequestParams,
  chainId?: string
): Promise<string>

getBalanceAsNumber

Gets the native token balance as a number (in ETH, not wei).
getBalanceAsNumber(chainId: string): Promise<number>
Example:
const balance = await portal.getBalanceAsNumber('eip155:1')
console.log(`Balance: ${balance} ETH`)

updateChain (Deprecated)

Updates the current chain ID.
updateChain(chainId: string): Promise<void>
Example:
await portal.updateChain('eip155:137') // Switch to Polygon

Event Methods

on

Subscribes to provider events.
on(event: string, callback: EventHandler): void
Example:
portal.on('chainChanged', (chainId) => {
  console.log('Chain changed to:', chainId)
})

emit

Emits a provider event.
emit(event: string, payload?: any): void

removeEventListener

Removes an event listener.
removeEventListener(event: string, callback?: EventHandler): void

Keychain Methods

deleteAddress

Deletes the stored address from keychain.
deleteAddress(): Promise<boolean>

deleteSigningShare

Deletes the signing share from keychain.
deleteSigningShare(): Promise<boolean>

deleteShares

Deletes all shares from keychain.
deleteShares(): Promise<boolean>

Share Metadata Methods

getSigningSharesMetadata

Gets metadata about signing share pairs.
getSigningSharesMetadata(chainId?: string): Promise<SigningSharePairMetadata[]>

getBackupSharesMetadata

Gets metadata about backup share pairs.
getBackupSharesMetadata(chainId?: string): Promise<BackupSharePairMetadata[]>

Testnet Methods

receiveTestnetAsset

Requests testnet tokens from the Portal faucet.
receiveTestnetAsset(
  chainId: string,
  params: FundParams
): Promise<FundResponse>
Example:
const result = await portal.receiveTestnetAsset('eip155:11155111', {
  token: 'ETH',
  amount: '0.1',
})

Portal Connect

createPortalConnectInstance

Creates a Portal Connect instance for WalletConnect integration.
createPortalConnectInstance(chainId: number): PortalConnect
Example:
const portalConnect = portal.createPortalConnectInstance(1)

The portal.api Object

The api property provides access to Portal’s REST API.

getClient

Gets the current client information.
portal.api.getClient(): Promise<ClientResponse>

getNFTs

Fetches NFTs owned by the wallet.
portal.api.getNFTs(chainId?: string): Promise<NFT[]>
Example:
const nfts = await portal.api.getNFTs('eip155:1')

getBalances

Fetches ERC20 token balances.
portal.api.getBalances(chainId?: string): Promise<Balance[]>
Example:
const balances = await portal.api.getBalances('eip155:1')

getTransactions

Fetches transaction history.
portal.api.getTransactions(
  chainId?: string,
  limit?: number,
  offset?: number,
  order?: GetTransactionsOrder
): Promise<Transaction[]>
Example:
const txs = await portal.api.getTransactions('eip155:1', 10, 0, 'desc')

getNetworks

Gets supported networks.
portal.api.getNetworks(): Promise<Network[]>

getEnabledDapps

Gets enabled dApps for the client.
portal.api.getEnabledDapps(): Promise<Dapp[]>

simulateTransaction

Simulates a transaction.
portal.api.simulateTransaction(
  transaction: SimulateTransactionParam,
  chainId?: string
): Promise<SimulatedTransaction>

getQuote

Gets a swap quote.
portal.api.getQuote(
  apiKey: string,
  args: QuoteArgs,
  chainId?: string
): Promise<QuoteResponse>

getSources

Gets available swap sources.
portal.api.getSources(
  apiKey: string,
  chainId?: string
): Promise<Record<string, string>>

The portal.mpc Object

The mpc property handles MPC wallet operations directly.

generate

Generates new MPC signing shares.
portal.mpc.generate(progress?: ProgressCallback): Promise<AddressesByNamespace>

backup

Creates backup shares.
portal.mpc.backup(
  method: BackupMethods,
  progress?: ProgressCallback,
  backupConfig?: BackupConfigs
): Promise<string>

recover

Recovers signing shares from backup.
portal.mpc.recover(
  cipherText: string,
  method: BackupMethods,
  progress?: ProgressCallback,
  backupConfig?: BackupConfigs
): Promise<AddressesByNamespace>

ejectPrivateKey

Ejects the SECP256K1 private key (for migration).
portal.mpc.ejectPrivateKey(
  cipherText?: string,
  method: BackupMethods,
  backupConfig?: BackupConfigs,
  orgShare?: string
): Promise<string>

ejectPrivateKeys

Ejects both SECP256K1 and ED25519 private keys.
portal.mpc.ejectPrivateKeys(
  cipherText?: string,
  method: BackupMethods,
  backupConfig?: BackupConfigs,
  orgShare?: orgShares
): Promise<EjectedKeys>

reset

Resets local wallet data.
portal.mpc.reset(): Promise<void>

isReady

Checks if the MPC client is ready.
portal.mpc.isReady(): Promise<boolean>

The portal.provider Object

The provider property is an EIP-1193 compliant provider.

request

Makes JSON-RPC requests.
portal.provider.request({
  method: string,
  params: any[],
  chainId?: string
}): Promise<any>
Example:
const txHash = await portal.provider.request({
  method: 'eth_sendTransaction',
  params: [{
    to: '0x...',
    value: '0x1',
    data: '0x',
  }],
  chainId: 'eip155:1',
})

React Context

PortalContextProvider

Provides the Portal instance to child components.
import { Portal, PortalContextProvider } from '@portal-hq/core'

const App = () => {
  const [portal, setPortal] = useState<Portal | null>(null)

  useEffect(() => {
    setPortal(new Portal({ /* config */ }))
  }, [])

  if (!portal) return null

  return (
    <PortalContextProvider value={portal}>
      <YourApp />
    </PortalContextProvider>
  )
}

usePortal

Hook to access the Portal instance.
import { usePortal } from '@portal-hq/core'

const WalletComponent = () => {
  const portal = usePortal()

  const createWallet = async () => {
    const addresses = await portal.createWallet()
    console.log(addresses)
  }

  return <Button onPress={createWallet} title="Create Wallet" />
}

Enums

BackupMethods

enum BackupMethods {
  Custom = 'custom',
  GoogleDrive = 'gdrive',
  Password = 'password',
  Passkey = 'passkey',
  Unknown = 'unknown',
  iCloud = 'icloud',
}

PortalNamespace

enum PortalNamespace {
  eip155 = 'eip155',
  solana = 'solana',
}

PortalCurve

enum PortalCurve {
  ED25519 = 'ED25519',
  SECP256K1 = 'SECP256K1',
}

PortalSharePairStatus

enum PortalSharePairStatus {
  COMPLETED = 'completed',
  INCOMPLETE = 'incomplete',
}

MpcErrorCodes

enum MpcErrorCodes {
  CLIENT_NOT_VERIFIED = 'CLIENT_NOT_VERIFIED',
  FORMAT_SHARES_ERROR = 'FORMAT_SHARES_ERROR',
  GOOGLE_UNAUTHENTICATED = 'GOOGLE_UNAUTHENTICATED',
  KEYCHAIN_UNAVAILABLE = 'KEYCHAIN_UNAVAILABLE',
  MPC_MODULE_NOT_FOUND = 'MPC_MODULE_NOT_FOUND',
  PASSWORD_REQUIRED = 'PASSWORD_REQUIRED',
  STORAGE_UNAVAILABLE = 'STORAGE_UNAVAILABLE',
  UNABLE_TO_READ_SIGNING_STORAGE = 'UNABLE_TO_READ_SIGNING_STORAGE',
  UNEXPECTED_ERROR = 'UNEXPECTED_ERROR',
  UNSUPPORTED_MPC_VERSION = 'UNSUPPORTED_MPC_VERSION',
  UNSUPPORTED_STORAGE_METHOD = 'UNSUPPORTED_STORAGE_METHODS',
  WALLET_MODIFICATION_ALREADY_IN_PROGRESS = 'WALLET_MODIFICATION_ALREADY_IN_PROGRESS',
}

EvaluateTransactionOperationType

enum EvaluateTransactionOperationType {
// Defined in @portal-hq/utils.
// Supported values are documented in the Evaluate a transaction guide.
}

Error Classes

MpcError

Custom error class for MPC operations.
class MpcError extends Error {
  code: string
  context?: string
}
Example:
import { MpcError, MpcErrorCodes } from '@portal-hq/core'

try {
  await portal.createWallet()
} catch (error) {
  if (error instanceof MpcError) {
    if (error.code === MpcErrorCodes.WALLET_MODIFICATION_ALREADY_IN_PROGRESS) {
      console.log('Please wait for the current operation to complete')
    }
  }
}

Types

PortalOptions

interface PortalOptions {
  apiKey: string
  backup: BackupOptions
  gatewayConfig: GatewayLike
  /** @deprecated */
  chainId?: number
  isSimulator?: boolean
  autoApprove?: boolean
  keychain?: KeychainAdapter
  apiHost?: string
  mpcHost?: string
  featureFlags?: FeatureFlags
}

BackupOptions

interface BackupOptions {
  custom?: Storage
  gdrive?: Storage
  icloud?: Storage
  passkey?: Storage
  password?: Storage
}

FeatureFlags

interface FeatureFlags {
  enableSdkPerformanceMetrics?: boolean
  isMultiBackupEnabled?: boolean
  useEnclaveMPCApi?: boolean
}

AddressesByNamespace

interface AddressesByNamespace {
  eip155?: string
  solana?: string
}

GatewayConfig

// String format
const gatewayConfig = 'https://mainnet.infura.io/v3/YOUR_KEY'

// Object format for multiple chains
const gatewayConfig: GatewayConfig = {
  'eip155:1': 'https://mainnet.infura.io/v3/YOUR_KEY',
  'eip155:137': 'https://polygon-mainnet.infura.io/v3/YOUR_KEY',
}

Dapp

interface Dapp {
  id: string
  name: string
  addresses: Address[]
  dappOnNetworks: DappOnNetwork[]
  image: DappImage
}

Address

interface Address {
  id: string
  network: Network
  value: string
}

Exports Summary

// Classes
export { Portal }
export { PortalApi }
export { MpcError }

// Context
export { PortalContext, PortalContextProvider, usePortal }

// Enums
export { BackupMethods, PortalCurve, PortalSharePairStatus, PortalNamespace }
export { MpcErrorCodes }
export { EvaluateTransactionOperationType }

// Yield.xyz (see https://docs.portalhq.io/integrations/yield-xyz for documentation)
export { YieldXyz, PortalYieldXyzApi, PortalYieldXyzApiError, YieldXyzErrorCode }

// Types
export type { PortalOptions, Address, Dapp, FeatureFlags, BackupOptions }
export type { IYieldXyz, IPortalYieldXyzApi, YieldXyzOptions, PortalYieldXyzApiOptions }
export type { YieldXyzOperationContext }
// Yield.xyz related types are re-exported by @portal-hq/core.