Skip to main content

Utilities

Utility functions and helper hooks provided by GIWA SDK.

Viem Re-exports

The SDK re-exports commonly used viem utilities for convenience. You don't need to install viem separately.

import {
parseEther,
formatEther,
parseUnits,
formatUnits,
isAddress,
getAddress,
} from 'giwa-react-native-wallet';

parseEther

Converts ETH string to wei (bigint).

const wei = parseEther('1.5'); // 1500000000000000000n
ParameterTypeDescription
valuestringETH amount as string
ReturnsbigintAmount in wei

formatEther

Converts wei (bigint) to ETH string.

const eth = formatEther(1500000000000000000n); // '1.5'
ParameterTypeDescription
valuebigintAmount in wei
ReturnsstringETH amount as string

parseUnits

Converts token amount string to smallest unit.

// USDC has 6 decimals
const amount = parseUnits('100', 6); // 100000000n
ParameterTypeDescription
valuestringToken amount as string
decimalsnumberToken decimals
ReturnsbigintAmount in smallest unit

formatUnits

Converts smallest unit to token amount string.

const amount = formatUnits(100000000n, 6); // '100'
ParameterTypeDescription
valuebigintAmount in smallest unit
decimalsnumberToken decimals
ReturnsstringToken amount as string

isAddress

Validates if string is a valid Ethereum address.

isAddress('0x1234567890123456789012345678901234567890'); // true
isAddress('invalid'); // false
ParameterTypeDescription
addressstringAddress to validate
ReturnsbooleanWhether address is valid

getAddress

Returns checksummed address.

const checksummed = getAddress('0x1234...'); // '0x1234...' (with correct checksum)
ParameterTypeDescription
addressstringAddress to checksum
Returns`0x${string}`Checksummed address

Helper Hooks

Shared hooks for building custom async operations.

useAsyncAction

Manages loading and error state for a single async action.

import { useAsyncAction } from 'giwa-react-native-wallet';

function MyComponent() {
const { execute, isLoading, error, reset } = useAsyncAction(
async (amount: string) => {
// Your async operation
return await myAsyncFunction(amount);
},
{
onSuccess: (result) => console.log('Success:', result),
onError: (error) => console.error('Error:', error),
}
);

return (
<Button
title={isLoading ? 'Processing...' : 'Execute'}
onPress={() => execute('1.0')}
disabled={isLoading}
/>
);
}

Parameters

NameTypeRequiredDescription
action(...args: TArgs) => Promise<TResult>YesAsync function to execute
options.onSuccess(result: TResult) => voidNoSuccess callback
options.onError(error: Error) => voidNoError callback

Returns

PropertyTypeDescription
execute(...args: TArgs) => Promise<TResult>Execute the action
isLoadingbooleanLoading state
errorError | nullError if failed
reset() => voidReset loading and error state

useAsyncActions

Manages multiple async actions as a group.

import { useAsyncActions } from 'giwa-react-native-wallet';

function BridgeComponent() {
const actions = useAsyncActions({
withdraw: async (amount: string) => await bridgeManager.withdraw(amount),
deposit: async (amount: string) => await bridgeManager.deposit(amount),
});

return (
<>
<Button
title={actions.withdraw.isLoading ? 'Withdrawing...' : 'Withdraw'}
onPress={() => actions.withdraw.execute('1.0')}
disabled={actions.withdraw.isLoading}
/>
<Button
title={actions.deposit.isLoading ? 'Depositing...' : 'Deposit'}
onPress={() => actions.deposit.execute('1.0')}
disabled={actions.deposit.isLoading}
/>
</>
);
}

Parameters

NameTypeRequiredDescription
actionsRecord<string, (...args) => Promise<unknown>>YesObject of async functions

Returns

Object with same keys as input, each containing:

PropertyTypeDescription
execute(...args) => Promise<TResult>Execute this action
isLoadingbooleanLoading state for this action
errorError | nullError if this action failed
reset() => voidReset this action's state

useAsyncQuery

Manages data fetching with auto-fetch and refetch support.

import { useAsyncQuery } from 'giwa-react-native-wallet';

function BalanceDisplay({ address }: { address: string }) {
const { data, isLoading, error, refetch } = useAsyncQuery(
() => tokenManager.getBalance(address),
{
enabled: !!address,
refetchInterval: 30000, // Refetch every 30 seconds
onSuccess: (balance) => console.log('Balance updated:', balance),
}
);

if (isLoading) return <Text>Loading...</Text>;
if (error) return <Text>Error: {error.message}</Text>;

return (
<View>
<Text>Balance: {data}</Text>
<Button title="Refresh" onPress={refetch} />
</View>
);
}

Parameters

NameTypeRequiredDefaultDescription
queryFn() => Promise<T>Yes-Async function to fetch data
options.enabledbooleanNotrueWhether query is enabled
options.initialDataTNonullInitial data value
options.refetchIntervalnumberNo-Auto refetch interval (ms)
options.onSuccess(data: T) => voidNo-Success callback
options.onError(error: Error) => voidNo-Error callback

