concept library in category ethereum

appears as: libraries, library, A library, library
Building Ethereum Dapps: Decentralized applications on the Ethereum blockchain

This is an excerpt from Manning's book Building Ethereum Dapps: Decentralized applications on the Ethereum blockchain.

  • DELEGATECALL—This operator allows the calling contract to send a message to an external contract but execute the related code in the context of the caller. This operator is especially useful for the creation of libraries of shared code that multiple contracts can access.
  • Although you can avoid code duplication by factoring a good class hierarchy where contracts at the bottom reuse function implementations located in their base classes, often common shareable logic isn’t specific to the domain of a contract hierarchy and has a more generic purpose. For example, functions that manipulate low-level data structures, such as arrays, byte arrays, or strings, in a generic way might be useful in any contract. The naive way to import such functionality is to copy and paste the required functions from a function repository into the contracts that need them. But there’s a much smarter way. Enter libraries.

    7.5.2. Deployed libraries

    True code reuse takes place when only one instance of the library is deployed on the network and all contracts accessing it reference it through its deployment address (conceptually the same as a contract address). Once deployed, the functions of a library are exposed with implicit external visibility to all the contracts referencing it. The usual way of calling a deployed library from a contract is to define a local abstract contract that matches the signature of the deployed library. Then you communicate with the library through this local abstract contract, which acts as a strongly typed proxy to the library, as shown in the following listing. The alternative would be to invoke the library functions directly through call(), but by doing so, you wouldn’t guarantee type safety.

    Figure 13.4. When you introduce a proxy to the library, client contracts no longer directly reference an instance of the library; they communicate with the proxy (or library dispatcher), which gets from another contract the latest valid address of the library and then forwards calls to the valid instance.