1

I am having an admin in my contract who can do certain things. Here is the contract

function changeAdmin(address admin_) public {
    if (msg.sender != admin) revert();
    potentialAdmin = admin_;
}

function becomeAdmin() public {
     if(potentialAdmin==msg.sender) admin = msg.sender;
}

address public admin;

constructor() public{
      admin = msg.sender;
}

I am trying to test this using truffle framework. For this I need to pass an admin name from the contract creator and then call becomeAdmin from the address passed in first step. I am not able to clear this. Here is my test case


const te = artifacts.require("MyContract");

contract("Contract test cases", function() {

  it("should be able to change admin", async function() {

    var token = await te.deployed();

    var accounts = await web3.eth.getAccounts();

    var newAdmin = accounts[1];
    await token.changeAdmin.call(newAdmin, {from : accounts[0]});
    await token.becomeAdmin.call({from: newAdmin});

    var adminChanged = await token.admin.call();
    assert.equal(adminChanged, accounts[1], 'Admin set is wrong');

  });

});

Is the way of calling contract by passing different from addresses correct ?

2

In order to execute a state-changing function within a transaction, you need to use send.

On Truffle you can also omit it and let Truffle choose the default:

  • call for constant functions (either pure or view)
  • send for non-constant functions (neither pure nor view)

So in short, you need to change this:

    await token.changeAdmin.call(newAdmin, {from : accounts[0]});
    await token.becomeAdmin.call({from: newAdmin});

To this:

    await token.changeAdmin.send(newAdmin, {from : accounts[0]});
    await token.becomeAdmin.send({from: newAdmin});

Or to this:

    await token.changeAdmin(newAdmin, {from : accounts[0]});
    await token.becomeAdmin({from: newAdmin});
| improve this answer | |
  • 1
    Thanks, much appreciated :) You made my day ! – Prashant Singh May 25 at 16:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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