Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Legacy Fallback Support for Non EIP-1559 Chains #104

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 21 additions & 8 deletions src/utils/transaction.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import {
Eip1559FeesNotSupportedError,
FeeValuesEIP1559,
FeeValuesLegacy,
Hash,
Hex,
PublicClient,
Expand Down Expand Up @@ -44,17 +47,13 @@ export async function populateTx(
value: tx.value ?? 0n,
data: tx.data ?? "0x",
};
const [estimatedGas, { maxFeePerGas, maxPriorityFeePerGas }] =
await Promise.all([
// Only estimate gas if not provided.
tx.gas || provider.estimateGas(transactionData),
provider.estimateFeesPerGas(),
]);
// Only estimate gas if not provided.
const estimatedGas = tx.gas || (await provider.estimateGas(transactionData));
const gasValues = await getGasData(provider);
return {
...transactionData,
...gasValues,
gas: estimatedGas,
maxFeePerGas,
maxPriorityFeePerGas,
chainId,
};
}
Expand All @@ -71,6 +70,20 @@ export function addSignature({
return serializeTransaction(signedTx);
}

export async function getGasData(
provider: PublicClient
): Promise<FeeValuesEIP1559 | FeeValuesLegacy> {
try {
// EIP-1559 transaction
return await provider.estimateFeesPerGas();
} catch (error: unknown) {
if (error instanceof Eip1559FeesNotSupportedError) {
console.warn(`${error.shortMessage} Using Legacy Gas Fees`);
}
return { gasPrice: await provider.getGasPrice() };
}
}

/**
* Relays signed transaction to Ethereum mem-pool for execution.
* @param serializedTransaction - Signed Ethereum transaction.
Expand Down
11 changes: 10 additions & 1 deletion tests/unit/utils.transaction.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { zeroAddress } from "viem";
import { serializeTransaction, zeroAddress } from "viem";
import { Network, TransactionWithSignature } from "../../src";
import {
buildTxPayload,
Expand Down Expand Up @@ -54,4 +54,13 @@ describe("Transaction Builder Functions", () => {
expect(tx.to).toEqual(zeroAddress);
expect(tx.value).toEqual(0n);
});

it.only("populate Non EIP-1559 Transaction", async () => {
const baseTx = {
chainId: 3776,
to: zeroAddress,
};
const tx = await populateTx(baseTx, zeroAddress);
console.log("Build Transaction", serializeTransaction(tx));
});
});