Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smart contract Ethereum - How to recreate same contract after used selfDestruct()

Is it possible to destroy (using selftDestruct function) and generate the same contract at the same time ?

We assume that the first contract is to have 1Eth and then withdraw all eth to another erc20 address, after the complete withdrawal, the first contract calls the selfdestruct function and then the same contract is redeployed, and that in a loop.

Maybe the simply way is to use a conditional function?

like image 265
Creeks Avatar asked Jan 20 '26 14:01

Creeks


1 Answers

Not possible "at the same time", need to do it in separate transactions.

selfdestruct prevents later operations on the contract from being executed, and flags the contract for deletion.

selfdestruct stops the execution in its current scope, and flags the contract for deletion.

However, the EVM doesn't delete its bytecode until the end of processing of the transaction. So you won't be able to deploy new bytecode to the same address until the next tx. But you're still able to perform calls on the to-be-destructed contract.

pragma solidity ^0.8;

contract Destructable {
    function destruct() external {
        selfdestruct(payable(msg.sender));
    }
}

contract Deployer {
    function deployAndDestruct() external {
        Destructable destructable = new Destructable{salt: keccak256("hello")}();
        destructable.destruct();

        // The second deployment (within the same transation) causes a revert
        // because the bytecode on the desired address is still non-zero
        Destructable destructable2 = new Destructable{salt: keccak256("hello")}();
    }
}
pragma solidity 0.8.17;

contract Destructable {
    uint public number = 1;

    function destruct() external {
        selfdestruct(payable(msg.sender));
        number++; // not executed after selfdestruct
    }
}

contract Caller {
    Destructable destructable;

    constructor(Destructable _destructable) {
        destructable = _destructable;
    }

    function executeSequence() external {
        destructable.destruct();
    
        // successfully call after the selfestruct was initiated
        uint returnedNumber = destructable.number();
        require(returnedNumber == 1);
    }
}
like image 132
Petr Hejda Avatar answered Jan 22 '26 07:01

Petr Hejda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!