ERC20Wrapper.sol 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 private immutable _underlying;
  17. constructor(IERC20 underlyingToken) {
  18. require(underlyingToken != this, "ERC20Wrapper: cannot self wrap");
  19. _underlying = underlyingToken;
  20. }
  21. /**
  22. * @dev See {ERC20-decimals}.
  23. */
  24. function decimals() public view virtual override returns (uint8) {
  25. try IERC20Metadata(address(_underlying)).decimals() returns (uint8 value) {
  26. return value;
  27. } catch {
  28. return super.decimals();
  29. }
  30. }
  31. /**
  32. * @dev Returns the address of the underlying ERC-20 token that is being wrapped.
  33. */
  34. function underlying() public view returns (IERC20) {
  35. return _underlying;
  36. }
  37. /**
  38. * @dev Allow a user to deposit underlying tokens and mint the corresponding number of wrapped tokens.
  39. */
  40. function depositFor(address account, uint256 amount) public virtual returns (bool) {
  41. address sender = _msgSender();
  42. require(sender != address(this), "ERC20Wrapper: wrapper can't deposit");
  43. SafeERC20.safeTransferFrom(_underlying, sender, address(this), amount);
  44. _mint(account, amount);
  45. return true;
  46. }
  47. /**
  48. * @dev Allow a user to burn a number of wrapped tokens and withdraw the corresponding number of underlying tokens.
  49. */
  50. function withdrawTo(address account, uint256 amount) public virtual returns (bool) {
  51. _burn(_msgSender(), amount);
  52. SafeERC20.safeTransfer(_underlying, account, amount);
  53. return true;
  54. }
  55. /**
  56. * @dev Mint wrapped token to cover any underlyingTokens that would have been transferred by mistake. Internal
  57. * function that can be exposed with access control if desired.
  58. */
  59. function _recover(address account) internal virtual returns (uint256) {
  60. uint256 value = _underlying.balanceOf(address(this)) - totalSupply();
  61. _mint(account, value);
  62. return value;
  63. }
  64. }