Blocks

訪問舊區塊的難度

  • November 6, 2022

是否可以從智能合約中訪問舊區塊的屬性(例如難度、時間戳等)?

您可以訪問智能合約中前 256 個區塊的區塊雜湊。但是,如果您想要舊塊的其他屬性(例如難度、時間戳等),您可以使用web3.eth.getBlock()web3.js等方法。

看:

https://docs.soliditylang.org/en/develop/units-and-global-variables.html#special-variables-and-functions

https://web3js.readthedocs.io/en/v1.2.11/web3-eth.html

這是我 1 個月的疑問,我認為最推薦的是使用“事件”,例如,您可以通過索引timestamp使搜尋更容易。

可以考慮的另一種選擇是準確確定您希望能夠從合約內部永久訪問哪些值,並將它們永久保存在數組中。

如果您只想從介面訪問過去的值,合約無法訪問不再位於storage中的變數,但您可以從web3.

我們檢索合約的第一個變數(索引 0),它是uint類型的,然後你可以試一試Testnet,該地址的合約已經部署在其中:

contract = "0x6d363cd2eb21ebd39e50c9a2f94a9724bf907d13";
maxBlocks = 1000;

startBlock = eth.blockNumber;
for (var i = 1; i < maxBlocks; i++) { /* Be careful: we go *back* in time */
   current = web3.eth.getStorageAt(contract, 0, startBlock-i);
   if (current != previous) {
       /* TODO Where to find msg.sender? We probably have to loop
        * over the transactions in the block can call
        * web3.eth.getTransaction */
       blockDate = new Date(web3.eth.getBlock(startBlock-i+1).timestamp*1000);
       console.log("Block #" + (startBlock-i+1) +  " (" + web3.eth.getBlock(startBlock-i+1).timestamp + " " + blockDate.toString()
           +  ") : " + web3.toDecimal(previous));
       /* What if there are two changes in a single block? The
        * documentation of getStorageAt seems silent about that */
       previous = current;
   }
}
blockDate = new Date(web3.eth.getBlock(startBlock-maxBlocks).timestamp*1000);
console.log("Somewhere before block #" +(startBlock-maxBlocks) +  " (block of " + blockDate.toString()
       +  ") : " + web3.toDecimal(previous));

引用自:https://ethereum.stackexchange.com/questions/138788