// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract TransactionHistory { event Transaction(address indexed from, address indexed to, uint256 indexed amount); function getTransactionHistory(address account) public { uint256 count = 0; uint256 currentBlock = block.number; uint256 lastBlock = currentBlock - 10; while (count < 10 && currentBlock > lastBlock) { currentBlock--; bytes32 blockHash = blockhash(currentBlock); if (blockHash != bytes32(0)) { uint256 txCount = block.number - currentBlock; for (uint256 i = 0; i < txCount && count < 10; i++) { bytes32 txHash = blockhash(currentBlock + 1); (address from, address to, uint256 amount) = parseTransaction(txHash); if (account == from || account == to) { emit Transaction(from, to, amount); count++; } } } } } function parseTransaction (bytes32 txHash) private pure returns (address, address, uint256) { (address from, address to, uint256 amount) = abi.decode(abi.encodePacked(txHash), (address, address, uint256)); return (from, to, amount); } }
时间: 2024-02-15 15:28:18 浏览: 24
这是一个基于以太坊的智能合约,名为TransactionHistory。它记录了过去10个区块内涉及到指定账户的交易记录,并提供getTransactionHistory函数来获取这些交易记录。当有符合条件的交易时,会触发Transaction事件,将交易的发送方、接收方、金额等信息记录下来。私有函数parseTransaction用于解析交易的哈希值,获取其中的发送方、接收方、金额等信息。
相关问题
完善合约// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract PriceFeed { constructor() {} /** * Returns the latest price. */ // 抵押品的价格,比如1 LPL = 2 USD function getLatestPrice() public pure returns (int price) { return 2 * 1e18; } }
完善的合约如下:
```
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorV3Interface {
function latestAnswer() external view returns (int256);
}
contract PriceFeed {
AggregatorV3Interface internal priceFeed;
constructor(address _priceFeed) {
priceFeed = AggregatorV3Interface(_priceFeed);
}
/**
* Returns the latest price.
*/
function getLatestPrice() public view returns (int256 price) {
(
,
price,
,
,
) = priceFeed.latestRoundData();
return price;
}
}
```
这个合约包含了一个 `PriceFeed` 合约,它用来获取某个抵押品的价格。在构造函数中,我们需要传入一个地址,该地址是一个实现了 Chainlink 的 AggregatorV3Interface 接口的合约地址,用来获取抵押品的价格。在 `getLatestPrice` 函数中,我们调用了 `latestRoundData` 函数来获取最新的价格。注意,我们使用了 `view` 关键字,表示该函数不会修改合约状态。
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract DynamicString { string name = "zhangsan"; // 思考是否能直接返回string类型变量的长度。 function getLength() public view returns(uint) { return name.length; } // 思考能否直接获得string类型中的元素 function getPartName() public view returns(bytes1) { return name[0]; } }纠错
对于第一个问题,可以直接返回string类型变量的长度,代码如下:
```
function getLength() public view returns(uint) {
return bytes(name).length;
}
```
对于第二个问题,不能直接获得string类型中的元素,需要先将string类型转换成bytes类型,再根据索引获得对应的元素,代码如下:
```
function getPartName() public view returns(bytes1) {
bytes memory nameBytes = bytes(name);
return nameBytes[0];
}
```