UNPKG

@avalabs/avacloud-waas-react

Version:
623 lines (591 loc) 20.2 kB
import * as react_jsx_runtime from 'react/jsx-runtime'; import * as _cubist_labs_cubesigner_sdk from '@cubist-labs/cubesigner-sdk'; import { CubeSignerClient, IdentityProof } from '@cubist-labs/cubesigner-sdk'; import { PropsWithChildren, ButtonHTMLAttributes, ReactNode } from 'react'; import { ButtonProps } from '@avalabs/core-k2-components'; import { Hex, Signature, TransactionRequest, Hash } from 'viem'; import * as _tanstack_react_query_build_legacy_types from '@tanstack/react-query/build/legacy/types'; import { CreateConnectorFn } from '@wagmi/core'; /** * Cubist wallet information */ interface CubistWalletInfo { /** Ethereum wallet address */ address: string; /** Cubist session ID */ sessionId: string; /** Cubist organization ID */ orgId: string; } /** * Wallet information structure */ interface WalletInfo { /** Wallet address (null if no wallet is connected) */ address: string | null; /** Optional HD wallet account index */ accountIndex?: number; /** Optional mnemonic ID for hierarchical deterministic wallets */ mnemonicId?: string; /** Optional Avalanche P-Chain/X-Chain address */ avaAddress?: string; /** Optional Cubist wallet information */ cubistWallet?: CubistWalletInfo; } /** * User information returned after authentication */ interface UserInfo { /** User's email address */ email?: string; /** Unique subject identifier */ sub: string; /** List of configured multi-factor authentication methods */ configured_mfa: string[]; /** User's display name */ displayName?: string; /** Raw user data from Auth0 */ rawUserData?: Auth0User$1; /** Additional properties that may be available */ [key: string]: unknown; } /** * Auth0 user object structure */ interface Auth0User$1 { /** User's email address */ email?: string; /** User's nickname */ nickname?: string; /** Unique subject identifier */ sub: string; /** Additional properties that may be available */ [key: string]: unknown; } /** * Organization configuration types */ /** * Admin portal settings within organization configuration */ interface AdminPortalSettings { /** * Array of enabled social login providers * Possible values: 'google', 'facebook', 'x', 'twitter', 'apple' * Note: Some providers like 'facebook' may be in development and not fully supported */ socialLogins?: string[]; [key: string]: unknown; } /** * Organization configuration interface */ interface OrgConfig { /** Primary key of the organization */ PKey?: string; /** Secondary key of the organization */ SKey?: string; /** Organization ID */ orgID?: string; /** Wallet provider organization ID used for Cubist */ walletProviderOrgID?: string; /** Admin portal settings */ adminPortalSettings?: AdminPortalSettings; /** Allowed origins for CORS */ originAllowlist?: string[]; /** Timestamp when the config was created */ createdAt?: number; /** Timestamp when the config was last updated */ updatedAt?: number; [key: string]: unknown; } /** * Authentication message payload structure */ interface AuthMessagePayload { /** OAuth ID token */ idToken?: string; /** User claims object */ claims?: Record<string, unknown>; /** Optional message content */ message?: string; /** User identifier */ userId?: string; } /** * Registration payload with identity proof */ interface RegisterPayload extends AuthMessagePayload { /** Identity proof for registration */ proof: { /** Identity information */ identity: { /** Issuer */ iss: string; /** Subject */ sub: string; }; /** User email */ email: string; /** Preferred username */ preferred_username?: string; /** Additional user information */ user_info?: { /** User ID */ user_id?: string; }; }; } /** * Avalanche Virtual Machine types */ declare enum VM { /** Ethereum Virtual Machine (C-Chain) */ EVM = "EVM", /** Avalanche Virtual Machine (X-Chain) */ AVM = "AVM", /** Platform Virtual Machine (P-Chain) */ PVM = "PVM" } type QueryClient = { invalidateQueries: (options: { queryKey: string[]; }) => void; }; /** * Possible AvaCloud environments */ type AvaCloudEnvironment = 'development' | 'staging' | 'production'; interface Auth0User { email?: string; email_verified?: boolean; family_name?: string; given_name?: string; name?: string; nickname?: string; picture?: string; sub: string; updated_at?: string; [key: string]: string | boolean | number | null | undefined; } type MessageType = 'IFRAME_READY' | 'CHECK_AUTH_STATUS' | 'AUTH_STATUS' | 'GET_OIDC' | 'RECEIVE_OIDC' | 'LOGIN_REQUEST' | 'SIGNUP_REQUEST' | 'LOGOUT_REQUEST' | 'REGISTER' | 'REGISTER_SUCCESS' | 'AUTH_STATE_UPDATE' | 'WALLET_KEYS_UPDATE' | 'WALLET_KEYS_ERROR' | 'ADD_ACCOUNT' | 'ERROR'; interface BaseAuthMessage { type: MessageType; requestId?: string; } interface IframeReadyMessage extends BaseAuthMessage { type: 'IFRAME_READY'; } interface CheckAuthStatusMessage extends BaseAuthMessage { type: 'CHECK_AUTH_STATUS'; payload?: { orgId: string; environment?: AvaCloudEnvironment; }; } interface AuthStatusMessage extends BaseAuthMessage { type: 'AUTH_STATUS'; isAuthenticated: boolean; user?: Auth0User; userId?: string; tokens?: { access_token: string; id_token: string; }; orgConfig?: { id: string; cubistOrgId?: string; [key: string]: unknown; }; } interface GetOidcMessage extends BaseAuthMessage { type: 'GET_OIDC'; } interface ReceiveOidcMessage extends BaseAuthMessage { type: 'RECEIVE_OIDC'; payload: { idToken: string; }; } interface LoginRequestMessage extends BaseAuthMessage { type: 'LOGIN_REQUEST'; email?: string; password?: string; connection?: string; } interface SignupRequestMessage extends BaseAuthMessage { type: 'SIGNUP_REQUEST'; email?: string; password?: string; } interface LogoutRequestMessage extends BaseAuthMessage { type: 'LOGOUT_REQUEST'; } interface RegisterMessage extends BaseAuthMessage { type: 'REGISTER'; payload: { proof: IdentityProof; }; } interface RegisterSuccessMessage extends BaseAuthMessage { type: 'REGISTER_SUCCESS'; payload: { userId: string; }; } interface AuthStateUpdateMessage extends BaseAuthMessage { type: 'AUTH_STATE_UPDATE'; payload: { isAuthenticated: boolean; authLoading: boolean; hasClient: boolean; hasKeys: boolean; cubistLoading: boolean; error?: string; status: 'error' | 'unauthenticated' | 'no_client' | 'no_keys' | 'ready' | 'loading'; }; } interface WalletKeysUpdateMessage extends BaseAuthMessage { type: 'WALLET_KEYS_UPDATE'; payload: { address: string; key: string; allKeys: string[]; }; } interface WalletKeysErrorMessage extends BaseAuthMessage { type: 'WALLET_KEYS_ERROR'; payload: { error: string; }; } interface AddAccountMessage extends BaseAuthMessage { type: 'ADD_ACCOUNT'; payload: { accountIndex: number; mnemonicId: string; derivationPath: string; identityProof: { email?: string; displayName?: string; sub: string; configured_mfa: string[]; }; }; } interface ErrorMessage extends BaseAuthMessage { type: 'ERROR'; error?: string; payload?: string; } type AuthMessage = IframeReadyMessage | CheckAuthStatusMessage | AuthStatusMessage | GetOidcMessage | ReceiveOidcMessage | LoginRequestMessage | SignupRequestMessage | LogoutRequestMessage | RegisterMessage | RegisterSuccessMessage | AuthStateUpdateMessage | WalletKeysUpdateMessage | WalletKeysErrorMessage | AddAccountMessage | ErrorMessage; /** * Props for the AvaCloudWalletProvider component */ interface AvaCloudWalletProviderProps { children: React.ReactNode; orgId: string; chainId?: number; darkMode?: boolean; env?: AvaCloudEnvironment; onAuthSuccess?: (user: UserInfo) => void; onAuthError?: (error: Error) => void; onWalletUpdate?: (wallet: WalletInfo) => void; } /** * Context type for AvaCloud authentication state and actions */ interface AvaCloudWalletContextType { isAuthenticated: boolean; isLoading: boolean; user: UserInfo | null; wallet: WalletInfo; orgConfig: OrgConfig | null; logout: () => void; loginWithCubist: (oidcToken?: string) => Promise<void>; cubistClient: CubeSignerClient | null; cubistError: Error | null; login: () => void; signup: (email: string, password: string) => void; addAccount: (accountIndex: number) => Promise<void>; queryClient: QueryClient; iframe: HTMLIFrameElement | null; authServiceUrl: string; chainId: number; environment: AvaCloudEnvironment; } declare function AvaCloudWalletProvider({ children, orgId, chainId, darkMode, env, onAuthSuccess, onAuthError, onWalletUpdate, }: AvaCloudWalletProviderProps): react_jsx_runtime.JSX.Element; declare function useAvaCloudWallet(): AvaCloudWalletContextType; interface ThemeContextType { isDarkMode: boolean; toggleTheme: () => void; } interface ThemeProviderProps extends PropsWithChildren { darkMode?: boolean; onDarkModeChange?: (isDark: boolean) => void; } declare const useThemeMode: () => ThemeContextType; declare function ThemeProvider({ children, darkMode, onDarkModeChange }: ThemeProviderProps): react_jsx_runtime.JSX.Element; interface LoginButtonProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'color'>, Pick<ButtonProps, 'color'> { label?: string; className?: string; } declare function LoginButton({ label, className, ...props }: LoginButtonProps): react_jsx_runtime.JSX.Element; interface WalletButtonProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'color'>, Pick<ButtonProps, 'color'> { label?: string; className?: string; } declare function WalletButton({ label, className, ...props }: WalletButtonProps): react_jsx_runtime.JSX.Element; interface WalletDisplayProps { className?: string; truncateAddress?: boolean; showAddAccount?: boolean; } declare function WalletDisplay({ className, truncateAddress, showAddAccount, }: WalletDisplayProps): react_jsx_runtime.JSX.Element | null; interface UserProfileProps { className?: string; showLogout?: boolean; } declare function UserProfile({ className, showLogout, }: UserProfileProps): react_jsx_runtime.JSX.Element | null; interface WalletCardProps { onClose?: () => void; className?: string; } declare function WalletCard({ onClose }: WalletCardProps): react_jsx_runtime.JSX.Element | null; interface BlockchainData { chainId: string; chainName: string; description: string; platformChainId: string; subnetId: string; vmId: string; vmName: string; explorerUrl: string; rpcUrl: string; wsUrl: string; isTestnet: boolean; utilityAddresses: { multicall: string; }; networkToken: { name: string; symbol: string; decimals: number; logoUri: string; description: string; }; chainLogoUri: string; private: boolean; enabledFeatures: string[]; } interface TokenReputation { verified: boolean; popular: boolean; risky: boolean; } interface NativeToken { chainId: string; name: string; symbol: string; decimals: number; price?: { currencyCode: string; value: number; }; balance: string; logoUri: string; } interface ERC20Token { ercType: string; chainId: string; address: string; name: string; symbol: string; decimals: number; balance: string; tokenReputation: TokenReputation | null; logoUri?: string; } interface TokensViewProps { onBack: () => void; onSend?: (token: ERC20Token | NativeToken) => void; } declare function TokensView({ onSend }: TokensViewProps): react_jsx_runtime.JSX.Element; interface SendViewProps { onBack: () => void; onViewStateChange?: (state: ViewState) => void; selectedToken?: ERC20Token | NativeToken; } type ViewState = 'form' | 'loading' | 'success' | 'failure' | 'idle'; declare function SendView({ onBack, onViewStateChange, selectedToken: initialToken }: SendViewProps): react_jsx_runtime.JSX.Element; interface ReceiveViewProps { onBack: () => void; } declare function ReceiveView(_props: ReceiveViewProps): react_jsx_runtime.JSX.Element; interface ExportViewProps { onBack: () => void; } declare function ExportView({ onBack }: ExportViewProps): react_jsx_runtime.JSX.Element; declare function useAuth(): { isAuthenticated: boolean; isLoading: boolean; user: UserInfo | null; wallet: WalletInfo; login: () => void; logout: () => void; loginWithCubist: (oidcToken?: string | undefined) => Promise<void>; cubistClient: _cubist_labs_cubesigner_sdk.CubeSignerClient | null; cubistError: Error | null; }; interface NextData { props: { pageProps: Record<string, unknown>; }; } declare global { interface Window { __NEXT_DATA__?: NextData; } } interface PostMessageConfig { authServiceUrl: string; orgId: string; environment: AvaCloudEnvironment; iframe: HTMLIFrameElement | null; isIframeReady: boolean; onAuthSuccess?: () => void; onAuthError?: (error: Error) => void; onWalletUpdate?: (newWallet: WalletInfo) => void; onOidcReceived?: (token: string) => void; onOrgConfigUpdate?: (config: Record<string, unknown>) => void; setIsAuthenticated: (isAuthenticated: boolean) => void; setUser: (user: UserInfo | null) => void; setIsLoading: (isLoading: boolean) => void; setIsIframeReady: (isReady: boolean) => void; wallet: WalletInfo; cubistClient: CubeSignerClient | null; } declare function usePostMessage({ authServiceUrl, orgId, environment, iframe, isIframeReady, onAuthSuccess, onAuthError, onOidcReceived, onOrgConfigUpdate, setIsAuthenticated, setUser, setIsLoading, setIsIframeReady, cubistClient, }: PostMessageConfig): { sendMessage: (message: { type: string; payload?: Record<string, unknown>; requestId?: string; }) => void; }; interface SignMessageState { isLoading: boolean; error: string | null; signature: Hex | null; } interface UseSignMessageReturn extends SignMessageState { signMessage: (message: string) => Promise<void>; reset: () => void; } declare function useSignMessage(): UseSignMessageReturn; interface SignTransactionState { isLoading: boolean; error: string | null; signature: Signature | null; signedTransaction: Hex | null; } interface UseSignTransactionReturn extends SignTransactionState { signTransaction: (transaction: TransactionRequest) => Promise<void>; reset: () => void; } declare function useSignTransaction(): UseSignTransactionReturn; interface ChainIdControls { chainId: number; setChainId: (chainId: number) => void; } declare function useChainId(): ChainIdControls; interface TransferState { isLoading: boolean; error: string | null; txHash: Hash | null; viewState: 'idle' | 'loading' | 'success' | 'failure'; actualBaseFee: string | null; actualPriorityFee: string | null; actualTotalFee: string | null; } interface UseTransferTokensReturn extends TransferState { transfer: (toAddress: string, amount: string) => Promise<void>; transferERC20: (tokenAddress: string, toAddress: string, amount: string, decimals: number) => Promise<void>; reset: () => void; } declare function useTransferTokens(): UseTransferTokensReturn; interface UseUserWalletsResult { getWallets: (client: CubeSignerClient) => Promise<WalletInfo[]>; error: Error | null; isLoading: boolean; } declare function useUserWallets(): UseUserWalletsResult; declare function useGlacier(): { balance: string; isLoadingBalance: boolean; currencySymbol: string; blockchain: BlockchainData | undefined; }; declare function useBlockchain(chainId: string): _tanstack_react_query_build_legacy_types.UseQueryResult<BlockchainData, Error>; declare function avaCloudWallet(): CreateConnectorFn; interface GaslessConfig { /** URL of the AvaCloud gasless relayer RPC endpoint */ relayerUrl: string; /** Public JSON-RPC endpoint of the target subnet */ subnetRpcUrl: string; /** Forwarder contract address provided by AvaCloud */ forwarderAddress: string; /** EIP-712 domain name, e.g. "domain" */ domainName: string; /** EIP-712 domain version, e.g. "1" */ domainVersion: string; /** Primary type for the request, e.g. "Message" */ requestType: string; /** Suffix for the request in format "type name" (e.g. "bytes32 XMKUCJONOFSUSFCYHTYHCLX") */ suffix?: string; } interface FetchGaslessConfigParams { orgId: string; subnetId: string; } interface GaslessProviderProps { children: ReactNode; /** Optional pre-fetched config (skip network fetch when supplied) */ config?: GaslessConfig; /** Parameters required to fetch config from the auth service */ fetchParams?: FetchGaslessConfigParams; } /** * GaslessProvider – supplies gasless relayer configuration to hooks * * NOTE: For security reasons, this provider expects the configuration to be * provided by the integrator. The intention is that your backend (or * another trusted environment) fetches the relayer configuration via * AvaCloud's internal endpoint and forwards the non-sensitive parts * (relayer URL, forwarder address, etc.) to the browser. */ declare function GaslessProvider({ children, config, fetchParams }: GaslessProviderProps): react_jsx_runtime.JSX.Element; interface GaslessTxState { isLoading: boolean; error: string | null; txHash: string | null; } interface SendGaslessTransactionParams { functionName: string; args?: unknown[]; abi?: unknown; contractAddress?: string; } interface UseGaslessTransactionReturn extends GaslessTxState { sendGaslessTransaction: (params: SendGaslessTransactionParams) => Promise<void>; reset: () => void; } interface UseGaslessTransactionOptions { /** Gasless transaction configuration */ gaslessConfig: GaslessConfig; /** Default contract address (can be overridden per call) */ contractAddress?: string; /** Default ABI (can be overridden per call) */ abi?: unknown; } declare function useGaslessTransaction({ gaslessConfig, contractAddress: defaultContractAddress, abi: defaultAbi }: UseGaslessTransactionOptions): UseGaslessTransactionReturn; export { type AddAccountMessage, type AdminPortalSettings, type Auth0User, type AuthMessage, type AuthMessagePayload, type AuthStateUpdateMessage, type AuthStatusMessage, type AvaCloudEnvironment, type AvaCloudWalletContextType, AvaCloudWalletProvider, type AvaCloudWalletProviderProps, type BaseAuthMessage, type CheckAuthStatusMessage, type CubistWalletInfo, type ErrorMessage, ExportView, GaslessProvider, type GetOidcMessage, type IframeReadyMessage, LoginButton, type LoginRequestMessage, type LogoutRequestMessage, type MessageType, type OrgConfig, type ReceiveOidcMessage, ReceiveView, type RegisterMessage, type RegisterPayload, type RegisterSuccessMessage, SendView, type SignupRequestMessage, ThemeProvider, TokensView, type UserInfo, UserProfile, VM, WalletButton, WalletCard, WalletDisplay, type WalletInfo, type WalletKeysErrorMessage, type WalletKeysUpdateMessage, avaCloudWallet, useAuth, useAvaCloudWallet, useBlockchain, useChainId, useGaslessTransaction, useGlacier, usePostMessage, useSignMessage, useSignTransaction, useThemeMode, useTransferTokens, useUserWallets };