Calling view methods

For view methods (which only read a value in a smart contract), they are invoked using an ordinary method call, except they will not return a TransactionReceipt as no transaction will be initiated (no cost associated). In our smart contract, we have a view method,  offset(), that can be invoked as follows:

BigInteger  Offset=CFutureInstance.offset().send();
log.info("your offset is "+Offset.intValue());

In the same manner, it is possible to query the public states of a smart contract, for instance to read the last fuelPriceUSD state's value:

BigInteger LastfuelPrice = CFutureInstance.fuelPriceUSD().send();
Integer fuelPriceUSD = LastfuelPrice.intValue();
log.info("Last fuel Price Fuel price According to the Oracle is: " + fuelPriceUSD);

But, to update the fuelPriceUSD to the current price, we need to go through two steps.

The first is to update the price, which we request from the oracle. The second is to wait for the event informing us of the oracle's response to read the new value:

BigInteger txcost = Convert.toWei("0.01", Convert.Unit.ETHER).toBigInteger();
TransactionReceipt UpdateReceipt = CFutureInstance.updateprice(txcost).send();
for (CFutures.NewDieselPriceEventResponse event :
CFutureInstance.getNewDieselPriceEvents(UpdateReceipt)) {
log.info("The oil price has been updated:" + event.price);
}

Keep in mind, when you call the oracle, you are initiating an asynchronous exchange, which means there will be a delay between the query and the response (request and a callback transaction). Thus, in our Java code, we will need to update the price by listening for the NewDieselPrice event before calling the offset() method to give us an accurate value.

Notice that we used Convert.toWei("0.01", Convert.Unit.ETHER) to convert from ethers to wei while calling updateprice(), to cover the call charges.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset