Skip to main content

Error Handling & Best Practices

Essential error handling patterns and best practices for Oko SDKs.

Common Error Types

User Rejection

try {
await provider.request({
method: "eth_sendTransaction",
params: [transaction],
});
} catch (error) {
if (error.code === ProviderRpcErrorCode.UserRejectedRequest) {
console.log("User rejected transaction");
}
}

Insufficient Funds

try {
await provider.request({
method: "eth_sendTransaction",
params: [transaction],
});
} catch (error) {
if (error.message.match(/insufficient|funds|balance/i)) {
console.log("Insufficient balance");
}
}

Gas Estimation

try {
const gasEstimate = await provider.request({
method: "eth_estimateGas",
params: [transaction],
});
const gasEstimate = await publicClient.estimateGas(transaction);
const gasLimit = (BigInt(gasEstimate) * BigInt(120)) / BigInt(100); // 20% margin
} catch (error) {
// Fallback to default gas
const gasLimit = BigInt(21000);
}

Transaction Monitoring

export async function monitorTransaction(hash, publicClient, timeout = 60000) {
const startTime = Date.now();

while (Date.now() - startTime < timeout) {
try {
const receipt = await provider.request({
method: "eth_getTransactionReceipt",
params: [hash],
});

if (receipt) {
return {
status: receipt.status === "0x1" ? "success" : "failed",
receipt,
};
}
} catch (error) {
// Transaction not yet mined
}

await new Promise((resolve) => setTimeout(resolve, 2000));
}

return { status: "timeout" };
}

Best Practices

Always Handle Errors

// Good
try {
const result = await walletClient.sendTransaction(transaction);
console.log("Transaction sent:", result);
} catch (error) {
console.error("Transaction failed:", error);
// Show user-friendly error message
}

// Bad
const result = await walletClient.sendTransaction(transaction); // Unhandled promise

Provide User Feedback

const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);

const handleTransaction = async () => {
setIsLoading(true);
setError(null);

try {
const result = await walletClient.sendTransaction(transaction);
// Show success message
} catch (err) {
setError(err.message);
// Show error message
} finally {
setIsLoading(false);
}
};

Log Errors for Debugging

try {
await walletClient.sendTransaction(transaction);
} catch (error) {
console.error("Transaction failed:", {
error: error.message,
code: error.code,
transaction,
timestamp: new Date().toISOString(),
});
throw error;
}

Next Steps