Returns

PropertyTypeDescription
dataT | nullFetched data
isLoadingbooleanLoading state
errorError | nullError if failed
refetch() => Promise<void>Manually trigger refetch
reset() => voidReset to initial state

Error Classes

GIWA SDK provides specialized error classes for different error types.

import {
GiwaError,
GiwaSecurityError,
GiwaNetworkError,
GiwaWalletError,
GiwaTransactionError,
GiwaFeatureUnavailableError,
} from 'giwa-react-native-wallet';

Error Class Hierarchy

ClassCodeDescription
GiwaErrorVariousBase error class
GiwaSecurityErrorSECURITY_ERRORSecurity-related errors (biometric, storage)
GiwaNetworkErrorNETWORK_ERRORNetwork/RPC errors
GiwaWalletErrorWALLET_ERRORWallet operation errors
GiwaTransactionErrorTRANSACTION_ERRORTransaction errors
GiwaFeatureUnavailableErrorFEATURE_UNAVAILABLEFeature not available on network

Error Handling Example

import {
GiwaSecurityError,
GiwaWalletError,
GiwaTransactionError,
ErrorCodes,
} from 'giwa-react-native-wallet';

try {
await sendTransaction({ to: '0x...', value: '1.0' });
} catch (error) {
if (error instanceof GiwaSecurityError) {
if (error.code === ErrorCodes.BIOMETRIC_FAILED) {
Alert.alert('Authentication Failed', 'Please try again');
} else if (error.code === ErrorCodes.RATE_LIMIT_EXCEEDED) {
Alert.alert('Rate Limited', 'Please wait before trying again');
}
} else if (error instanceof GiwaWalletError) {
Alert.alert('Wallet Error', error.message);
} else if (error instanceof GiwaTransactionError) {
if (error.code === ErrorCodes.INSUFFICIENT_BALANCE) {
Alert.alert('Insufficient Balance', 'Not enough ETH to send');
}
}
}

Error Codes

All available error codes:

import { ErrorCodes } from 'giwa-react-native-wallet';

Security Errors

CodeDescription
SECURE_STORAGE_UNAVAILABLESecure storage not available
BIOMETRIC_NOT_AVAILABLEBiometric hardware not available
BIOMETRIC_NOT_ENROLLEDNo biometrics enrolled on device
BIOMETRIC_FAILEDBiometric authentication failed
RATE_LIMIT_EXCEEDEDToo many attempts, rate limited
INVALID_RPC_URLInvalid RPC URL format
INVALID_ADDRESSInvalid Ethereum address
INVALID_AMOUNTInvalid amount format

Wallet Errors

CodeDescription
WALLET_NOT_FOUNDNo wallet found in storage
WALLET_ALREADY_EXISTSWallet already exists
INVALID_MNEMONICInvalid recovery phrase
INVALID_PRIVATE_KEYInvalid private key format

Transaction Errors

CodeDescription
INSUFFICIENT_BALANCENot enough balance
TRANSACTION_FAILEDTransaction failed
GAS_ESTIMATION_FAILEDFailed to estimate gas

Network Errors

CodeDescription
RPC_ERRORRPC call failed
NETWORK_UNAVAILABLENetwork not reachable
FEATURE_UNAVAILABLEFeature not available on network
NETWORK_NOT_READYNetwork not ready for use
TBD_CONTRACTContract not yet deployed

Bridge Errors

CodeDescription
BRIDGE_DEPOSIT_FAILEDBridge deposit failed
BRIDGE_WITHDRAW_FAILEDBridge withdrawal failed

Network Validator Utils

Utilities for checking network status and feature availability.

import {
getNetworkStatus,
getFeatureAvailability,
isTbdAddress,
} from 'giwa-react-native-wallet';

getNetworkStatus

Get comprehensive network status.

const status = getNetworkStatus('testnet');
// {
// network: 'testnet',
// readiness: 'ready',
// isTestnet: true,
// hasWarnings: false,
// warnings: [],
// features: { bridge: {...}, giwaId: {...}, ... }
// }

getFeatureAvailability

Check if a specific feature is available.

const bridgeStatus = getFeatureAvailability('bridge', 'mainnet');
// {
// name: 'bridge',
// status: 'unavailable',
// reason: 'L1 Bridge contract is TBD'
// }

isTbdAddress

Check if an address is a TBD placeholder.

isTbdAddress('0xTBD'); // true
isTbdAddress('0x1234...'); // false

Environment Detection

import { detectEnvironment } from 'giwa-react-native-wallet';

const env = await detectEnvironment();
// 'expo' | 'react-native' | 'unsupported'
Return ValueDescription
'expo'Running in Expo with expo-secure-store
'react-native'Running in React Native CLI with react-native-keychain
'unsupported'No secure storage available