Solidity.

Bài viết

Chia sẻ kiến thức của bạn.

0x8744...6532.
Apr 12, 2023
Hỏi đáp Chuyên Gia

How to set transaction gas price in foundry?

If I have a test in foundry:

function testDoStuff() public {
  myContract.functionCall()
}

And I'm trying to figure out how much gas it uses, I'd use gasleft(). However, tx.gasprice is defaulted to 0 in foundry.

How do I set it to something else so I can get the gas used of this function?

For context, in a foundry test, this prints 0

console.log(tx.gasprice);
  • Smart Contract
  • Solidity
1
2
Chia sẻ
Bình luận
.

Câu trả lời

2
0x8744...6532.
Apr 12 2023, 18:30

You can use the foundry cheatcode txGasPrice.

For example:

vm.txGasPrice(2);
uint256 gasStart = gasleft();
fundMe.withdraw();
gasEnd = gasleft();

// tx.gasprice is 2 due to the first line
console.log(tx.gasprice);
uint256 gasUsed = (gasStart - gasEnd) * tx.gasprice;
1
Câu trả lời hay nhất
Bình luận
.
carlesdh.
Apr 15 2023, 07:45

Yes, your answer is correct for setting the transaction gas price in Foundry using the cheatcode txGasPrice. Here's the revised code with some minor modifications to ensure correct variable declarations and usage:

await vm.txGasPrice(2);
const gasStart = await ethers.provider.getGasLeft();
await myContract.functionCall();
const gasEnd = await ethers.provider.getGasLeft();

// tx.gasprice is 2 due to the first line
const gasPrice = 2;
const gasUsed = (gasStart - gasEnd) * gasPrice;
console.log("Gas used:", gasUsed);

This code sets the transaction gas price to 2 using the vm.txGasPrice cheatcode. It then calculates the gas used by the functionCall() by subtracting the remaining gas (gasEnd) from the initial gas (gasStart) and multiplying the result by the gas price.

1
Bình luận
.

Bạn có biết câu trả lời không?

Hãy đăng nhập và chia sẻ nó.

Solidity is an object-oriented, high-level language for implementing smart contracts. It is a curly-bracket language designed to target the Ethereum Virtual Machine (EVM).

38Bài viết47Câu trả lời
Sui.X.Peera.

Kiếm phần của bạn từ 1000 Sui

Tích lũy điểm danh tiếng và nhận phần thưởng khi giúp cộng đồng Sui phát triển.

Chúng tôi sử dụng cookie để đảm bảo bạn có trải nghiệm tốt nhất trên trang web của chúng tôi.
Thêm thông tin