1
votes

** Updated based on comment

When interacting with the contract and calling the function directly using the 'contract address: ' directly from the output of the truffle migration output the error is also invalid address.

-

New to Solidity contracts and web3.js - (although I have been trying to get this working for a number of weeks now!!)

I am using react.js, truffle-contract and web3 to create a Dapp and connect to my smart contract from Ganache. I am also managing my application via webpack.

I have written a simple contract in Solidity (versions set out below) - and can connect to the contract without any problem from the truffle console.

When connecting to the contract through a simple (for this demo) enroll() function I recieve an Error: invalid address I have re-written the code in a number of ways now and always receive the same error regardless.

After viewing lots of posts on here I understand that a fairly common issue when doing so is that I need to set the 'default' - which I have done both when I connect to web3 for the first time in my componentDidMount function and also when connecting to the contract via the contract.defaults function. This also has not made a difference so far.

Any thoughts as to what I am doing wrong here would be greatly appreciated!

relevant versions are below

"web3": "^1.2.1", "webpack": "^4.20.2", "react": "^16.2.0",

"truffle-contract": "^3.0.4",

"solc": "0.4.18",

Below is the page attempting to connect to the contract

    componentDidMount = () => {
    if(this.state.web3MetaON == false && this.state.accUnlock == false) {

      if (typeof web3 != 'undefined') {

        this.web3Provider = web3.currentProvider
        web3 = new Web3(web3.currentProvider)
        this.setState({web3MetaON: true})
        const accountID = web3.eth.accounts[0];
        web3.eth.defaultAccount = accountID;
        console.log('Window opening in older browser') 

        // check if accountID is available
        if(accountID !== null || accountID !== undefined) {
        this.setState({accUnlock: true})
        this.setState({account: accountID})

        this.loadDataContract(accountID)

    }
    else {
        console.log('Error on accessing account')
          this.setState({accUnlock: false})
    }
  }
    else {
          window.alert("Please connect to Metamask.")
          this.setState({web3MetaON: false})
          // ::TO-DO method to invoke retry after 2 seconds
        }
      }

      // Below loads web3 and sets state if browser
      // is and a modern ethereum browser 
      else if (window.ethereum && this.state.web3MetaON == false && this.state.accUnlock == false) {
        window.web3 = new Web3(ethereum)
        try {
          // Request account access if needed
          const accountID = ethereum.enable()
          web3.eth.sendTransaction({/* ... */})
          // setting state to accountID
          this.setState({account: accountID})
          this.setState({accUnlock: true})

          console.log('Window opening in modern browser')

        } catch (error) {
          console.log(error, 'Modern Browser failed')
          this.setState({web3MetaON: false})
        }
        console.log('Non-Ethereum browser detected. You should consider trying MetaMask!')
      }
    };

  loadDataContract = () =>  {
      const contract = TruffleContract(DataAccess)
      contract.setProvider(this.web3Provider)
      contract.defaults({from: this.web3Provider});

      // deploy contract
      contract.deployed().then((DataAccessInstance) => {
              this.DataAccessInstance = DataAccessInstance;
              DataAccessInstance.enroll()
                }).then(data => {
                window.alert("contract loaded.", data)

              }).catch(err => console.log("data load data this is ", err))
            };

Below is a section of the solidity contract



contract DataAccess {

    // This declares a new complex type which
    // will be used for variables
    // it represents a single usersData
    struct DataLocation {
        string ownerName;
        string ownerID;
        string url;
        string dateOfAccess;
        string timeOfAccess;
        uint accessCount;
        uint index;
    }

    struct Index {
        uint indexLocation;
    }

    // store Data that has a location
    mapping(address => DataLocation) private datastores;

    mapping (address => uint) private balances;

    // store datalocation Count
    uint public datalocationsCount;

    // userIndex stors location of pointers
    address[] public userIndex;

    // stored event
    event storedEvent (
        uint indexed _dataLocationId
    );

    // event for new data location 
    event LogNewData   (
        address indexed dataAddress, 
        string ownerName,
        string url,
        string ownerID,
        string dateOfAccess,
        string timeOfAccess,
       // uint accessCount,
        uint index);


    // event for new updated data  location 
    event LogUpdateData   (
        address indexed dataAddress,
        string ownerName,
        string url,
        string ownerID,
        string dateOfAccess,
        string timeOfAccess,
     //   uint accessCount,
        uint index);

    function enroll() public returns (uint){
      /* Set the sender's balance to 1000, return the sender's balance */
        address user = msg.sender;

        balances[user] = 1000; 
        return user.balance;
    }

When trying to rewrite the contract based on feedback the result is still an error of invalid address.


  loadDataContract = () =>  {

      const contract = TruffleContract(DataAccess)
      contract.setProvider(this.web3Provider)
      contract.defaults({from: this.web3Provider});


      // initial function
      contract.at('0x8a4A12479486A427109e964e90CaEB5798C13A01').enroll().then((Output) => {
        this.setState({value: Output})
      }).catch(err => console.log("Enroll function error ", err))

    };
1

1 Answers

0
votes

You should use contract.new() to deploy new contract. If you wand to use the contract that is already deployed, use contract.at(<address of deployed contract>).

contract.deployed() is used for example for tests and it returns the contract deployed in migrations script when you run truffle test command.