Selfdestruct

Solidity

Définition

Fonction pour détruire un contrat et envoyer son ether restant à une adresse. Le bytecode reste sur la blockchain (historique immuable) mais les appels futurs échouent. Coûte du gas négatif (remboursement) mais DÉPRÉCIÉ depuis EIP-6049. Ne devrait plus être utilisé dans les nouveaux contrats. Alternative : désactiver le contrat avec un flag.

Version anglaise

Function to destroy a contract and send remaining ether to an address. Bytecode remains on blockchain (immutable history) but future calls fail. Costs negative gas (refund) but DEPRECATED since EIP-6049. Should no longer be used in new contracts. Alternative: disable contract with flag.

Exemple de Code

contract Deprecated {
  address public owner;

  constructor() {
    owner = msg.sender;
  }

  // ⚠️ DÉPRÉCIÉ : ne plus utiliser
  function destroy() public {
    require(msg.sender == owner);
    selfdestruct(payable(owner)); // Envoie l'ether et détruit
  }
}

// ✅ Alternative moderne
contract Modern {
  bool public disabled;

  function disable() public onlyOwner {
    disabled = true;
  }

  modifier whenNotDisabled() {
    require(!disabled, "Contract disabled");
    _;
  }
}

Termes Liés

Pratique ce concept sur Solingo

Maîtrise Selfdestruct avec des exercices interactifs et un IDE intégré.

Commencer gratuitement