Migrator.sol 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // contracts/Messages.sol
  2. // SPDX-License-Identifier: Apache 2
  3. pragma solidity ^0.8.0;
  4. pragma experimental ABIEncoderV2;
  5. import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
  6. import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
  7. contract Migrator is ERC20 {
  8. IERC20 public fromAsset;
  9. IERC20 public toAsset;
  10. uint public fromDecimals;
  11. uint public toDecimals;
  12. constructor (
  13. address _fromAsset,
  14. address _toAsset
  15. )
  16. // LP shares track the underlying toToken amount
  17. ERC20("Token Migration Pool", "Migrator-LP") {
  18. fromAsset = IERC20(_fromAsset);
  19. toAsset = IERC20(_toAsset);
  20. fromDecimals = ERC20(_fromAsset).decimals();
  21. toDecimals = ERC20(_toAsset).decimals();
  22. }
  23. // _amount denominated in toAsset
  24. function add(uint _amount) external {
  25. // deposit toAsset
  26. SafeERC20.safeTransferFrom(toAsset, msg.sender, address(this), _amount);
  27. // mint LP shares
  28. _mint(msg.sender, _amount);
  29. }
  30. // _amount denominated in LP shares
  31. function remove(uint _amount) external {
  32. // burn LP shares
  33. _burn(msg.sender, _amount);
  34. // send out toAsset
  35. SafeERC20.safeTransfer(toAsset, msg.sender, _amount);
  36. }
  37. // _amount denominated in LP shares
  38. function claim(uint _amount) external {
  39. // burn LP shares
  40. _burn(msg.sender, _amount);
  41. // send out fromAsset
  42. SafeERC20.safeTransfer(fromAsset, msg.sender, adjustDecimals(toDecimals, fromDecimals, _amount));
  43. }
  44. // _amount denominated in fromToken
  45. function migrate(uint _amount) external {
  46. // deposit fromAsset
  47. SafeERC20.safeTransferFrom(fromAsset, msg.sender, address(this), _amount);
  48. // send out toAsset
  49. SafeERC20.safeTransfer(toAsset, msg.sender, adjustDecimals(fromDecimals, toDecimals, _amount));
  50. }
  51. function adjustDecimals(uint _fromDecimals, uint _toDecimals, uint _amount) internal pure returns (uint) {
  52. if (_fromDecimals > _toDecimals){
  53. _amount /= 10 ** (_fromDecimals - _toDecimals);
  54. } else if (_fromDecimals < _toDecimals) {
  55. _amount *= 10 ** (_toDecimals - _fromDecimals);
  56. }
  57. return _amount;
  58. }
  59. }