0

Isn't it possible to define modifiers in libraries? I'm really asking myself why, because thats some functionality you would need over and over again.

If I would like to hypothetically implement some ownable modifier and let that be used in many of my contracts, I would have to implement it in every of my contracts or use another contract (no library), that provides the modifier.

I've seen https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ownership/Ownable.sol and they implement the functionality also as a contract rather than a function as, I guess, modifiers cannot be accessed from Solidity libraries?

My question: should I now implement my modifiers in my abstract contracts or define modifiers in a contract on its own like the Zeppelin guys did? Whats the up/downsides?

2

Library may define and use modifiers, but it cannot export them. Modifiers are compile-time feature, kind of macros. Modifier code is substituted by compiler to every method that uses this modifier. For complex modifiers this may be a problem, but you may always move modifier's logic into a function (library function, probably), and then refer to this function from within modifier. You may also implement common modifiers in interface to share them among several contracts:

library Foo {
    modifier nonZero (uint x) {
        require (x != 0);
        _;
    }

    function isPrime (uint x) public nonZero (x) returns (bool) {
        // Complicated logic here
    }
}

interface Bar {
    modifier onlyPrime (uint x) {
        require (Foo.isPrime (x));
        _;
    }
}

contract Zoo is Bar {
    function fooBar (uint x) public onlyPrime (x) {
        // Here we know that x is prime!
    }
}
  • Thanks for the concise answer – Curzon Dax Mar 19 at 21:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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