ERC20Wrapper.sol 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts v4.4.0-rc.1 (token/ERC20/extensions/ERC20Wrapper.sol)
  3. pragma solidity ^0.8.0;
  4. import "../ERC20.sol";
  5. import "../utils/SafeERC20.sol";
  6. /**
  7. * @dev Extension of the ERC20 token contract to support token wrapping.
  8. *
  9. * Users can deposit and withdraw "underlying tokens" and receive a matching number of "wrapped tokens". This is useful
  10. * in conjunction with other modules. For example, combining this wrapping mechanism with {ERC20Votes} will allow the
  11. * wrapping of an existing "basic" ERC20 into a governance token.
  12. *
  13. * _Available since v4.2._
  14. */
  15. abstract contract ERC20Wrapper is ERC20 {
  16. IERC20 public immutable underlying;
  17. constructor(IERC20 underlyingToken) {
  18. underlying = underlyingToken;
  19. }
  20. /**
  21. * @dev Allow a user to deposit underlying tokens and mint the corresponding number of wrapped tokens.
  22. */
  23. function depositFor(address account, uint256 amount) public virtual returns (bool) {
  24. SafeERC20.safeTransferFrom(underlying, _msgSender(), address(this), amount);
  25. _mint(account, amount);
  26. return true;
  27. }
  28. /**
  29. * @dev Allow a user to burn a number of wrapped tokens and withdraw the corresponding number of underlying tokens.
  30. */
  31. function withdrawTo(address account, uint256 amount) public virtual returns (bool) {
  32. _burn(_msgSender(), amount);
  33. SafeERC20.safeTransfer(underlying, account, amount);
  34. return true;
  35. }
  36. /**
  37. * @dev Mint wrapped token to cover any underlyingTokens that would have been transfered by mistake. Internal
  38. * function that can be exposed with access control if desired.
  39. */
  40. function _recover(address account) internal virtual returns (uint256) {
  41. uint256 value = underlying.balanceOf(address(this)) - totalSupply();
  42. _mint(account, value);
  43. return value;
  44. }
  45. }