Transaction simulation, private transactions, gas optimization, and asset change analysis for DeFi operations. The Transact namespace provides advanced transaction capabilities including pre-execution simulation and MEV protection.
Simulate transaction execution before sending to predict outcomes and gas usage.
/**
* Simulate transaction execution to predict results
* @param request - Transaction to simulate
* @param options - Simulation options
* @returns Promise resolving to simulation results
*/
simulateExecution(
request: TransactionRequest,
options?: SimulateExecutionOptions
): Promise<SimulateExecutionResponse>;
/**
* Simulate asset changes that would result from a transaction
* @param request - Transaction to simulate
* @param options - Simulation options
* @returns Promise resolving to asset change predictions
*/
simulateAssetChanges(
request: TransactionRequest,
options?: SimulateAssetChangesOptions
): Promise<SimulateAssetChangesResponse>;
/**
* Simulate asset changes for a bundle of transactions
* @param requests - Array of transactions to simulate as bundle
* @param options - Simulation options
* @returns Promise resolving to bundle asset change predictions
*/
simulateAssetChangesBundle(
requests: TransactionRequest[],
options?: SimulateAssetChangesBundleOptions
): Promise<SimulateAssetChangesBundleResponse>;
interface SimulateExecutionOptions {
blockNumber?: number | string;
stateOverrides?: StateOverrides;
}
interface SimulateExecutionResponse {
calls: SimulateExecutionCall[];
}
interface SimulateExecutionCall {
type: string;
from: string;
to: string;
value: string;
gasUsed: string;
gasLimit: string;
input: string;
output: string;
error?: string;
revertReason?: string;
calls?: SimulateExecutionCall[];
}
interface SimulateAssetChangesOptions {
blockNumber?: number | string;
}
interface SimulateAssetChangesResponse {
changes: AssetChange[];
gasUsed: string;
error?: SimulationError;
}
interface AssetChange {
assetType: AssetType;
changeType: ChangeType;
from: string;
to: string;
rawAmount: string;
amount: string;
symbol: string;
decimals: number;
name: string;
logo?: string;
contractAddress?: string;
tokenId?: string;
}
enum AssetType {
NATIVE = "NATIVE",
ERC20 = "ERC20",
ERC721 = "ERC721",
ERC1155 = "ERC1155",
}
enum ChangeType {
APPROVE = "APPROVE",
TRANSFER = "TRANSFER",
}Send transactions through private mempools to avoid MEV and front-running.
/**
* Send a private transaction to avoid MEV
* @param request - Transaction to send privately
* @param options - Private transaction options
* @returns Promise resolving to transaction hash
*/
sendPrivateTransaction(
request: TransactionRequest,
options?: SendPrivateTransactionOptions
): Promise<string>;
/**
* Cancel a pending private transaction
* @param transactionHash - Hash of transaction to cancel
* @returns Promise resolving to cancellation status
*/
cancelPrivateTransaction(transactionHash: string): Promise<boolean>;
interface SendPrivateTransactionOptions {
maxBlockNumber?: number;
preferences?: PrivateTransactionPreferences;
}
interface PrivateTransactionPreferences {
fast?: boolean;
privacy?: PrivacyLevel;
validity?: number;
}
enum PrivacyLevel {
STANDARD = "standard",
HIGH = "high",
MAXIMUM = "maximum",
}Get optimal gas prices and manage transaction costs.
/**
* Get the recommended max priority fee per gas
* @returns Promise resolving to optimal priority fee in wei
*/
getMaxPriorityFeePerGas(): Promise<string>;
/**
* Get gas fee recommendations for different speed preferences
* @returns Promise resolving to gas fee suggestions
*/
getGasFeeRecommendations(): Promise<GasFeeRecommendations>;
/**
* Estimate gas for a transaction with advanced options
* @param request - Transaction to estimate gas for
* @param options - Estimation options
* @returns Promise resolving to detailed gas estimate
*/
estimateGasAdvanced(
request: TransactionRequest,
options?: EstimateGasOptions
): Promise<AdvancedGasEstimate>;
interface GasFeeRecommendations {
slow: GasFeeRecommendation;
standard: GasFeeRecommendation;
fast: GasFeeRecommendation;
}
interface GasFeeRecommendation {
maxFeePerGas: string;
maxPriorityFeePerGas: string;
gasLimit: string;
estimatedWaitTime: number;
}
interface EstimateGasOptions {
blockNumber?: number | string;
stateOverrides?: StateOverrides;
}
interface AdvancedGasEstimate {
gasLimit: string;
gasUsed: string;
baseFeePerGas: string;
priorityFeePerGas: string;
totalFee: string;
}Enhanced transaction sending with retry logic and monitoring.
/**
* Send transaction with enhanced error handling and retries
* @param request - Transaction to send
* @param options - Send options
* @returns Promise resolving to transaction response
*/
sendTransactionAdvanced(
request: TransactionRequest,
options?: SendTransactionOptions
): Promise<TransactionResponse>;
/**
* Replace a pending transaction with higher gas price
* @param originalHash - Hash of transaction to replace
* @param newRequest - New transaction with higher gas
* @returns Promise resolving to new transaction response
*/
replaceTransaction(
originalHash: string,
newRequest: TransactionRequest
): Promise<TransactionResponse>;
/**
* Speed up a pending transaction
* @param transactionHash - Hash of transaction to speed up
* @param gasPriceIncrease - Percentage increase in gas price
* @returns Promise resolving to new transaction response
*/
speedUpTransaction(
transactionHash: string,
gasPriceIncrease?: number
): Promise<TransactionResponse>;
interface SendTransactionOptions {
retries?: number;
retryDelay?: number;
monitorPending?: boolean;
timeoutMs?: number;
}Tools for protecting against Maximum Extractable Value (MEV) attacks.
/**
* Check if a transaction is vulnerable to MEV
* @param request - Transaction to analyze
* @returns Promise resolving to MEV risk analysis
*/
analyzeMevRisk(request: TransactionRequest): Promise<MevRiskAnalysis>;
/**
* Get MEV protection recommendations for a transaction
* @param request - Transaction to protect
* @returns Promise resolving to protection suggestions
*/
getMevProtectionRecommendations(
request: TransactionRequest
): Promise<MevProtectionRecommendations>;
interface MevRiskAnalysis {
riskLevel: MevRiskLevel;
vulnerabilities: string[];
recommendations: string[];
estimatedMevValue: string;
}
interface MevProtectionRecommendations {
usePrivateMempool: boolean;
adjustSlippage: boolean;
splitTransaction: boolean;
delayExecution: boolean;
alternativeRoutes: string[];
}
enum MevRiskLevel {
LOW = "low",
MEDIUM = "medium",
HIGH = "high",
CRITICAL = "critical",
}Advanced simulation with custom blockchain state modifications.
interface StateOverrides {
[address: string]: StateOverride;
}
interface StateOverride {
balance?: string;
nonce?: number;
code?: string;
state?: { [key: string]: string };
stateDiff?: { [key: string]: string };
}
interface SimulationError {
code: number;
message: string;
revertReason?: string;
}Usage Examples:
import { Alchemy, Network } from "alchemy-sdk";
const alchemy = new Alchemy({
apiKey: "your-api-key",
network: Network.ETH_MAINNET,
});
// Simulate transaction execution
const simulation = await alchemy.transact.simulateExecution({
to: "0x...",
value: "1000000000000000000", // 1 ETH
data: "0x...",
});
// Simulate asset changes before executing
const assetChanges = await alchemy.transact.simulateAssetChanges({
to: "0x...", // DEX contract
data: "0x...", // swap function call
});
console.log("Expected asset changes:", assetChanges.changes);
// Send private transaction to avoid MEV
const privateTxHash = await alchemy.transact.sendPrivateTransaction({
to: "0x...",
value: "1000000000000000000",
gasLimit: "21000",
}, {
preferences: {
fast: true,
privacy: "high",
},
});
// Get optimal gas prices
const priorityFee = await alchemy.transact.getMaxPriorityFeePerGas();
const gasRecommendations = await alchemy.transact.getGasFeeRecommendations();
// Analyze MEV risk
const mevRisk = await alchemy.transact.analyzeMevRisk({
to: "0x...", // AMM contract
data: "0x...", // large swap
});
if (mevRisk.riskLevel === "HIGH") {
const protection = await alchemy.transact.getMevProtectionRecommendations({
to: "0x...",
data: "0x...",
});
if (protection.usePrivateMempool) {
// Use private transaction
await alchemy.transact.sendPrivateTransaction(/* ... */);
}
}
// Simulate bundle of transactions
const bundleSimulation = await alchemy.transact.simulateAssetChangesBundle([
{ to: "0x...", data: "0x..." }, // Transaction 1
{ to: "0x...", data: "0x..." }, // Transaction 2
]);