1

I'm wanting to create a smart contract that sends an amount of ether to an address when the weather is above 30 degrees for 3 or more consecutive days, using the OpenWeatherMap API.

How can I use data from an API in a smart contract?

Thanks in advance..

Victor
  • 61
  • 3

2 Answers2

0

Yes, it's possible.

Option 1: Easy but centralised

You need Web3JS (or py or java etc.). Make a NodeJS file index.js, install web3 and axios (to call weather data), host index.js somewhere, and when temperature goes up or down, call smart contract function.

Option 2 : hard but decentralised.

use Oracles https://ethereum.org/en/developers/docs/oracles/ It give right data for smart contracts.

tutorial: https://www.youtube.com/watch?v=AtHp7me2Yks

API calling with solidity example:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

import "@chainlink/contracts/src/v0.8/ChainlinkClient.sol";

contract APIConsumer is ChainlinkClient { using Chainlink for Chainlink.Request;

uint256 public volume;

address private oracle;
bytes32 private jobId;
uint256 private fee;

constructor() {
    setPublicChainlinkToken();
    oracle = 0xc57B33452b4F7BB189bB5AfaE9cc4aBa1f7a4FD8;
    jobId = "d5270d1c311941d0b08bead21fea7747";
    fee = 0.1 * 10 ** 18; // (Varies by network and job)
}


function requestVolumeData() public returns (bytes32 requestId) 
{
    Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);

    // Set the URL to perform the GET request on
    request.add("get", "https://min-api.cryptocompare.com/data/pricemultifull?fsyms=ETH&tsyms=USD");

    // Set the path to find the desired data in the API response, where the response format is:
    // {"RAW":
    //   {"ETH":
    //    {"USD":
    //     {
    //      "VOLUME24HOUR": xxx.xxx,
    //     }
    //    }
    //   }
    //  }
    request.add("path", "RAW.ETH.USD.VOLUME24HOUR");

    // Multiply the result by 1000000000000000000 to remove decimals
    int timesAmount = 10**18;
    request.addInt("times", timesAmount);

    // Sends the request
    return sendChainlinkRequestTo(oracle, request, fee);
}

/**
 * Receive the response in the form of uint256
 */ 
function fulfill(bytes32 _requestId, uint256 _volume) public recordChainlinkFulfillment(_requestId)
{
    volume = _volume;
}

// function withdrawLink() external {} - Implement a withdraw function to avoid locking your LINK in the contract

}

aakash4dev
  • 691
  • 3
  • 11
0

Ethreum virtual machine (EVM) does not has access to the external network due to the fact that all the transactions must be deterministic.

You need to create an oracle service that reads an external API and feeds this information to the Ethereum smart contracts in a trusted manner.

Here is more background inform,ation How do oracle services work under the hood?

Mikko Ohtamaa
  • 22,269
  • 6
  • 62
  • 127