When a base class uses a library, do derived classes also use the same library?
For example:
contract A {
using SafeMath for uint256;
...
}
contract B is A {
//is code here using SafeMath for uint256?
}
Ethereum Stack Exchange is a question and answer site for users of Ethereum, the decentralized application platform and smart contract enabled blockchain. It only takes a minute to sign up.
Sign up to join this communityWhen a base class uses a library, do derived classes also use the same library?
For example:
contract A {
using SafeMath for uint256;
...
}
contract B is A {
//is code here using SafeMath for uint256?
}
Yes.
As noted in the official docs,
When a contract inherits from multiple contracts, only a single contract is created on the blockchain, and the code from all the base contracts is copied into the created contract.
This copying of code includes using...for
statements, which apply to the contract as a whole rather than specific functions.
You can verify this for yourself by testing contract B for the behavior that the library provides to contract A. In this example you can try to cause an overflow in a test on contract B and see that it throws an error instead, if the library is properly included and linked with B's parent type, contract A.
You can also see this in OpenZeppelin's implementation of ERC20 tokens.
You are right
pragma solidity ^0.4.24;
library Bytes32 {
function toString(bytes32) public pure returns (string) {
return "1";
}
}
contract Parent {
using Bytes32 for bytes32;
function bar() public pure returns(string) {
return bytes32(0).toString(); // returns "1"
}
}
contract Child is Parent {
function foo() public pure returns(string) {
return bytes32(0).toString(); // returns "1"
}
}