[Ethereum] How to import and compile contracts of different versions solidity

compilationcompilerimportremixsolidity

How to import and compile contracts of different versions using solidity in remix?

When I import a contract I get this error:

ParserError: Source file requires different compiler version (current
compiler is 0.8.3+commit.8d00100c.Emscripten.clang) – note that
nightly builds are considered to be strictly less than the released
version –>
https://github.com/ConsenSysMesh/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol:1:1:
| 1 | pragma solidity ^0.4.23; |

I am importing a contract from open zepplin. The contract is MathSafe and it uses pragma solidity 0.4.23;. My local contract uses 0.8.3.

This is how my code looks like on remix:

// SPDX-License-Identifier: MIT

pragma solidity >=0.4.23 <0.9.0;

import "https://github.com/ConsenSysMesh/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol";

contract StakingToken is ERC20, Ownable{
    using SafeMath for uint256;
    
    constructor(){}
    
    function addNumber(uint256 number) public view returns(uint256) {
        return number.add(5);
    }
}

Best Answer

First you have to decide which solidity version you want to choose for your project. Its not necessary that you choose the latest version(my opinion). You have to consider the solidity version of external packages that you wish to use in your project.

For example, if you are using Openzeppelin, you can find different versions here: @openzeppelin/contracts.

Here is the updated code compatible with Solidity:0.8.3 with Openzeppelin:

// SPDX-License-Identifier: MIT
pragma solidity >=0.4.23 <0.9.0;

import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol";

contract StakingToken is ERC20, Ownable{
    using SafeMath for uint256;
    
    constructor()ERC20("MyCoin", "XMC"){}
    
    function addNumber(uint256 number) public pure returns(uint256) {
        return number.add(5);
    }
}
Related Topic