0

I am trying to make a simple smart contract where you can create a car. It creates a new contract that allows you to change the name of the car. I would like only the mechanics to change the name of the car and I would like to have the becMechanic() function in the CarFactory contract so you don't need to become a mechanic every time you are changing a name. So the problem is that I can't access the mapping mechanics in the Car contract and I don't know how to do it.

contract CarFactory {
Car[] deployedCars;
mapping(address=>bool) mechanics;

function createCar(string memory _name) public {
    Car newCar=new Car(_name);
    deployedCars.push(newCar);
    
}
function getDeployedCars() public view returns (Car[] memory) {
    return deployedCars;
}
function becMechanic() public {
    mechanics[msg.sender]=true;
}}





contract Car {

string carName;

constructor(string memory _name){
    carName =_name;
}

function changeName(string memory name) public {
    require(mechanics[msg.sender]==true);
    carName=name;
}

}

1 Answer 1

1
  1. In CarFactory added function getMechanic
  2. In Car construtor added parameter referring to CarFactory contract
  3. In requiry operator used call of getMechanic function of parent CarFactory contract
pragma solidity 0.6.0;

contract CarFactory {

  Car[] deployedCars;

  mapping(address=>bool) mechanics ;

 function createCar(string memory _name) public {
    Car newCar=new Car(this, _name);
    deployedCars.push(newCar);   
 }

 function getDeployedCars() public view returns (Car[] memory) {
    return deployedCars;
 }

 function becMechanic() public {
    mechanics[msg.sender]=true;
 }

 function getMechanic(address  _user) public view returns(bool) {
    return(mechanics[_user]) ;
 }

}


contract Car {

 CarFactory  factory ;
     string  carName;

  constructor(CarFactory  _factory, string memory _name) public {

    factory = _factory ;
    carName = _name;
  }

  function changeName(string memory name) public {

    require(factory.getMechanic(msg.sender)==true);

                    carName=name;
  }

}

1
  • Ayo thanks so much dude.Really appreciate it
    – zzz
    Jan 13, 2022 at 19:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.