interface_libraries.rst 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. Interfaces and libraries
  2. ========================
  3. Interfaces
  4. __________
  5. An interface is a contract sugar type with restrictions. This type cannot be instantiated; it can only define the
  6. functions prototypes for a contract. This is useful as a generic interface.
  7. .. include:: ../examples/polkadot/interface.sol
  8. :code: solidity
  9. - Interfaces can only have other interfaces as a base contract
  10. - All functions must the ``external`` visibilty
  11. - No constructor can be declared
  12. - No contract storage variables can exist (however constants are allowed)
  13. - No function can have a body or implementation
  14. Libraries
  15. _________
  16. Libraries are a special type of contract which can be reused in multiple contracts. Functions declared in a library can
  17. be called with the ``library.function()`` syntax. When the library has been imported or declared, any contract
  18. can use its functions simply by using its name.
  19. .. include:: ../examples/library.sol
  20. :code: solidity
  21. When writing libraries there are restrictions compared to contracts:
  22. - A library cannot have constructors, fallback or receive function
  23. - A library cannot have base contracts
  24. - A library cannot be a base contract
  25. - A library cannot have virtual or override functions
  26. - A library cannot have payable functions
  27. .. note::
  28. When using the Ethereum Foundation Solidity compiler, libraries are a special contract type and are
  29. called using `delegatecall`. Solang statically links the library calls into your contract code.
  30. This generates larger contract code, however it reduces the call overhead and make it possible to do
  31. compiler optimizations across library and contract code.
  32. Library Using For
  33. _________________
  34. Libraries can be used as method calls on variables. The type of the variable needs to be bound to the
  35. library, and the type of the first parameter of the function of the library must match the type of a
  36. variable.
  37. .. include:: ../examples/library_using_for.sol
  38. :code: solidity
  39. The syntax ``using`` `library` ``for`` `Type` ``;`` is the syntax that binds the library to the type. This
  40. must be specified on the contract. This binds library ``lib`` to any variable with type ``int32[100]``.
  41. As a result of this, any method call on a variable of type ``int32[100]`` will be matched to library ``lib``.
  42. For the call to match, the first argument of the function must match the variable; note that here, `bar`
  43. is of type ``storage``, since all contract variables are implicitly ``storage``.
  44. There is an alternative syntax ``using`` `library` ``for *;`` which binds the library functions to any
  45. variable that will match according to these rules.