AA Utils Package
The @layerg-ua-sdk/aa-utils
package provides a collection of utility functions for working with Universal Accounts and blockchain interactions. These utilities handle common tasks such as data formatting, encoding/decoding, cryptographic operations, and chain-specific utilities.
Signature Utilities
createSignature
createSignature(
privateKey: string,
domain: string,
timestamp?: number
): SignatureHeaders
Creates authentication signature headers for API requests.
Parameters:
privateKey: string
- Private key to sign withdomain: string
- Domain for which the signature is being createdtimestamp?: number
- Optional custom timestamp (defaults to current time)
Returns:
SignatureHeaders
- Object containing:signature: string
- The cryptographic signaturetimestamp: number
- Timestamp when signature was createdpublicKey: string
- Public key derived from the private key
Example:
import { createSignature } from '@layerg-ua-sdk/aa-utils';
const headers = createSignature(
'0x1234...', // Private key
'mydapp.com'
);
console.log(`Signature: ${headers.signature}`);
console.log(`Timestamp: ${headers.timestamp}`);
console.log(`Public Key: ${headers.publicKey}`);
verifySignature
verifySignature(
signature: string,
message: string,
address: string
): boolean
Verifies if a signature was created by a specific address.
Parameters:
signature: string
- The signature to verifymessage: string
- Original message that was signedaddress: string
- Address to check against
Returns:
boolean
- Whether the signature is valid
Example:
import { verifySignature } from '@layerg-ua-sdk/aa-utils';
const isValid = verifySignature(
signature,
message,
'0xUserAddress'
);
console.log(`Signature is valid: ${isValid}`);
Data Formatting
formatAddress
formatAddress(
address: string,
format?: AddressFormat
): string
Formats an Ethereum address in various display formats.
Parameters:
address: string
- Ethereum addressformat?: AddressFormat
- Format option:'full'
- Full address (default)'short'
- Shortened with ellipsis (0x1234...5678)'checksum'
- EIP-55 checksum format
Returns:
string
- Formatted address
Example:
import { formatAddress } from '@layerg-ua-sdk/aa-utils';
const shortAddress = formatAddress('0x1234567890abcdef1234567890abcdef12345678', 'short');
console.log(shortAddress); // 0x1234...5678
const checksumAddress = formatAddress('0x1234567890abcdef1234567890abcdef12345678', 'checksum');
console.log(checksumAddress); // 0x1234567890abCdef1234567890ABcDEf12345678
formatBigNumber
formatBigNumber(
value: string | BigNumber,
decimals: number,
displayDecimals?: number
): string
Formats a BigNumber or string numeric value with proper decimal formatting.
Parameters:
value: string | BigNumber
- Value to formatdecimals: number
- Number of decimals used in the input valuedisplayDecimals?: number
- Number of decimals to display in output
Returns:
string
- Formatted numeric string
Example:
import { formatBigNumber } from '@layerg-ua-sdk/aa-utils';
import { BigNumber } from 'ethers';
// Format a token amount (e.g., 1.5 USDC with 6 decimals)
const formatted = formatBigNumber('1500000', 6, 2);
console.log(formatted); // "1.50"
// Format ETH amount
const weiAmount = BigNumber.from('1000000000000000000'); // 1 ETH in wei
const ethAmount = formatBigNumber(weiAmount, 18, 4);
console.log(ethAmount); // "1.0000"
Blockchain Utilities
waitForTransaction
waitForTransaction(
provider: ethers.providers.Provider,
txHash: string,
confirmations?: number,
timeout?: number
): Promise<ethers.providers.TransactionReceipt>
Waits for a transaction to be confirmed on the blockchain.
Parameters:
provider: ethers.providers.Provider
- Blockchain providertxHash: string
- Transaction hash to wait forconfirmations?: number
- Number of confirmations to wait for (default: 1)timeout?: number
- Timeout in milliseconds (default: 60000)
Returns:
Promise<ethers.providers.TransactionReceipt>
- Transaction receipt
Example:
import { waitForTransaction } from '@layerg-ua-sdk/aa-utils';
try {
const receipt = await waitForTransaction(
provider,
'0x1234...',
3, // Wait for 3 confirmations
120000 // 2 minute timeout
);
console.log(`Transaction confirmed in block ${receipt.blockNumber}`);
console.log(`Gas used: ${receipt.gasUsed.toString()}`);
} catch (error) {
console.error('Transaction confirmation failed:', error.message);
}
getChainInfo
getChainInfo(chainId: number): ChainInfo
Gets chain information for a specific network.
Parameters:
chainId: number
- Blockchain network ID
Returns:
ChainInfo
- Chain information including:name: string
- Network namerpcUrl: string
- Default RPC URLcurrency: string
- Native currency symbolexplorerUrl: string
- Block explorer URL
Example:
import { getChainInfo } from '@layerg-ua-sdk/aa-utils';
// Get info for U2U Network (Chain ID 2484)
const u2uInfo = getChainInfo(2484);
console.log(`Network: ${u2uInfo.name}`);
console.log(`Explorer: ${u2uInfo.explorerUrl}`);
// For a custom chain, this will return default values or throw an error if completely unknown
try {
const customChainInfo = getChainInfo(99999);
} catch (error) {
console.error('Chain not supported:', error.message);
}
Log Decoding
decodeEventLog
decodeEventLog(
log: ethers.providers.Log,
abi: any,
eventName?: string
): DecodedEvent
Decodes an event log into a structured object.
Parameters:
log: ethers.providers.Log
- Raw log dataabi: any
- Contract ABI or event ABI fragmenteventName?: string
- Optional event name to decode
Returns:
DecodedEvent
- Decoded event data
Example:
import { decodeEventLog } from '@layerg-ua-sdk/aa-utils';
import { ERC20_ABI } from '@layerg-ua-sdk/aa-smc';
// From a transaction receipt
const transferLog = receipt.logs.find(log => log.topics[0] === '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef');
if (transferLog) {
const decodedEvent = decodeEventLog(transferLog, ERC20_ABI, 'Transfer');
console.log(`Transfer from: ${decodedEvent.args.from}`);
console.log(`Transfer to: ${decodedEvent.args.to}`);
console.log(`Amount: ${formatBigNumber(decodedEvent.args.value, 18)}`);
}
decodeFunctionData
decodeFunctionData(
data: string,
abi: any
): DecodedFunction
Decodes function call data from a transaction.
Parameters:
data: string
- Function call dataabi: any
- Contract ABI or function ABI fragment
Returns:
DecodedFunction
- Decoded function data:name: string
- Function nameargs: any[]
- Function argumentssignature: string
- Function signature
Example:
import { decodeFunctionData } from '@layerg-ua-sdk/aa-utils';
// From a transaction
const decodedFunction = decodeFunctionData(
transaction.data,
CONTRACT_ABI
);
console.log(`Function called: ${decodedFunction.name}`);
console.log('Arguments:', decodedFunction.args);
Transaction Helpers
buildRawTransaction
buildRawTransaction(
options: RawTransactionOptions
): string
Builds a raw transaction suitable for sending via RPC.
Parameters:
options: RawTransactionOptions
- Transaction options:to: string
- Recipient addressvalue?: string
- Value to send (in wei)data?: string
- Transaction datanonce: number
- Account noncegasLimit: string
- Gas limitmaxFeePerGas?: string
- Max fee per gas (for EIP-1559)maxPriorityFeePerGas?: string
- Max priority fee (for EIP-1559)gasPrice?: string
- Gas price (for legacy transactions)chainId: number
- Chain ID
Returns:
string
- Serialized raw transaction
Example:
import { buildRawTransaction } from '@layerg-ua-sdk/aa-utils';
const rawTx = buildRawTransaction({
to: '0xRecipientAddress',
value: '1000000000000000', // 0.001 ETH
data: '0x', // Empty data for simple transfer
nonce: 5,
gasLimit: '21000',
maxFeePerGas: '1500000000', // 1.5 gwei
maxPriorityFeePerGas: '1000000000', // 1 gwei
chainId: 2484
});
// Use the raw transaction with a provider
const txHash = await provider.send('eth_sendRawTransaction', [rawTx]);
estimateGas
estimateGas(
provider: ethers.providers.Provider,
txRequest: TransactionRequest
): Promise<GasEstimate>
Estimates gas for a transaction with current network gas prices.
Parameters:
provider: ethers.providers.Provider
- Blockchain providertxRequest: TransactionRequest
- Transaction request object
Returns:
Promise<GasEstimate>
- Gas estimate information:gasLimit: string
- Estimated gas limitmaxFeePerGas: string
- Recommended max fee per gasmaxPriorityFeePerGas: string
- Recommended max priority fee
Example:
import { estimateGas } from '@layerg-ua-sdk/aa-utils';
const gasEstimate = await estimateGas(provider, {
to: '0xContractAddress',
data: encodedFunctionData,
value: '0'
});
console.log(`Estimated gas limit: ${gasEstimate.gasLimit}`);
console.log(`Max fee per gas: ${gasEstimate.maxFeePerGas}`);
Error Utilities
handleRpcError
handleRpcError(error: any): StandardError
Converts RPC errors into standardized error objects.
Parameters:
error: any
- Original error object from RPC call
Returns:
StandardError
- Standardized error object:code: string
- Error codemessage: string
- Human-readable error messagedata?: any
- Additional error data if available
Example:
import { handleRpcError } from '@layerg-ua-sdk/aa-utils';
try {
// Make RPC call that might fail
await provider.call(callObject);
} catch (error) {
const standardError = handleRpcError(error);
console.error(`Error ${standardError.code}: ${standardError.message}`);
// Handle specific error codes
if (standardError.code === 'INSUFFICIENT_FUNDS') {
// Handle insufficient funds
} else if (standardError.code === 'CONTRACT_EXECUTION_FAILED') {
// Handle contract execution error
}
}
Next Steps
- Explore AA Validation for transaction validation utilities
- See the AA SDK for how to use these utilities in contract calls
- Check Smart Contracts for contract interaction helpers