Solidity and Web js for Ethereum blockchain data

0 votes

I want to save and retrieve data to an Ethereum Blockchain. I’m using the following code but I am not able to retrieve data. I am only getting the transaction the receipt. How to retrieve data?

Web3.js

export class AppComponent {

  title = 'app';

  dappUrl: string = 'http://myapp.com';

  web3: any;

  contractHash: string = '0x3b8a60616bde6f6d251e807695900f31ab12ce1a';

  MyContract: any;

  contract: any;

  ABI: any = [{"constant":true,"inputs":[{"name":"idx","type":"uint256"}],"name":"getLocationHistory","outputs":[{"name":"delegate","type":"address"},{"name":"longitude","type":"uint128"},{"name":"latitude","type":"uint128"},{"name":"name","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"recentLocation","outputs":[{"name":"delegate","type":"address"},{"name":"longitude","type":"uint128"},{"name":"latitude","type":"uint128"},{"name":"name","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"longitude","type":"uint128"},{"name":"latitude","type":"uint128"},{"name":"name","type":"bytes32"}],"name":"saveLocation","outputs":[],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"getLastLocation","outputs":[{"components":[{"name":"delegate","type":"address"},{"name":"longitude","type":"uint128"},{"name":"latitude","type":"uint128"},{"name":"name","type":"bytes32"}],"name":"recentLocation","type":"tuple"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"locations","outputs":[{"name":"delegate","type":"address"},{"name":"longitude","type":"uint128"},{"name":"latitude","type":"uint128"},{"name":"name","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"item","outputs":[{"name":"id","type":"bytes32"},{"name":"name","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"id","type":"bytes32"},{"name":"name","type":"bytes32"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"}];

  constructor(private route: ActivatedRoute) { }

  @HostListener('window:load')

  windowLoaded() {

    this.checkAndInstantiateWeb3();

    this.getLocation();

  }

  getLocationHistory() {

    this.MyContract.methods

      .getLocationHistory(0).send({

      'from': '0x902D578B7E7866FaE71b3AB0354C9606631bCe03',

      'gas': '44000'

    }).then((result) => {

      this.MyContract.methods.getLocationHistory(0).call()

        .then(hello => {console.log('hello', hello)});

    });

  }

  private checkAndInstantiateWeb3 = () => {

    if (typeof window.web3 !== 'undefined') {

      console.warn('Using web3 detected from external source.');

      // Use Mist/MetaMask's provider

      this.web3 = new Web3(window.web3.currentProvider);

    } else {

      console.warn(`No web3 detected. Falling back to http://localhost:8545.`);

      this.web3 = new Web3(

        new Web3.providers.HttpProvider('http://localhost:8545')

      );

    }

    this.MyContract = new this.web3.eth.Contract(this.ABI, this.contractHash);

  }

  private getLocation(): void {

    let query = this.route.snapshot.queryParams;

    if (query.action && query.action === 'setLocation') {

      this.setLocation();

    }

  }

  private setLocation(): void {

    navigator.geolocation.getCurrentPosition((position) => {

      this.MyContract.methods.saveLocation(

        position.coords.longitude, position.coords.latitude, window.web3.fromAscii("test")

      ).send({'from': '0x902D578B7E7866FaE71b3AB0354C9606631bCe03'}

      ).then((result) => {

        console.log('saveLocation')

        console.log(result)

      });

      this.getLocationHistory();

    });

  }   

}

Solidity Contract

pragma solidity ^0.4.11;

/// @title QRCodeTracking with delegation.

contract QRCodeTracking {

    struct Location {

        address delegate;

        uint128 longitude;

        uint128 latitude;

        bytes32 name;

    }

    struct Item {

        bytes32 id;  

        bytes32 name;

    }

    Item public item;

    Location[] public locations;

    Location public recentLocation;

    function QRCodeTracking(bytes32 id, bytes32 name) public {

        // Limit gas

        locations.length = 100;

        item = Item({id: id, name: name});

    }

    function saveLocation (

        uint128 longitude,

        uint128 latitude,

        bytes32 name

    ) public constant {

        locations.push(Location({

            delegate: msg.sender,

            longitude: longitude,

            latitude: latitude,

            name: name

}));


    }


    function getLocationHistory(uint idx) constant
        returns (address delegate, uint128 longitude, uint128 latitude, bytes32 name) {


        Location storage loc = locations[idx];


        return (loc.delegate, loc.longitude, loc.latitude, loc.name);
    }


    function getLastLocation() public
        returns (Location recentLocation) {
        recentLocation = locations[locations.length - 1];


        return recentLocation;
    }
}
Jul 30, 2018 in Blockchain by slayer
• 29,350 points
985 views

1 answer to this question.

0 votes

Your code is not right. I have tried to use my own code and it works. You are confused regarding send and call method. Read this document to understanding regarding the send method http://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#methods-mymethod-send. And also, you are using returns in a non-constant function. So the returns will compile but it wont return anything.

If you want returns to return anything then you have use it in a constant function.

Look at the code below that I have used:

const Web3 = require('web3');

const solc = require('solc');

const fs = require('fs');

const provider = new Web3.providers.HttpProvider("http://localhost:8545")

const web3 = new Web3(provider);

web3.eth.getAccounts().then((accounts) => {

  const code = fs.readFileSync('./QRCodeTracking.sol').toString();

  const compiledCode = solc.compile(code);

  const byteCode = compiledCode.contracts[':QRCodeTracking'].bytecode;

  // console.log('byteCode', byteCode);

  const abiDefinition = JSON.parse(compiledCode.contracts[':QRCodeTracking'].interface);

  const deployTransactionObject = {

    data: byteCode,

    from: accounts[0],

    gas: 4700000

  };

  let deployedContract;

  const MyContract = new web3.eth.Contract(abiDefinition, deployTransactionObject);

  MyContract.deploy({arguments: [web3.utils.asciiToHex("someId"), web3.utils.asciiToHex("someName")]}).send((err, hash) => {

    if (err)

      console.log("Error: " + err);

    else

      console.log("TX Hash: " + hash);

  }).then(result => {

    deployedContract = result;

    deployedContract.setProvider(provider);

    return deployedContract.methods.saveLocation(123456789, 987654321, web3.utils.asciiToHex("newLocationName")).send();

  }).then(saveResult => {

    return deployedContract.methods.getLocationHistory(0).call();

  }).then(locationResult => {

    console.log(locationResult);

  })

});

answered Jul 30, 2018 by digger
• 26,740 points

Related Questions In Blockchain

+1 vote
2 answers

What is a blockchain and ethereum?

Some of the use-cases are: Healthcare Medical records are ...READ MORE

answered Aug 9, 2018 in Blockchain by Omkar
• 69,210 points
596 views
+1 vote
1 answer

How to store state data in Ethereum blockchain?

You won't have to overwrite the whole ...READ MORE

answered Apr 25, 2018 in Blockchain by Shashank
• 10,400 points
727 views
0 votes
1 answer

How to extract Ethereum Blockchain data?

You are using web3.eth.getTransaction(txHash) web3.eth.getTransaction(txHash) will only return info ...READ MORE

answered Jul 30, 2018 in Blockchain by slayer
• 29,350 points
1,419 views
0 votes
1 answer

Truffle tests not running after truffle init

This was a bug. They've fixed it. ...READ MORE

answered Sep 11, 2018 in Blockchain by Christine
• 15,790 points
1,699 views
0 votes
1 answer

Hyperledger Sawtooth vs Quorum in concurrency and speed Ask

Summary: Both should provide similar reliability of ...READ MORE

answered Sep 26, 2018 in IoT (Internet of Things) by Upasana
• 8,620 points
1,237 views
+1 vote
5 answers

Where does the smart contracts stored and executed on blockchain?

Ethereum smart contracts are executed on EVM ...READ MORE

answered May 3, 2018 in Blockchain by Shashank
• 10,400 points
8,829 views
0 votes
1 answer
0 votes
1 answer

What is transientMap in node.js and getTransient in chaincode?

TransientMap: TransientMap  contains data that might be used to ...READ MORE

answered Jul 13, 2018 in Blockchain by digger
• 26,740 points
1,112 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP