Search code examples
javascriptethereumsolidityweb3jsmetamask

ERC20 token. Cannot get variable nor use methods with deployed contract


I have deployed a ERC20 token contract via Metamask on the Ropsten network. The issue is that I am trying to interact with it via web3. I have followed the answers provided in SO and SE, related to token transfer and method calling.

As you will see, I am not transferring tokens here, but I am using my solidity contract method to set the initial owners of the token. The method in the contract receives 2 arguments, an address and also a tokenId.

When I use the code to transfer a token to the test Metamask account, it fails, in the sense that, if I enter into this test account and import the token, it has none.

For reference, This tokenId, is basically provided by my variable nextTokenIdToAssign, which I call this way:

const tokenIdToAssign = contract.nextTokenIdToAssign.call(function(err, res){
    if(!err) { tokenIdToAssign = res; }
    else { console.log("Error"); }
  }); 

Oddly, when I try to console.log, it returns as undefined. Also, following the question comments, of this question I used

const test = web3.eth.getCode(contractAddress);

It just returns a null. The comments suggest that there is crash in my constructor, or a parent constructor.

Is there some important detail that I am missing here?

The complete code is the following:

const config = require('../config');
var Web3 = require('web3');
var web3 = new Web3();
const infuraApi = (config.infura.infuraApiKey);

//Set a provider (HttpProvider)
if (typeof web3 !== 'undefined') {
  web3 = new Web3(web3.currentProvider);
} else {
  // set the provider you want from Web3.providers
  web3 = new Web3(new Web3.providers.HttpProvider('https://ropsten.infura.io/'+infuraApi));
}

const EthereumTx = require('ethereumjs-tx');
var accountAddressHex = (config.metamaskAccount.metamaskAddressHex);
var accountAddressPrivateKey  = (config.metamaskAccount.metamaskAddressPrivateKey);
var privateKey = new Buffer(accountAddressPrivateKey, 'hex');

var count = web3.eth.getTransactionCount(accountAddressHex);
var contractAddress = (config.solidityContract.contractAddress);
var contractAbiArray = (config.solidityContract.contractABI);
var contract = web3.eth.contract(contractAbiArray).at(contractAddress);

const testSendAccount= "0x...";

const gasPrice = web3.eth.gasPrice;
const gasPriceHex = web3.toHex(gasPrice);
const gasLimitHex = web3.toHex(30000000);
//const tokenTransferAmount = 1;
var tokenIdToAssignHex = contract.nextTokenIdToAssign.sendTransaction( {from: accountAddressHex}, function(err, hash){
        if(!err) { tokenIdToAssignHex = hash;
        console.log(tokenIdToAssignHex); }
        else { console.log("Error"); }
      });


var tokenIdToAssign = contract.nextTokenIdToAssign.call(function(err, res){
        if(!err) { tokenIdToAssign = res; }
        else { console.log("Error"); }
      });
    const test = web3.eth.getCode(contractAddress);

var rawTransaction = {
          "from": accountAddressHex,
          "nonce": web3.toHex(count),
          "gasPrice": gasPriceHex,
          "gasLimit": gasLimitHex,
          "to": contractAddress,
          "value": "0x0",
          "data": contract.setInitialOwner.getData(testSendAccount, tokenIdToAssign, {from: accountAddressHex}), //contract.transfer.getData("0xCb...", 10, {from: "0x26..."}),
          "chainId": 0x03 //Ropsten id is 3, replace with 1 for main
      };

      var tx = new EthereumTx(rawTransaction);
      tx.sign(privateKey);
      var serializedTx = tx.serialize();

      web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), function(err, hash) {
          if (!err) { console.log( 'contract creation tx: ' + hash); }
          else {
              console.log(err);
              return;
            }
      });

EDIT 1

Here is the contract code for the setInitialOwner:

function setInitialOwner(address _to, uint256 _tokenId) public
    onlyOwner
    tokensRemainingToAssign
    tenKLimit (_tokenId)
    yesZeroAddressOwner (_tokenId) 
    notSelfSend (_to, _tokenId) {

        tokenIdToOwner[_tokenId] = _to;
        balanceOfAddress[_to] = balanceOfAddress[_to].add(1);
        emit Assign(_to, _tokenId);

        tokenIndexArray.push(_tokenId);

        uint256 length = balanceOf(msg.sender);
        ownedTokensIndexMapping[_tokenId] = length;
        addressToTokenIdByIndex[msg.sender][length] = _tokenId;

        nextTokenIdToAssign = nextTokenFunc(nextTokenIdToAssign);
       hypeKillsTokensRemainingToAssign = tokensRemainingToAssign.sub(1);
        }

EDIT 2 I have changed the tokenToAssign and added the

var tokenIdToAssignHex = contract.nextTokenIdToAssign.sendTransaction( {from: accountAddressHex}, function(err, hash){
    if(!err) { tokenIdToAssignHex = hash;
    console.log(tokenIdToAssignHex); }
    else { console.log("Error"); }
  });

Solution

  • The problem here was that my nextTokenToAssign variable was not updating properly.

    I used myetherwallet.com to deploy the contract and to check its value. When I deployed the contract, if afterwards I did not call the constructor function, setting the initial value of nextTokenToAssign to 1, it would not update during the successive call to the setInitialOwner function. So the solution simply was to simply call the function.