1

I am coding a smart contract which will be integrating ChainLink's decentralized oracles, however I've run into an issue that is preventing me from deploying the smart contract on Remix IDE. The problem is that I want to refer to price in another function that is yet to be written, and I need price to be accessible globally as an unsigned integer current_price. But If I want to deploy the following smart contract on Remix, I get the error 'The execution failed due to an exception. Reverted', and it is the very last line of code uint current_price = uint(getThePrice()); that is causing this error. Even if I would simplify the last line to current_price = getThePrice(); I still get the same error. What is the reason for that and how to overcome this?

pragma solidity ^0.8.4;

import "https://github.com/smartcontractkit/chainlink/blob/master/evm-contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";

contract Price {

    
    receive() external payable {
    }
    
    address payable owner;
    
        AggregatorV3Interface internal priceFeed;

    /**
     * Network: Kovan
     * Aggregator: ETH/USD
     * Address: 0x9326BFA02ADD2366b30bacB125260Af641031331
     */
    constructor() public payable {
        priceFeed = AggregatorV3Interface(address(0x9326BFA02ADD2366b30bacB125260Af641031331));
    }

    function getThePrice() public view returns (int) {
        (
            uint80 roundID, 
            int price,
            uint startedAt,
            uint timeStamp,
            uint80 answeredInRound
        ) = priceFeed.latestRoundData();
        return price;
    }
    
    uint current_price = uint(getThePrice());


    
    
}

1 Answer 1

1

You can declare the current_price variable at the head of the contract, along with the other global variables:

contract Price {
    address payable owner;
    AggregatorV3Interface internal priceFeed;
    uint current_price;
    ...

And then set it in the constructor:

    constructor() public payable {
        priceFeed = AggregatorV3Interface(address(0x9326BFA02ADD2366b30bacB125260Af641031331));
        current_price = uint(getThePrice());
    }
2
  • That indeed solved my problem. Could you please explain the logic behind why this works, and why my way didn't?
    – Teo
    Commented May 30, 2021 at 20:30
  • 1
    Glad it worked :-) So in the main body of the contract you can either declare global variables (e.g. uint current_price;) or declare and define them at the same time (e.g. uint current_price = 150;) But to define them you can't invoke a function, like you were trying to. All "executable" code has to be inside a function (the constructor is a special function). Commented May 30, 2021 at 20:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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