Emily Kuo
Emily Kuo

Reputation: 101

Why is the open zeppelin Safe Math contract not importing?

I am using the following contract from Ethernaut and did sudo npm i @openzeppelin/contracts

pragma solidity 0.6.0;

import "@openzeppelin/contracts/math/SafeMath.sol";

contract CoinFlip {

  using SafeMath for uint256;
  uint256 public consecutiveWins;
  uint256 lastHash;
  uint256 FACTOR = 57896044618658097711785492504343953926634992332820282019728792003956564819968;

  constructor() public {
    consecutiveWins = 0;
  }

  function flip(bool _guess) public returns (bool) {
    uint256 blockValue = uint256(blockhash(block.number.sub(1)));

    if (lastHash == blockValue) {
      revert();
    }

    lastHash = blockValue;
    uint256 coinFlip = blockValue.div(FACTOR);
    bool side = coinFlip == 1 ? true : false;

    if (side == _guess) {
      consecutiveWins++;
      return true;
    } else {
      consecutiveWins = 0;
      return false;
    }
  }
}

However, I'm still getting this error regarding SafeMath contract not being found even after installing all the openzeppelin contracts: Error: Could not find @openzeppelin/contracts/math/SafeMath.sol from any sources

My configurations below:

Truffle v5.1.39 (core: 5.1.39)
Solidity - 0.6.0 (solc-js)
Node v16.13.1
Web3.js v1.2.1

Upvotes: 0

Views: 1860

Answers (2)

Tanjin Alam
Tanjin Alam

Reputation: 2496

The problem is your version selection.

import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/solc-0.6/contracts/utils/SafeCast.sol";

This one is for solidity 0.6.0 the version you are currently using.

but you are using

https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol

which is for solidity >= 0.8.0

Upvotes: 0

sirroger
sirroger

Reputation: 316

When you install openzeppelin contracts with npm as you did, you install the version with the current tag. The current tag is right now at Solidity version ^0.8.0. Since version 0.8+, you don't need to use SafeMath anymore as it is implemented on the language level.

As you are using Solidity version 0.6 you should also install the openzeppelin package for this version. This should be 3.4.1. You can install this version with the following command:

npm i @openzeppelin/[email protected]

The better solution, however, would be to update your contract to solidity version 0.8+, use the current openzeppelin implementation and remove SafeMath library.

Upvotes: 1

Related Questions