EOS Dapp Programming

Yes sure, Scatter happens to be buggy sometimes, I understand it is in the process to be improved… :hammer_and_wrench: … but it’s fine, I will move forward with the course and do my best to do the exercises. In the meantime, I will google the JSON “unexpected token” error and if needed, check with the EOSIO Developers Community.

Right now, I am not on my Ubuntu laptop, so I will try tomorrow to close/open and refresh Scatter to see the account displayed. I am quite sure that my nodeos was up and running, but I will check again.

Thanks!

1 Like

Hi! I moved forward with the course, but I am still getting the “Unexpected token” error:

Unexpected_token_26Sep20

Here is a screenshot of my dApp window:

Now following the course and Filip’s instructions, I added the addDog() function in my code.

When I try to insert a dog name and the dog age in the text boxes and click the Add button (the Add Dog feature of the dApp), I am getting another error:

transact_error

I checked line 94 of my JS code: eos.transact({ and verified the whole addDog() function by comparing it to Filip’s code in the video, but I didn’t spot any error.

I reached the end of the Add Dog Table Update section. I would like to do the Assignment - Remove Dog exercise, but I cannot test the result of my code in my dApp, because of these two errors, that don’t allow me to see and refresh the list of dogs and to use the Add Dog feature, so I cannot test my code.

Here is my main.js code now:

ScatterJS.plugins( new ScatterEOS() );

const network = ScatterJS.Network.fromJson({
    blockchain:'eos',
    chainId:'cf057bbfb72640471fd910bcb67639c22df9f92470936cddc1ade0e2f2e7dc4f',
    host:'127.0.0.1',
    port:8888,
    protocol:'http'
});

const contractConfig = {
  code: "dogctrissuer",
  scope: "dogctrissuer",
  dogTableName: "dogs",
  balancesTableName: "balances",
  symbol: "DOGCOIN"
}

const scatter = ScatterJS.scatter;
var eos;
var rpc; //fetch data from blockchain
var account;
//initialize function to scatter and webpage functions
ScatterJS.connect('DogDapp', {network}).then(connected => {
  //check if scatter is running
  if(!connected) return alert("No Scatter Detected");
  console.log("Scatter Connected");


  window.ScatterJS = null;


});//end ScatterJS.connect function

function logIn(){
  //scatter login popup window
  scatter.login({accounts: [network]}).then(function(){
    account = scatter.account('eos');
    //get data from blockchain into a Json
    rpc = new eosjs_jsonrpc.JsonRpc(network.fullhost());
    //initialize eos object to create transactions
    eos = scatter.eos(network, eosjs_api.Api, {rpc});
    //get table data functions
    getAccount();
    getBalance();
    getDogs();

  });

}//end logIn
function logOut(){
  scatter.logout({accounts: null}).then();
}//enf logOut

//get name account
function getAccount(){
  $("#Account").empty();
  var AccId = document.getElementById("Account");
  var AccName = account.name;
  AccId.innerHTML = AccName;
}//end getAccount

//function to get data from blockchain tables
function getDogs(){
  rpc.get_table_rows({
    json: true,
    code: contractConfig.code,
    scope: contractConfig.scope,
    table: contractConfig.dogTableName,
    index_position: 2,
    key_type: "name",
    lower_bound: account.name,
    upper_bound: account.name
  }).then(function(res){
    console.log(res);
    populateDogList(res.rows);
  })
}//end getDogs()

function populateDogList(dogs){
  $("#doglist").empty();
  var ul = document.getElementById("doglist");
  for (var i = 0; i < dogs.length; i++) {
    var li = document.createElement("li");
    li.appendChild(document.createTextNode(dogs[i].id + ": " + dogs[i].dog_name + ", " + dogs[i].age));
    ul.appendChild("li");
  }
}

function addDog(){
  var dogName = $("#dog_name").val();
  var dogAge = $("#dog_age").val();

  eos.transact({
    actions: [{
      account: contractConfig.code,
      name: 'insert',
      authorization: [{
        actor: account.name,
        permission: account.authority
      }],
      data: {
        owner: account.name,
        dog_name: dogName,
        age: dogAge
      }
    }]
  }, {
    blocksBehind: 3,
    expireSeconds: 30
  }).then(function(res){
    // SUCCESSFUL ADD
    getDogs();
  }).catch(function(err){
  alert(err);
  })
}

//wait until html page is loaded and apply some logic to objects
$(document).ready(function() {
  //Add dog button function
  $("#add_button").click(addDog);
  //Delete dog button function
  $("#del_button").click(deleteDog);
  //Delete ALL button function
  $("#del_all_button").click(deleteAll);
  //Deposit coins into contract
  $("#deposit_button").click(deposit_coin);
  //logIn and logOut buttons
  $("#login_button").click(logIn);
  $("#logout_button").click(logOut);
});

Your help would be appreciated @thecil @ivga80 @filip

Please kindly note that I submitted the “Unexpected token < in JSON at position 0” issue to the EOS.IO Stack Exchange forum. Let’s see if I get an answer soon.

Hello @swisscrypto, glad to know your ok. sorry for the long delay.

Now in your code your probably have an error on addDog() function, in your data: should be listed in the same exactly way that is in your table.
I tried with this order and it works for now:
data: { dog_name: dogName, age: dogAge, owner: account.name }

Remember to check on the cleos if the account have any dog.

cleos get table <account> <scope> <table-name>

Also, you can not add dogs with the contract owner (dogctrissuer if that your contract deployed account). So I advice to create another account (example: bob), transfer some dogecoins to that account and try it on your dapp.

If you have any more questions, please let us know so we can help you! :slight_smile:

Carlos Z.

1 Like

Hi Carlos, thank you for your reply!

I listed my data: in the same order as you suggested:

data: {
    dog_name: dogName,
    age: dogAge,
    owner: account.name
}

Unfortunately, I am still getting the same errors:

dogdapp_errors

The Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 error when I am loading the dapp homepage.

The Uncaught TypeError: Cannot read property 'transact' of undefined error when I am trying to use the dapp to add a dog.

I posted the Unexpected token issue in the EOS.IO Stack Exchange and got the following answer: “That unexpected token < is a strong clue that the response was HTML instead of JSON. While you expected to get JSON”.
I also saw this suggestion when I googled the error.
But I don’t know how to correct my code accordingly and to make the dapp work properly, so that I can see my dogs and add them.

I checked on the cleos, and I don’t have any account associated with my public/private keypair:

cleos get accounts EOS5dnHK432yiTvnmavNvPQ7QpjMJkxp6nRgk8XAD58v1RU46RfDt { "account_names": [] }

I cannot find the gemeos account I created in May associated with my new public key EOS5dnHK432yiTvnmavNvPQ7QpjMJkxp6nRgk8XAD58v1RU46RfDt.

This is what I get when I am using `cleos get table :

It used to work in May (see Payable Functions - Discussion), but today it appears the account is not here anymore.

Along this EOS 201 course, I think I really have been carefully following the instructions in the videos, but for some reason, I have not been able to make the dapp run properly on my laptop, with my environment.

This is OK :slightly_smiling_face:, I think I will simply follow the last videos until the end of the course.

All the best!

1 Like

@thecil Having problems with curl: (7) Failed to connect to localhost port 8888: Connection refused

after using curl http://localhost:8888/v1/chain/get_info

1 Like

Hello @cherrybluemoon, hope you are great.

Which OS are you using?
If linux, you could check which program is using the port 8888 with netstat commands.
sudo netstat -ltnp
that will give you a list of ports that are being used and by which process (PID is the ID of the process)

Then you can use pkill command to kill the process…example: pkill 2626 means process kill ID(number).

Hope you find this useful.
If you have any more questions, please let us know so we can help you! :slight_smile:

Carlos Z.

1 Like

Hi @thecil,

My OS is mac. So I found and used sudo lsof -i -n -P | grep TCP to check ports. After I used pkill nodeos, then nodeos start command. I still received the error msg. Will keep troubleshooting. Hopefully I can find a solution. :grinning: :nerd_face:

Now I tried sudo lsof -PiTCP -sTCP:LISTEN which now I can see ports, but still cannot query or connect

node      92797 cherrybluemoon   35u  IPv4 0x3d24e3b81f42d40b      0t0  TCP localhost:50952 (LISTEN)
node      92797 cherrybluemoon   36u  IPv4 0x3d24e3b81f15466b      0t0  TCP localhost:50953 (LISTEN)
node      92797 cherrybluemoon   37u  IPv4 0x3d24e3b7f9e208cb      0t0  TCP localhost:45623 (LISTEN)
node      92797 cherrybluemoon   38u  IPv4 0x3d24e3b81d17eeeb      0t0  TCP localhost:59623 (LISTEN)
cherrybluemoon@Markandrews-MacBook-Pro ~ % curl http://localhost:50592/v1/chain/get_info
curl: (7) Failed to connect to localhost port 50592: Connection refused
cherrybluemoon@Markandrews-MacBook-Pro ~ % curl http://localhost:50593/v1/chain/get_info
curl: (7) Failed to connect to localhost port 50593: Connection refused
1 Like

Ok i’m not really an expert on MAC OS, but i think you have an issue with the firewall, probably, i’m not complete sure.

Maybe this could help https://www.macworld.co.uk/how-to/mac-software/how-open-specific-ports-in-os-x-1010-firewall-3616405/

Hope you find this useful.
If you have any more questions, please let us know so we can help you! :slight_smile:

Carlos Z.

1 Like

I think it may have something to do with eosio.cdt. What I found when searching a user solved it using eosio/eos-dev:v1.2.3
Also this link https://cmichel.io/how-to-install-an-old-package-version-with-brew/ has a how to for old package version.
A little confusing for me.
However in Step 1 Installing Binaries for this course, (I am not sure but v1.8.1 may have something to do with solving port issue)

brew tap eosio/eosio
brew install eosio
(make sure you get v1.8.1)

I get this:

brew install [email protected]
Error: No available formula or cask with the name "[email protected]".
=> **Searching for a previously deleted formula (in the last month)...**
Error: No previously deleted formula found.
==> **Searching for similarly named formulae...**
Error: No similarly named formulae found.
==> **Searching taps...**
==> **Searching taps on GitHub...**
Error: No formulae found in taps.

Ok based on their instructions:
First you have to remove the actual eosio, brew remove eosio.cdt.
Then download the package of the old version, extract it and install it.

Now, are you sure that you are in the same folder when extracting the package file?
I mean you have to create a local folder to extract the package, then you should go into the folder and run the brew install [email protected] for example.

If you have any more questions, please let us know so we can help you! :slight_smile:

Carlos Z.

I did not get the needed results with my chainid with the command Filip used
curl http://localhost:8888/v1/chain/get_info

But I used the following instead and it worked just fine. Hopefully this helps anyone in the future!
curl http://127.0.0.1:8888/v1/chain/get_info

1 Like

I have following action in my smartcontract:

ACTION uploadfile1 (name creator, vector<uint8_t> content, string filename)

I’m trying to push action from my Swift application using following code:

struct uploadFile: Codable {
    var creator: EosioName
    var content: [Int8]
    var filename: String
}

    let testArr = Array(repeating: Int8(20), count: 10)
    let data = uploadFile(creator: try! EosioName("tibackbone"),
                          content: testArr,
                          filename: theFileName)

    rpcProvider = EosioRpcProvider(endpoint: endpoint)
    guard let rpcProvider = rpcProvider else {
        print("ERROR: No RPC provider found.")
        return
    }

    let serializationProvider = EosioAbieosSerializationProvider()
    let signatureProvider = try! EosioSoftkeySignatureProvider(privateKeys: privateKeys)
    transactionFactory = EosioTransactionFactory(
        rpcProvider: rpcProvider,
        signatureProvider: signatureProvider,
        serializationProvider: serializationProvider
    )
    
    let transaction = transactionFactory?.newTransaction()
    let action = try! EosioTransaction.Action(
        account: EosioName(accountName),
        name: EosioName("uploadfile1"),
        authorization: [EosioTransaction.Action.Authorization(
            actor: EosioName(accountName),
            permission: EosioName("active"))
        ],
        data: data
    )

    transaction?.add(action: action)

    transaction?.signAndBroadcast { result in
        switch result {
        case .failure (let error):
            print("*** TRANSACTION ERROR")
            print("---- ERROR SIGNING OR BROADCASTING TRANSACTION")
            print(error)
            print(error.reason)
        case .success (let info):
            if let transactionId = transaction?.transactionId {
                print("Transaction ID \(transactionId)")
        default: break
        }
    }

When i’m running this code i’m receiving following error:

*** TRANSACTION ERROR ---- ERROR SIGNING OR BROADCASTING TRANSACTION Error was encountered in SerializationProvider. Unable to pack json to bin. Expected string

Can anyone suggest me where i’m wrong and what i’m missing.

Thanks to everyone in advance!

Hello everyone

I am struggling with the following Error:
I’ve set up the Dog Dapp according to the videos. I can log into a Scatter account when the site launches, but I cant use any of the functions.
When trying to add a Dog i receive the following error:
0.0.0.0:8000
Error: fetching abi for dogcontract: Read past end of buffer

Couldn’t really solve it with google nor the forum so far.
I’ve found people having similar errors due to performance issues, which wouldn’t really make sense to me tbh.
Has anyone got an Idea?

Thanks alot!