0

I want to make a function that has extra steps if called by one contract and not another. For example, I have function doSomething declared in contract A, which is inherited by contracts B and C. I want to add some code to the function that will check which contract is calling it and if it's contract B, do something extra, like add one to some variable. Pseudocode:

function doSomething(){
    if(contract == B) {
       randomVariable++;
    }
    do something;
}

I don't want to write the function separately for each contract. Is this possible?

1 Answer 1

1

Since you are using inheritance, the same function is basically copied to both B and C.

You have at least three alternative approaches:

  1. Parameters to the function. So use some parameter which changes the logic
  2. Checking the contract address. Since B and C are deployed to different addresses, you can change the logic based on the current contract's address (compare to a variable, and set the variable's value after deployment). Not a very nice nor clean approach
  3. Use function overriding. Contract A can have a function doStuff which is a virtual and abstract function - no implementation needed. Then contract B and C have different implementation of the same function. And in the original function doSomething you simply call doStuff which then uses the right implementation (well, there is only one implementation for it, since the other implementation is in another contract). This is probably the cleanest approach.
2
  • if I use the virtual function, will a user be able to just call the original function?
    – Antheloth
    Feb 6, 2022 at 17:11
  • No. There is always just one function which is being called. Feb 6, 2022 at 19:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.