FURTHER_EDITS: Here's the code to validate selfdestruct's existence in the contract.
// substite your path here
const contractPath = path.resolve(__dirname, "contracts", "Attack.sol");
const contractCode = fs.readFileSync(contractPath, "utf8");
// >=0 is true // -1 is false
const selfdestructExists = (contractCode.search("selfdestruct") >= 0 ? true : false);
console.log('selfdestruct exists:', selfdestructExists);
// if true then initiate the test...
=========================================
EDITS after additional clarity from zak100: "I have shown a smart contract (SC) named Attack, it is stored in a fie say, attack.sol, how can I use web3.js to check if the SC contains selfdestruct opcode or not?".
NEW INPUT: If your intent is to instantiate a contract's object only if it contains selfdestruct then you could very well leverage JavaScript packages path & fs (a) to load all contract files available and (b) by then checking for the occurrence of the string 'selfdestruct' within each file's content. (c) If occurrence found then create that object - this one needs to be explored a bit further.
All in all, my point is to not be dependent on web3 alone and leverage path and fs for your requirement.
const path = require("path");
const fs = require("fs");
Hope this helps. Again, please clarify further in case I have missed the ask.
Immediate answer:
Get bytecode. Get opcode from bytecode. Search for 'SelfDestruct' in the opcodes.
For bytecode
await web3.eth.getCode(etherStore.address);
NOTE: Ensure that you are clear between the deployment bytecode and runtime bytecode. Refer this thread on ESE for clarity.
- For opcode: Use Etherscan based functionality here.
**Now, what's the requirement?
I see that you are trying out the selfdestruct hack in solidity-by-example to throw a contract's balance off-balance.
If that's the case, your attacking contract is the one that will have selfdestruct. The victim/target contract's address should simply suffice as that's the value you will pass to the selfdestruct call to your attacking contract.
Your attacking contract will need a certain amount of ETH to feed the victim contract. Note that in this hack, you are actually giving ETH to the victim contract. Intent is to mess the contract's balance such that any balance dependent code in that victim contract goes for a toss.
For the above intent, you simply need the victim contract's address. That itself should suffice.
Hope this helps. If not, please clarify your ask.
If testing's the intent then the Attacker contract becomes your test-bed, your driver. Victim contract addresses become the input for your Attacker contract - the addresses would suffice as those would be the input you would pass to your Attacker's attack method, the eventual parameter to your selfdestruct.
I will leave it at that. Good luck!
– TaherBorsadwala Jan 02 '22 at 04:46Error: Cannot find module '~/Truffle_programs/search_opcode/contracts', please guide me.
– zak100 Jan 02 '22 at 05:34