아이콘 2.0: 실시간 분산 쿼트

21390 단어 blockchainiconelixir
ICON 2.0는 스마트 계약 플랫폼으로 독특한 상호작용성 주장을 가지고 있다Blockchain Transmission Protocol (BTP).BTP는 ICON 2.0과 이를 구현하는 모든 블록체인 간에 분산되고 신뢰할 수 없는 상호 운용성을 구현한다.
이 문서의 전체 BTP는 아직 게시되지 않았습니다.그러나 그것의 일부 기능은 이미 모든 사람에게 제공되었다.그 중 하나는 웹 소켓으로 생성된 블록과 이벤트 로그의 실시간 업데이트를 수신하는 데 사용됩니다.
본고는 이 웹소켓 연결을 어떻게 활용하는지 중점적으로 소개하고 내가 지난 몇 달 동안 쓴 Balanced Decentralized Exchange를 사용하여 Elixir ICON 2.0 SDK에서 견적을 검색하는 것을 통해 소개한다.
더 이상 귀찮게 하지 말고 우리 갑시다!


선결 조건
이 문서에서는 새 프로젝트에서 icon 또는 스크립트 다운로드mix new를 사용했다고 가정합니다. 예를 들어 다음과 같습니다.
#/usr/bin/env elixir

Mix.install([
  {:icon, "~> 0.1"}
])

# ... rest of the script ...
sICX/bnUSD 견적을 가져오는 전체 스크립트here도 찾을 수 있습니다.

오퍼
우리가 하나의 영패로 다른 영패를 교환하고 싶을 때, 우리는 영패가 맞는 것을 볼 수 있다.이러한 쌍에는 기본 태그, 쿼트 태그 및 쿼트가 있습니다.

만약 우리가 누군가가 영패를 교환할 때마다 보내는 사건 로그를 어떤 방식으로 포착한다면, 우리는 우리가 원하는 영패에 대해 실시간으로 가격을 제시할 수 있다.본 문서에서 우리는 균형 잡힌 sICX/bnUSD 가격을 구독할 것이다.

Note: sICX is staked ICX token and bnUSD is an algorithmic stablecoin pegged to the dollar called Balanced Dollars.



교환 로그 가져오기
Balanced는 여러 개의 점수(신뢰할 수 있는 환경에서의 스마트 계약)로 구성되어 있으며, 그 중 하나의 점수는 분산교환(DEx)과 관련된 모든 조작을 처리한다.주요한 DEx 조작은 기호화폐를 교환하는 것이다. 예를 들어 우리는 계약과bnUSD를 사용하여 sICX를 교환할 수 있다.
또한 누군가가 토큰을 교환할 때마다 점수는 다음과 같은 이벤트를 보냅니다.
Swap(int,Address,Address,Address,Address,Address,int,int,int,int,int,int,int,int,int)
우리는 Icon.get_score_api/2를 사용하여 점수의 API를 조회하고 입력마다 의미를 얻을 수 있다.이를 위해서는 기본 네트워킹의 점수 주소cxa0af3165c08318e988cb30993b3048335b94af6c가 필요합니다.
dex_score = "cxa0af3165c08318e988cb30993b3048335b94af6c"
identity = Icon.RPC.Identity.new(network_id: :mainnet)

{:ok, api} = Icon.get_score_api(identity, dex_score)

swap_definition =
  Enum.find(api, fn %{"name" => name, "type" => type} ->
    name == "Swap" and type == "eventlog"
  end)
변수swap_definition에는 이벤트 로그 정의Swap가 있습니다.
%{
  "inputs" => [
    %{"indexed" => "0x1", "name" => "_id", "type" => "int"},
    %{"indexed" => "0x1", "name" => "_baseToken", "type" => "Address"},
    %{"name" => "_fromToken", "type" => "Address"},
    %{"name" => "_toToken", "type" => "Address"},
    %{"name" => "_sender", "type" => "Address"},
    %{"name" => "_receiver", "type" => "Address"},
    %{"name" => "_fromValue", "type" => "int"},
    %{"name" => "_toValue", "type" => "int"},
    %{"name" => "_timestamp", "type" => "int"},
    %{"name" => "_lpFees", "type" => "int"},
    %{"name" => "_balnFees", "type" => "int"},
    %{"name" => "_poolBase", "type" => "int"},
    %{"name" => "_poolQuote", "type" => "int"},
    %{"name" => "_endingPrice", "type" => "int"},
    %{"name" => "_effectiveFillPrice", "type" => "int"}
  ],
  "name" => "Swap",
  "type" => "eventlog"
}

