Attacks

契約中的自毀工作是什麼?

  • January 9, 2022

它如何用於在不觸發回退功能的情況下處理將乙太幣強制發送到合約?

selfdestruct操作碼根本不會創建對地址的呼叫,它只是將ingselfdestruct合約的餘額添加到它指定的地址。

當該地址的智能合約執行自毀時,它會從區塊鏈中刪除智能合約。selfdestruct 將儲存在合約中的所有剩餘乙太幣發送到指定地址。

這是一個展示概念的範例。不得直接用於生產。

   contract Test {
   uint public y;
   uint256 public bal;
   address payable public me;
   // This function is called for all messages sent to
   // this contract, except plain Ether transfers
   // Any call with non-empty calldata to this contract will execute
   // the fallback function (even if Ether is sent along with the call).
   fallback() external payable { 
       y = msg.value; 
       bal = address(this).balance;
   }

   // This function is called for plain Ether transfers, i.e.
   // for every call with empty calldata.
   receive() external payable { 
       y = msg.value; 
       bal = address(this).balance;
   }

   // Note: It just to test concept. not something advisable to do in 
   //production.
   // call to close function will remove code and storage from the state.
   // but it is still part of the history of the blockchain and probably 
   // retained by most Ethereum nodes 
   // if you sends Ether to removed contracts, the Ether is forever lost
   function close() public {
    me = payable(msg.sender);
   selfdestruct(me);
   } 
}

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