Store and display native coin market cap from the DB (#7585)
* Store and display market cap from the DB * Fix reviwer comments * Fix reviewer comment * Fix reviewer comments * Process reviwer comments * Fix failing incompatible test * Fix test * Fix history_chart.js Return available_supply for backward compatibilityfix-missing-ranges-collector-test
parent
ed4553daf9
commit
171a81a45b
@ -0,0 +1,18 @@ |
||||
defmodule Explorer.Market.History.Source.MarketCap do |
||||
@moduledoc """ |
||||
Interface for a source that allows for fetching of market cap history. |
||||
""" |
||||
|
||||
@typedoc """ |
||||
Record of market values for a specific date. |
||||
""" |
||||
@type record :: %{ |
||||
date: Date.t(), |
||||
market_cap: Decimal.t() |
||||
} |
||||
|
||||
@doc """ |
||||
Fetch history for a specified amount of days in the past. |
||||
""" |
||||
@callback fetch_market_cap() :: {:ok, [record()]} | :error |
||||
end |
@ -0,0 +1,60 @@ |
||||
defmodule Explorer.Market.History.Source.MarketCap.CoinGecko do |
||||
@moduledoc """ |
||||
Adapter for fetching current market from CoinGecko. |
||||
|
||||
The current market is fetched for the configured coin. You can specify a |
||||
different coin by changing the targeted coin. |
||||
|
||||
# In config.exs |
||||
config :explorer, coin: "POA" |
||||
|
||||
""" |
||||
|
||||
alias Explorer.ExchangeRates.Source |
||||
alias Explorer.ExchangeRates.Source.CoinGecko, as: ExchangeRatesSourceCoinGecko |
||||
alias Explorer.Market.History.Source.MarketCap, as: SourceMarketCap |
||||
|
||||
@behaviour SourceMarketCap |
||||
|
||||
@impl SourceMarketCap |
||||
def fetch_market_cap do |
||||
url = ExchangeRatesSourceCoinGecko.source_url() |
||||
|
||||
if url do |
||||
case Source.http_request(url, ExchangeRatesSourceCoinGecko.headers()) do |
||||
{:ok, data} -> |
||||
result = |
||||
data |
||||
|> format_data() |
||||
|
||||
{:ok, result} |
||||
|
||||
_ -> |
||||
:error |
||||
end |
||||
else |
||||
:error |
||||
end |
||||
end |
||||
|
||||
@spec date(String.t()) :: Date.t() |
||||
defp date(date_time_string) do |
||||
with {:ok, datetime, _} <- DateTime.from_iso8601(date_time_string) do |
||||
datetime |
||||
|> DateTime.to_date() |
||||
end |
||||
end |
||||
|
||||
@spec format_data(term()) :: SourceMarketCap.record() | nil |
||||
defp format_data(nil), do: nil |
||||
|
||||
defp format_data(data) do |
||||
market_data = data["market_data"] |
||||
market_cap = market_data["market_cap"] |
||||
|
||||
%{ |
||||
market_cap: Decimal.new(to_string(market_cap["usd"])), |
||||
date: date(data["last_updated"]) |
||||
} |
||||
end |
||||
end |
@ -0,0 +1,9 @@ |
||||
defmodule Explorer.Repo.Migrations.MarketHistoryAddMarketCap do |
||||
use Ecto.Migration |
||||
|
||||
def change do |
||||
alter table(:market_history) do |
||||
add(:market_cap, :decimal) |
||||
end |
||||
end |
||||
end |
Loading…
Reference in new issue