교환 이벤트 분석
앞에서 정의한 바와 같이 우리는 모든 이벤트 입력에 대해 가설을 하고 이벤트가 발생할 때마다 sICX/bnUSD의 가격을 얻기 위해 무엇을 얻어야 하는지를 가정할 수 있다.
  • _id는 영패 대조표식자indexed의 1위다.
  • _baseToken는 이 쌍의 기본 표기indexed 2위)의 점수 주소다.
  • _fromToken는 판매 중인 토큰의 점수 주소data 1위다.
  • _toToken는 구매한 기호화폐의 점수 주소data 2위다.
  • _timestamp는 UTC 단위의 UNIX 역원 타임 스탬프이며, 단위는 마이크로초(data 7위)이다.
  • _endingPriceloopdata 12위에서 교환된 가격이다.
  • 부분이든 전부든 우리는 이전의 입력을 사용하여 우리가 찾고 있는 견적을 찾을 수 있다.

    Protip: We can query the pool stats with the DEx function getPoolStats and search by ID. This will give us sICX/bnUSD pair has the ID 2. You can check it out yourself by running the following:

    Icon.call(identity, dex_score, "getPoolStats", %{_id: 2},
      call_schema: %{_id: :integer}
    )
    

    At the time of writing this article, there are 39 pools, but not all of them have a name, so in this case using _baseToken, _fromToken, and _toToken addresses can help us figure out the actual pair name.



    실시간 업데이트
    Elixir ICON 2.0 SDK에는 ICON용 웹소켓Yggdrasil 어댑터가 있다.따라서 Yggdrasil 프로세스 구독 Swap 이벤트를 사용할 수 있습니다.이 경우 가장 중요한 부분은 출력 채널을 올바르게 정의하는 것입니다.
    defmodule Quotes do
      use Yggdrasil
      alias Icon.Schema.Types.EventLog
    
      @dex_contract "cxa0af3165c08318e988cb30993b3048335b94af6c"
      @sicx_bnusd_id 2
      @signature "Swap(int,Address,Address,Address,Address,Address,int,int,int,int,int,int,int,int,int)"
    
      @channel [
        adapter: :icon,
        name: %{
          source: :event,
          data: %{
            addr: @dex_contract,
            event: @signature,
            indexed: [@sicx_bnusd_id, nil]
          },
          from_height: 47_077_000
        }
      ]
    
      def start_link, do: Yggdrasil.start_link(__MODULE__, [@channel])
    
      # ... handle_event/3 definition ...
    end
    

    Protip: I added from_height: 47_077_000 field to the channel's name for subscribing to an older block height. This way, we don't need to wait for a Swap event to happen and we can see some results right away. In general, this is only needed for testing purposes, but it wouldn't be needed if we just want the latest price.



    표시 가격
    저희가 받을 이벤트는 다음과 같습니다.
  • _timestamp 7위data는 마이크로초 단위이다.
  • _endingPricedata12위_endingPrice * 10¹⁸에 위치한다.
  • 따라서 이제 리콜handle_event/3을 정의하고 콘솔에서 견적을 인쇄할 수 있습니다.
    defmodule Quotes do
      use Yggdrasil
      alias Icon.Schema.Types.EventLog
    
      # ... channel definition ...
    
      @impl Yggdrasil
      def handle_event(_channel, %EventLog{} = swap_event, _state) do
        [_, _, _, _, _, _, timestamp, _, _, _, _, price, _] = swap_event.data
    
        datetime =
          timestamp
          |> DateTime.from_unix!(:microsecond)
          |> DateTime.to_iso8601()
    
        price = price / 1_000_000_000_000_000_000
    
        IO.puts("[#{datetime}] sICX/bnUSD price: #{price}")
    
        {:ok, nil}
      end
    end
    
    만약 우리가 이 과정을 집행한다면
    Quotes.start_link()
    
    그러면 다음과 같은 출력이 제공됩니다.
    [2022-03-07T16:17:15.095799Z] sICX/bnUSD price: 0.6762914917929946
    [2022-03-07T16:33:31.390351Z] sICX/bnUSD price: 0.6765223727152583
    [2022-03-07T16:19:25.140181Z] sICX/bnUSD price: 0.6763077935623969
    [2022-03-07T16:06:10.885982Z] sICX/bnUSD price: 0.6696113966372721
    [2022-03-07T16:28:17.210851Z] sICX/bnUSD price: 0.6765180152082558
    [2022-03-07T16:27:41.288288Z] sICX/bnUSD price: 0.6764913565725723
    ... continues ...
    

    Note: You can check out the full script here.




    결론
    비록 BTP가 아직 완전히 발표되지는 않았지만, 우리는 이미 그것의 일부 핵심 기능을 이용하여 우리의 장점을 실현하기 시작했다.ICON의 차단 시간이 3초라는 것을 감안하여 이러한 웹소켓 연결은 서로 다른 목적에 사용되는 실시간 로봇을 구축하는 데 커다란 장점을 제공했다. 우리의 생산량을 극대화하는 것부터 우리가 가장 좋아하는 NFT의 최신 다운로드를 확보하는 것까지.
    ICON 2.0은 다른 많은 느린 블록체인보다 큰 장점을 가진다. 나는 그의 DeFi 생태계가 밝은 미래를 가질 것이라고 믿는다!

    표지 사진 작성자Maxim Hopman

    좋은 웹페이지 즐겨찾기