
1、通过预言机获取Token价格(需要部署合约)
在以太坊区块链上,由于智能合约本身无法获取外部数据,因此需要使用预言机 (Oracle) 来获取外部数据。
以下是一个获取代币价格的示例:
- 选择预言机:首先需要选择一个可靠的预言机服务供应商,例如 Chainlink、Band Protocol 等。
 - 查询代币价格:通过预言机服务供应商提供的 API,可以查询代币价格。以 Chainlink 为例,可以使用其提供的 Price Feed Contract 来查询代币价格。
 - 调用预言机合约:在智能合约中通过调用预言机合约来获取代币价格。
 
pragma solidity ^0.8.0;
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
contract TokenPrice {
    AggregatorV3Interface internal priceFeed;
    constructor() {
        priceFeed = AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331); // Chainlink ETH/USD Price Feed
    }
    function getLatestTokenPrice() public view returns (uint256) {
        (, int price, , , ) = priceFeed.latestRoundData();
        return uint256(price);
    }
} 
备注:预言机服务供应商提供的价格信息可能会受到篡改或攻击,因此需要选择可靠的服务供应商,并实现相应的安全措施来保护智能合约的安全性。
2、通过API获取Token价格
为了保证获取token价格的稳定性,以及准确定,我们可以选择几个比较大的交易所API(例如 CoinGecko、CryptoCompare、Binance 等),交易1U的价格,取平均值即可。
另外,为了防止IP被封,我们可以取申请一个key,然后后端请求,存储数据库和缓存中,如果请求失败,可以获取缓存中的数据,如果成功,将数据添加到缓存中和数据库中。
以下是一个获取代币价格并计算平均值的示例代码:
javascript版本:
const axios = require('axios');
async function getTokenPrice() {
  const apiUrls = [
    'https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd',
    'https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD',
    'https://api.binance.com/api/v3/ticker/price?symbol=ETHUSDT'
  ];
  let prices = [];
  for (const apiUrl of apiUrls) {
    try {
      const response = await axios.get(apiUrl);
      if (response.data) {
        prices.push(response.data.USD);
      }
    } catch (error) {
      console.error(`Failed to fetch price from ${apiUrl}: ${error.message}`);
    }
  }
  if (prices.length > 0) {
    const averagePrice = prices.reduce((total, price) => total + parseFloat(price), 0) / prices.length;
    return averagePrice.toFixed(2);
  } else {
    throw new Error('Failed to fetch price from all APIs');
  }
}
getTokenPrice().then(price => console.log(price)).catch(error => console.error(error)); 
java版本
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class TokenPrice {
    private static final String[] API_URLS = {
            "https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd",
            "https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD",
            "https://api.binance.com/api/v3/ticker/price?symbol=ETHUSDT"
    };
    public static void main(String[] args) throws IOException {
        double price = getTokenPrice();
        System.out.println("Token price: " + price);
    }
    public static double getTokenPrice() throws IOException {
        List<Double> prices = new ArrayList<>();
        for (String apiUrl : API_URLS) {
            try {
                ObjectMapper mapper = new ObjectMapper();
                URL url = new URL(apiUrl);
                JsonNode response = mapper.readTree(url);
                if (response != null && response.has("USD")) {
                    double price = response.get("USD").asDouble();
                    prices.add(price);
                }
            } catch (IOException e) {
                System.err.println("Failed to fetch price from " + apiUrl + ": " + e.getMessage());
            }
        }
        if (prices.size() > 0) {
            double averagePrice = prices.stream().mapToDouble(Double::doubleValue).average().getAsDouble();
            return Math.round(averagePrice * 100) / 100.0;
        } else {
            throw new RuntimeException("Failed to fetch price from all APIs");
        }
    }
} 
                

















