1

A library is deployed separately and a contract is linked to it. All internal library functions are copied to the contract using it. But what about public functions?

If the library declares struct Storage and public functions make changes to the storage, is it safe to assume no third party can call those functions and that they are accessible only for the contract using the library?

library Friends {

  struct Storage {
    address[] friendsList;
  }

  function addFriend(
    Storage storage self, 
    address friend
  ) public { // <- can anyone but MyContract make changes?
    self.push(friend);
  }
}

contract MyContract {
  using Friends for Friends.Storage;

  Friends.Storage friendsStorage;
}
1

Good question. I think what you are missing is the point that libraries have no state themselves. They are basically contracts deployed at a certain address, but have no variables in their storage. All data is passed to the library by the calling contract using DELEGATECALL. This operation basically calls another contract's function but within its own context, meaning all storage memory is used from the calling contract.

That means a library can be used by as many contracts that want to use it without security problems. In fact that is the main reason to use a library, you deploy it once and use it with many other contracts. So to actually use the addFriend function in your example you would have to add a function to your contract like

library Friends {
  struct Storage {
    address[] friendsList;
  }

  function addFriend(
    Storage storage self, 
    address friend
  ) public {
    self.friendsList.push(friend);
  }
}

contract MyContract {
  using Friends for Friends.Storage;
  Friends.Storage friendsStorage;

  function addFriend(address friend) public {
        friendsStorage.addFriend(friend);
        // alternative without using for: Friends.addFriend(friendsStorage, friend);
  }
}

See https://solidity.readthedocs.io/en/latest/contracts.html#libraries for more details.

| improve this answer | |

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.