1

In the http://truffleframework.com/tutorials/pet-shop example, there is the following contract, and the function adopt(uint petId) has only one parameter.

contract Adoption {
    address[16] public adopters;

    function adopt(uint petId) public returns (uint) {
        require(petId >= 0 && petId <= 15);
        adopters[petId] = msg.sender;
        return petId;
    }

    function getAdopters() public returns (address[16]) {
        return adopters;
    }
}

However, in the javascript code app.js, the handleAdopt function call the contract function using the following code.

  App.contracts.Adoption.deployed().then(function(instance) {
    adoptionInstance = instance;
    return adoptionInstance.adopt(petId, {from: account});
  })

The function is called with the extra object {from: account}. Why? And is this parameter discarded in the solidity code?

BTW, there is an undefined global variable web3? Is the value be assigned by the MetaMask extension?

0

The extra argument object {from: account} specifies details about how to send the transaction. The fields in this argument object are not passed to the Solidity function.

In your example it specifies which account to make the transaction from. In the context of the code you're talking about, account refers to accounts[0] which is the first account available in the web3 instance you have access to. If you remove this argument, the from account defaults to accounts[0].

This web3 doc shows the other fields you can include in the extra argument object. Eg if you wanted to specify the maximum gas the transaction should use it could look like this adoptionInstance.adopt(petId, {from: accounts[0], gas: 1000000})

To answer your second question, this bit of the tutorial has a code snippet that attempts to get the web3 object from different sources. It checks if it has been injected, which is what MetaMask does if it is installed and unlocked, if it can't find an injected web3 object, it will try to use a local web3 instance available at http://localhost:7545, the ip that Ganache uses. So make sure you either have MetaMask installed and unlocked or Ganache running to get access to a web3 object.

| improve this answer | |

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.