使用TheGraph 获取Uniswap数据(c#)

构建一个.NET sdk来使用GraphQL调用Uniswap的subgraph。

> * 原文:https://medium.com/coinmonks/get-uniswap-data-using-the-graph-79d0c6f7b9f2 来自: [Reitter](https://reitter.medium.com/?source=post_page-----79d0c6f7b9f2--------------------------------) > * 译文出自:[登链翻译计划](https://github.com/lbc-team/Pioneer) > * 译者:[张小风](https://learnblockchain.cn/people/74) > * 校对:[Tiny 熊](https://learnblockchain.cn/people/15) > * 本文永久链接:[learnblockchain.cn/article…](https://learnblockchain.cn/article/2118) > Uniswap是一个建立在以太坊上的去中心化协议,用户可以交换ERC-20代币,不需要买家和卖家创造需求。 它是最受欢迎的去中心化交易所(DEX),在撰写本文时,总价值锁定超过[14亿美元](https://defipulse.com/uniswap)。 Uniswap使用`y=k*x`做市商机制来确定代币的价格,该产品保持不变,用于确定交易价格。 The Graph是一个用于查询以太坊和IPFS数据的索引协议。 任何人都可以贡献和创建subgraph,从而使区块链数据的访问变得容易(参考:[ 使用 TheGraph 完善Web3 事件数据检索](https://learnblockchain.cn/article/1589)。 The Graph有多个subgraph,如[Aave](https://thegraph.com/explorer/subgraph/aave/protocol)、[ENS](https://thegraph.com/explorer/subgraph/ensdomains/ens)、[Balancer](https://thegraph.com/explorer/subgraph/balancer-labs/balancer)和[MakerDAO](https://thegraph.com/explorer/subgraph/protofire/makerdao-governance)。 为了查询这些subgraph的数据,我们将使用GraphQL。 > [GraphQL](https://en.wikipedia.org/wiki/GraphQL)是一种开源的数据查询和操作语言,用于Facebook创建的API。 Uniswap subgraph可以在[Uniswap V2 Subgraph ](https://thegraph.com/explorer/subgraph/uniswap/uniswap-v2)找到。 ## 建立Uniswap sdk。 为了进行GraphQL查询,我们需要两个包,一个用于进行GraphQL查询,另一个用于使用新的高性能的`System.Text.Json`反序列化数据。 为了添加软件包,我们可以运行 cli 命令。 ``` dotnet add package GraphQL.Client --version 3.2.0 dotnet add package GraphQL.Cliente.Serializer.SystemTextJson --version 3.2.0 ``` 现在,我们可以创建我们的`Uniswap.cs`类,它将通过构造函数注入来接收IGraphQLClient。 ```c# public class Uniswap : IUniswap { private readonly IGraphQLClient _graphQLClient; public Uniswap(IGraphQLClient graphQLHttpClient) { _graphQLClient = graphQLHttpClient ?? throw new ArgumentNullException(nameof(graphQLHttpClient)); } ``` ## 获得流动性最高的市场交易对 我们现在可以调用Uniswap V2 subgraph。 创建一个名为 `GetMostLiquidMarketPairs `的方法,并使用GraphQL进行第一个查询。 为了创建查询,实例化`GraphQLRequest`类,并将`Query`属性设置为所需的GraphQL查询: ```c# /// <summary> /// Get the first 150 most liquid market pairs ordered by desc /// </summary> /// <returns></returns> public async Task<Pools> GetMostLiquidMarketPairs() { var query = new GraphQLRequest { Query = @" { pairs(first: 150, orderBy: reserveETH orderDirection: desc){ token0 { symbol } token1 { symbol } reserveETH reserveUSD } } " }; ``` <center>GetMostLiquidMarketPairs.cs</center> 现在我们可以通过使用GraphQL客户端(SendQueryAsync.cs)中的`SendQueryAsync`方法来调用API: ```c# GraphQLResponse<Pools> response = await _graphQLClient.SendQueryAsync<Pools>(query); ``` <center>调用Uniswap V2subgraph</center> 我们将得到以下JSON响应(GetMostLiquidMarketPairs.json)。 ```js { "pairs": [ { "reserveETH": "3054879.156087123647945100225370331", "reserveUSD": "1743372228.452697253933797109410237", "token0": { "symbol": "UETH" }, "token1": { "symbol": "ULCK" } }, { "reserveETH": "244080.0678437459262731", "reserveUSD": "159910793.9406229506814469778929296", "token0": { "symbol": "WBTC" }, "token1": { "symbol": "WETH" } }, { "reserveETH": "194482.309033213794313742", "reserveUSD": "127433830.4304311482666341163887563", "token0": { "symbol": "DAI" }, "token1": { "symbol": "WETH" } }, { "reserveETH": "188948.216124956584332354", "reserveUSD": "123806052.2355680797669692758593685", "token0": { "symbol": "WETH" }, "token1": { "symbol": "USDT" } }, ``` <center>GetMostLiquidMarketPairs JSON response</center> ## 将Uniswap类添加到DI容器 为了能够访问建立的Uniswap类,我们将把它添加到DI容器中。 为此,我们将创建`IUniswap`接口,并创建扩展方法`AddUniswap`,可以在下面的代码中看到。 我们为`IServiceCollection`接口创建一个扩展方法,因为在使用这个sdk时,我们只需在`StartUp.cs`类中添加`services.AddUniswap();`。 ```c# public static class UniswapExtension { public static void AddUniswap(this IServiceCollection services) { services.AddSingleton<IGraphQLClient>(ctx => { var graphQLOptions = new GraphQLHttpClientOptions { EndPoint = new Uri("https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2") }; return new GraphQLHttpClient(graphQLOptions, new SystemTextJsonSerializer()); }); services.AddSingleton<IUniswap>(ctx => { IGraphQLClient graphQLClient = ctx.GetRequiredService<IGraphQLClient>(); return new Uniswap(graphQLClient); }); } } ``` <center>AddUniswap.cs</center> 在上面的代码中,我们已经使用了HttpClient类型的客户端,它只是一个为某些特定用途预先配置的`HttpClient`。 ## 使用Uniswap sdk 现在已经建立了sdk,我们可以在自己的API中使用它。 在下面的例子中,将通过构造函数注入得到`IUniwap`接口,然后我们就可以调用它的方法,如下面的示例控制器所示: ```c# [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private readonly ILogger<WeatherForecastController> _logger; private readonly IUniswap _uniswap; public WeatherForecastController(ILogger<WeatherForecastController> logger, IUniswap uniswap) { _logger = logger; _uniswap = uniswap; } [HttpGet] public async Task<Pools> Get(string project = null) { var result = await _uniswap.GetMostLiquidMarketPairs(); return result; } } ``` <center>使用 IUniswap.cs</center> ## Uniswap .NET标准库 这个完整的库是免费的,可以下载并通过运行cli命令添加到你的项目中。 ``` dotnet add package Uniswap.dotnet --version 1.0.1 ``` 你也可以通过nuget(.NET的官方包管理器)或GitHub来添加这个包。 [Uniswap.dotnet 1.0.1](https://www.nuget.org/packages/Uniswap.dotnet/) - 在TheGraph GraphQL API上为Uniswap V2 Subgraph提供的dotnet标准封装器. [strykerin/Uniswap-dotnet(代码库)](https://github.com/strykerin/Uniswap-dotnet)在TheGraph GraphQL API上的Uniswap V2 Subgraph的dotnet标准封装器。 ## 结论 在这篇文章中,我们为Uniswap V2 subgraph构建了一个dotnet包装器,以获得去中心化交易所的分析结果,如获得流动性最高的交易对。 ## 参考文献 1. [Uniswap](https://uniswap.org/)在Ethereumuniswap.org上自动提供流动性的完全去中心化协议 2. [什么是Uniswap?](https://decrypt.co/resources/what-is-uniswap)- 去中心化代币交易所指南. 3. [自动做市算法在很多场合被常规采用,从金融市场到博彩市场。 4. [使用DeFi Pulse API](https://reitter.medium.com/get-defi-projects-data-with-defi-pulse-api-81721f8e6dd2)获取DeFi项目数据使用 ------ 本翻译由 [Cell Network](https://www.cellnetwork.io/?utm_souce=learnblockchain) 赞助支持。

  • 原文:https://medium.com/coinmonks/get-uniswap-data-using-the-graph-79d0c6f7b9f2 来自: Reitter
  • 译文出自:登链翻译计划
  • 译者:张小风
  • 校对:Tiny 熊
  • 本文永久链接:learnblockchain.cn/article…

Uniswap是一个建立在以太坊上的去中心化协议,用户可以交换ERC-20代币,不需要买家和卖家创造需求。 它是最受欢迎的去中心化交易所(DEX),在撰写本文时,总价值锁定超过14亿美元。

Uniswap使用y=k*x做市商机制来确定代币的价格,该产品保持不变,用于确定交易价格。

The Graph是一个用于查询以太坊和IPFS数据的索引协议。 任何人都可以贡献和创建subgraph,从而使区块链数据的访问变得容易(参考: 使用 TheGraph 完善Web3 事件数据检索。

The Graph有多个subgraph,如Aave、ENS、Balancer和MakerDAO。 为了查询这些subgraph的数据,我们将使用GraphQL。

GraphQL是一种开源的数据查询和操作语言,用于Facebook创建的API。

Uniswap subgraph可以在Uniswap V2 Subgraph 找到。

建立Uniswap sdk。

为了进行GraphQL查询,我们需要两个包,一个用于进行GraphQL查询,另一个用于使用新的高性能的System.Text.Json反序列化数据。 为了添加软件包,我们可以运行 cli 命令。

dotnet add package GraphQL.Client --version 3.2.0

dotnet add package GraphQL.Cliente.Serializer.SystemTextJson --version 3.2.0

现在,我们可以创建我们的Uniswap.cs类,它将通过构造函数注入来接收IGraphQLClient。

public class Uniswap : IUniswap
{
    private readonly IGraphQLClient _graphQLClient;

    public Uniswap(IGraphQLClient graphQLHttpClient)
    {
        _graphQLClient = graphQLHttpClient ?? throw new ArgumentNullException(nameof(graphQLHttpClient));
    }

获得流动性最高的市场交易对

我们现在可以调用Uniswap V2 subgraph。 创建一个名为 GetMostLiquidMarketPairs的方法,并使用GraphQL进行第一个查询。 为了创建查询,实例化GraphQLRequest类,并将Query属性设置为所需的GraphQL查询:

/// &lt;summary>
/// Get the first 150 most liquid market pairs ordered by desc
/// &lt;/summary>
/// &lt;returns>&lt;/returns>
public async Task&lt;Pools> GetMostLiquidMarketPairs()
{
    var query = new GraphQLRequest
    {
        Query = @"
        {
            pairs(first: 150, orderBy: reserveETH orderDirection: desc){
            token0 {
              symbol
            }
            token1 {
              symbol
            }
            reserveETH
            reserveUSD
          }
        }
        "
    };

<center>GetMostLiquidMarketPairs.cs</center>

现在我们可以通过使用GraphQL客户端(SendQueryAsync.cs)中的SendQueryAsync方法来调用API:

GraphQLResponse&lt;Pools> response = await _graphQLClient.SendQueryAsync&lt;Pools>(query);

<center>调用Uniswap V2subgraph</center>

我们将得到以下JSON响应(GetMostLiquidMarketPairs.json)。

{
  "pairs": [
    {
      "reserveETH": "3054879.156087123647945100225370331",
      "reserveUSD": "1743372228.452697253933797109410237",
      "token0": {
        "symbol": "UETH"
      },
      "token1": {
        "symbol": "ULCK"
      }
    },
    {
      "reserveETH": "244080.0678437459262731",
      "reserveUSD": "159910793.9406229506814469778929296",
      "token0": {
        "symbol": "WBTC"
      },
      "token1": {
        "symbol": "WETH"
      }
    },
    {
      "reserveETH": "194482.309033213794313742",
      "reserveUSD": "127433830.4304311482666341163887563",
      "token0": {
        "symbol": "DAI"
      },
      "token1": {
        "symbol": "WETH"
      }
    },
    {
      "reserveETH": "188948.216124956584332354",
      "reserveUSD": "123806052.2355680797669692758593685",
      "token0": {
        "symbol": "WETH"
      },
      "token1": {
        "symbol": "USDT"
      }
    },

<center>GetMostLiquidMarketPairs JSON response</center>

将Uniswap类添加到DI容器

为了能够访问建立的Uniswap类,我们将把它添加到DI容器中。 为此,我们将创建IUniswap接口,并创建扩展方法AddUniswap,可以在下面的代码中看到。 我们为IServiceCollection接口创建一个扩展方法,因为在使用这个sdk时,我们只需在StartUp.cs类中添加services.AddUniswap();

public static class UniswapExtension
{
    public static void AddUniswap(this IServiceCollection services)
    {
        services.AddSingleton&lt;IGraphQLClient>(ctx =>
        {
            var graphQLOptions = new GraphQLHttpClientOptions
            {
                EndPoint = new Uri("https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2")
            };
            return new GraphQLHttpClient(graphQLOptions, new SystemTextJsonSerializer());
        });

        services.AddSingleton&lt;IUniswap>(ctx => 
        {
            IGraphQLClient graphQLClient = ctx.GetRequiredService&lt;IGraphQLClient>();
            return new Uniswap(graphQLClient);
        });
    }
}

<center>AddUniswap.cs</center>

在上面的代码中,我们已经使用了HttpClient类型的客户端,它只是一个为某些特定用途预先配置的HttpClient

使用Uniswap sdk

现在已经建立了sdk,我们可以在自己的API中使用它。 在下面的例子中,将通过构造函数注入得到IUniwap接口,然后我们就可以调用它的方法,如下面的示例控制器所示:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private readonly ILogger&lt;WeatherForecastController> _logger;
    private readonly IUniswap _uniswap;

    public WeatherForecastController(ILogger&lt;WeatherForecastController> logger, IUniswap uniswap)
    {
        _logger = logger;
        _uniswap = uniswap;
    }

    [HttpGet]
    public async Task&lt;Pools> Get(string project = null)
    {
        var result = await _uniswap.GetMostLiquidMarketPairs();
        return result;
    }
}

<center>使用 IUniswap.cs</center>

Uniswap .NET标准库

这个完整的库是免费的,可以下载并通过运行cli命令添加到你的项目中。

dotnet add package Uniswap.dotnet --version 1.0.1

你也可以通过nuget(.NET的官方包管理器)或GitHub来添加这个包。

Uniswap.dotnet 1.0.1 - 在TheGraph GraphQL API上为Uniswap V2 Subgraph提供的dotnet标准封装器.

strykerin/Uniswap-dotnet(代码库)在TheGraph GraphQL API上的Uniswap V2 Subgraph的dotnet标准封装器。

结论

在这篇文章中,我们为Uniswap V2 subgraph构建了一个dotnet包装器,以获得去中心化交易所的分析结果,如获得流动性最高的交易对。

参考文献

  1. Uniswap在Ethereumuniswap.org上自动提供流动性的完全去中心化协议

  2. 什么是Uniswap?- 去中心化代币交易所指南.

  3. [自动做市算法在很多场合被常规采用,从金融市场到博彩市场。

  4. 使用DeFi Pulse API获取DeFi项目数据使用

本翻译由 Cell Network 赞助支持。

  • 发表于 2021-02-05 11:59
  • 阅读 ( 1384 )
  • 学分 ( 98 )
  • 分类:DeFi

评论