ERC20Wrapper.sol 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.6.0) (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 See {ERC20-decimals}.
  22. */
  23. function decimals() public view virtual override returns (uint8) {
  24. try IERC20Metadata(address(underlying)).decimals() returns (uint8 value) {
  25. return value;
  26. } catch {
  27. return super.decimals();
  28. }
  29. }
  30. /**
  31. * @dev Allow a user to deposit underlying tokens and mint the corresponding number of wrapped tokens.
  32. */
  33. function depositFor(address account, uint256 amount) public virtual returns (bool) {
  34. SafeERC20.safeTransferFrom(underlying, _msgSender(), address(this), amount);
  35. _mint(account, amount);
  36. return true;
  37. }
  38. /**
  39. * @dev Allow a user to burn a number of wrapped tokens and withdraw the corresponding number of underlying tokens.
  40. */
  41. function withdrawTo(address account, uint256 amount) public virtual returns (bool) {
  42. _burn(_msgSender(), amount);
  43. SafeERC20.safeTransfer(underlying, account, amount);
  44. return true;
  45. }
  46. /**
  47. * @dev Mint wrapped token to cover any underlyingTokens that would have been transferred by mistake. Internal
  48. * function that can be exposed with access control if desired.
  49. */
  50. function _recover(address account) internal virtual returns (uint256) {
  51. uint256 value = underlying.balanceOf(address(this)) - totalSupply();
  52. _mint(account, value);
  53. return value;
  54. }
  55. }