Search code examples
soliditysmartcontractschainlink

How do I convert a uint256 variable to an int256 one?


I was trying to print uint timeStamp by typing return timeStamp; right below return price; from this code:

pragma solidity ^0.6.7;

import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";

contract PriceConsumerV3 {

AggregatorV3Interface internal priceFeed;

/**
 * Network: Kovan
 * Aggregator: BTC/USD
 * Address: 0x6135b13325bfC4B00278B4abC5e20bbce2D6580e
 */
constructor() public {
    priceFeed = AggregatorV3Interface(0x6135b13325bfC4B00278B4abC5e20bbce2D6580e);
}

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

When I compiled the code above on the Remix Compiler, it replied:

TypeError: Return argument type uint256 is not implicitly convertible to expected type (type of first return variable) int256. return timeStamp; ^-------^

I tend to think that I would just have to type int256 return timeStamp or something similar instead of return timeStamp; but I can't figure it out.

Feedback is appreciated.


Solution

  • You can typecast the uint to int using this syntax:

    return int(timeStamp);
    

    Note: This will overflow (in Solidity 0.7.x and older) or throw an exception (in Solidity 0.8+) for values between 2^255 (int max value) and 2^256-1 (uint max value). But this is most likely just a theoretical case, because timestamp is not expected to have this large value.


    Mind that this line is unreachable, because you're already returning price on the previous line.

    (
        uint80 roundID, 
        int price,
        uint startedAt,
        uint timeStamp,
        uint80 answeredInRound
    ) = priceFeed.latestRoundData();
    return price; // the `price` is returned, and the function doesn't execute after this line
    return timeStamp; // this is ignored because of the early return on previous line
    

    If you want to return multiple values, you can use this syntax:

    // note the multiple datatypes in the `returns` block
    function getThePriceAndTimestamp() public view returns (int, uint) {
        (
            uint80 roundID, 
            int price,
            uint startedAt,
            uint timeStamp,
            uint80 answeredInRound
        ) = priceFeed.latestRoundData();
        return (price, timeStamp); // here returning multiple values
    }