Skip to content

Instantly share code, notes, and snippets.

@duanescarlett
Created December 28, 2023 02:24
Show Gist options
  • Save duanescarlett/859968d703f3f0f2963a1a499f62ad5c to your computer and use it in GitHub Desktop.
Save duanescarlett/859968d703f3f0f2963a1a499f62ad5c to your computer and use it in GitHub Desktop.
This is for a solidity tutorial that explains the use of the tx object and gas in solidity
// SPDX-License-Identifier: MIT
pragma solidity 0.8.23;
contract TransactionInfo {
// State variable to store contract balance
uint256 public contractBalance;
// Variables to store transaction details
address sender;
uint256 value;
// Event emitted when Ether is sent to the contract
event EthSent(
address indexed sender,
uint256 value
);
// Function to get and return Ether sent to the contract
function getEthSent() public payable {
contractBalance = msg.value;
// Emit an event with the sender and value of Ether sent
emit EthSent(tx.origin, contractBalance);
}
// Function to get the original sender of the transaction
function getTxOrigin() public view returns (address) {
return tx.origin;
}
// Function to get the gas price of the transaction
function txGasPrice() public view returns (uint256) {
return tx.gasprice;
}
// Function to get the input data of the transaction
function txInputData() public pure returns (bytes memory) {
return msg.data;
}
// Function to get the remaining gas limit
function gasLeft() public view returns (uint256) {
uint256 gasL = gasleft();
return gasL;
}
// Function to withdraw the contract balance, only accessible by the owner
function withdraw() external {
// Only the owner can withdraw the contract balance
uint256 amount = contractBalance;
contractBalance = 0;
payable(tx.origin).transfer(amount);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment