I have an issue with my oraclize. I need to call oraclaze for update exchange rate. If i call function updatePrice() manually - it's ok, global variable dollarCost is updating. But if I call updatePrice() automatically into the fallback function, dollarCost isn't updating.

How to call updatePrice() into the fallback function and get result in dollarCost before calc tokens (tokens = msg.value * dollarCost / 1000 / (10 ** 16);)?

pragma solidity ^0.4.11;

import 'https://github.com/oraclize/ethereum-api/oraclizeAPI.sol';

contract Test is usingOraclize {

uint public tokens;

uint public dollarCost;


function() payable {
    updatePrice();
    tokens = msg.value * dollarCost / 1000 / (10 ** 16);
}


function __callback(bytes32 myid, string result) {
    if (msg.sender != oraclize_cbAddress()) throw;
    dollarCost = parseInt(result, 3);
}

function updatePrice() public payable {

    if (oraclize_getPrice("URL") > this.balance) {
        return;
    }
    else {
      oraclize_query("URL", "json(https://api.coinmarketcap.com/v1/ticker/ethereum/?convert=USD).[0].price_usd");
    }
}

}

Just put the line

tokens = msg.value * dollarCost / 1000 / (10 ** 16);

at the end of the function __callback(). That way you could make dollarCost a memory variable and would not even have to change the state of the contract which saves you some gas when using the contract.

On the other hand, you would have to store msg.value each time the fallback function is called. For that, I would use a mapping which uses the Oraclize id from oraclize_query() as a key for each respective msg.value.

mapping (bytes32 => uint256) public msgValue;

function __callback(bytes32 myid, string result) public {
    if (msg.sender != oraclize_cbAddress()) throw;
    dollarCost = parseInt(result, 3);
    tokens = msgValue[myid] * dollarCost / 1000 / (10 ** 16);
}

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.