Skip to content

Commit ae30790

Browse files
authored
Merge pull request #2412 from nervosnetwork/testnet
Deploy to mainnet
2 parents 6110307 + 727b961 commit ae30790

11 files changed

+211
-21
lines changed

app/controllers/api/v2/fiber/graph_nodes_controller.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,11 @@ def show
2525
@graph_channels = @graph_channels.where.not(closed_transaction_id: nil)
2626
end
2727
end
28+
29+
def addresses
30+
nodes = FiberGraphNode.all.select(:node_id, :addresses)
31+
render json: { data: nodes.map { _1.attributes.except("id") } }
32+
end
2833
end
2934
end
3035
end
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
module Api
2+
module V2
3+
module Fiber
4+
class StatisticsController < BaseController
5+
def index
6+
expires_in 15.minutes, public: true, stale_while_revalidate: 5.minutes, stale_if_error: 5.minutes
7+
statistics = FiberStatistic.order(created_at_unixtimestamp: :desc).limit(7)
8+
9+
render json: {
10+
data: statistics.map do |statistic|
11+
statistic.attributes.except("id", "created_at", "updated_at").transform_values(&:to_s)
12+
end,
13+
}
14+
end
15+
16+
def show
17+
expires_in 15.minutes, public: true, stale_while_revalidate: 5.minutes, stale_if_error: 5.minutes
18+
statistics = FiberStatistic.filter_by_indicator(params[:id]).order(created_at_unixtimestamp: :desc).limit(14)
19+
20+
render json: { data: statistics.map { _1.attributes.except("id").transform_values(&:to_s) } }
21+
end
22+
end
23+
end
24+
end
25+
end

app/models/fiber_graph_channel.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ def open_transaction_info
1616
open_transaction.as_json(only: %i[tx_hash block_number block_timestamp]).merge(
1717
{
1818
capacity: funding_cell.capacity,
19-
udt_amount: funding_cell.udt_amount,
19+
udt_info: funding_cell.udt_info,
2020
address: funding_cell.address_hash,
2121
},
2222
)
@@ -29,7 +29,7 @@ def closed_transaction_info
2929
close_accounts: closed_transaction.outputs.map do |cell|
3030
{
3131
capacity: cell.capacity,
32-
udt_amount: cell.udt_amount,
32+
udt_info: cell.udt_info,
3333
address: cell.address_hash,
3434
}
3535
end,

app/models/fiber_statistic.rb

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class FiberStatistic < ApplicationRecord
2+
VALID_INDICATORS = %w(total_nodes total_channels total_liquidity created_at_unixtimestamp).freeze
3+
4+
scope :filter_by_indicator, ->(indicator) {
5+
raise ArgumentError, "Invalid indicator" unless VALID_INDICATORS.include?(indicator.to_s)
6+
7+
select(indicator, :created_at_unixtimestamp)
8+
}
9+
end
10+
11+
# == Schema Information
12+
#
13+
# Table name: fiber_statistics
14+
#
15+
# id :bigint not null, primary key
16+
# total_nodes :integer
17+
# total_channels :integer
18+
# total_liquidity :bigint
19+
# mean_value_locked :bigint
20+
# mean_fee_rate :integer
21+
# medium_value_locked :bigint
22+
# medium_fee_rate :integer
23+
# created_at_unixtimestamp :integer
24+
# created_at :datetime not null
25+
# updated_at :datetime not null
26+
#
27+
# Indexes
28+
#
29+
# index_fiber_statistics_on_created_at_unixtimestamp (created_at_unixtimestamp) UNIQUE
30+
#

app/workers/fiber_graph_detect_worker.rb

Lines changed: 48 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -8,18 +8,15 @@ def perform
88
@graph_node_ids = []
99
@graph_channel_outpoints = []
1010

11-
# sync graph nodes and channels
12-
["nodes", "channels"].each { fetch_graph_infos(_1) }
13-
# purge outdated graph nodes
14-
FiberGraphNode.where.not(node_id: @graph_node_ids).destroy_all
15-
# purge outdated graph channels
16-
FiberGraphChannel.where.not(channel_outpoint: @graph_channel_outpoints).destroy_all
17-
# check channel is closed
18-
FiberGraphChannel.open_channels.each do |channel|
19-
funding_cell = channel.funding_cell
20-
if funding_cell.consumed_by
21-
channel.update(closed_transaction_id: funding_cell.consumed_by_id)
22-
end
11+
ApplicationRecord.transaction do
12+
# sync graph nodes and channels
13+
["nodes", "channels"].each { fetch_graph_infos(_1) }
14+
# purge outdated graph nodes
15+
FiberGraphNode.where.not(node_id: @graph_node_ids).destroy_all
16+
# purge outdated graph channels
17+
FiberGraphChannel.where.not(channel_outpoint: @graph_channel_outpoints).destroy_all
18+
# generate statistic
19+
compute_statistic
2320
end
2421
end
2522

@@ -42,7 +39,7 @@ def fetch_graph_infos(data_type)
4239

4340
def fetch_nodes(last_cursor)
4441
data = rpc.graph_nodes(ENV["FIBER_NODE_URL"], { limit: "0x64", after: last_cursor })
45-
ApplicationRecord.transaction { data.dig("result", "nodes").each { upsert_node_with_cfg_info(_1) } }
42+
data.dig("result", "nodes").each { upsert_node_with_cfg_info(_1) }
4643
data.dig("result", "last_cursor")
4744
rescue StandardError => e
4845
Rails.logger.error("Error fetching nodes: #{e.message}")
@@ -54,9 +51,6 @@ def fetch_channels(last_cursor)
5451
channel_attributes = data.dig("result", "channels").map { build_channel_attributes(_1) }.compact
5552
FiberGraphChannel.upsert_all(channel_attributes, unique_by: %i[channel_outpoint]) if channel_attributes.any?
5653
data.dig("result", "last_cursor")
57-
rescue StandardError => e
58-
Rails.logger.error("Error fetching channels: #{e.message}")
59-
nil
6054
end
6155

6256
def upsert_node_with_cfg_info(node)
@@ -124,6 +118,44 @@ def extract_peer_id(addresses)
124118
end
125119
end
126120

121+
def compute_statistic
122+
total_nodes = FiberGraphNode.count
123+
total_channels = FiberGraphChannel.count
124+
# 资金总量
125+
total_liquidity = FiberGraphChannel.sum(:capacity)
126+
# 资金均值
127+
mean_value_locked = total_channels.zero? ? 0.0 : total_liquidity.to_f / total_channels
128+
# fee 均值
129+
mean_fee_rate = FiberGraphChannel.average("fee_rate_of_node1 + fee_rate_of_node2") || 0.0
130+
# 获取 capacity 的数据
131+
capacities = FiberGraphChannel.pluck(:capacity).compact
132+
# 获取 fee_rate_of_node1 和 fee_rate_of_node2 的数据并合并
133+
fee_rate_of_node1 = FiberGraphChannel.pluck(:fee_rate_of_node1).compact
134+
fee_rate_of_node2 = FiberGraphChannel.pluck(:fee_rate_of_node2).compact
135+
combined_fee_rates = fee_rate_of_node1 + fee_rate_of_node2
136+
# 计算中位数
137+
medium_value_locked = calculate_median(capacities)
138+
medium_fee_rate = calculate_median(combined_fee_rates)
139+
created_at_unixtimestamp = Time.now.beginning_of_day.to_i
140+
FiberStatistic.upsert(
141+
{ total_nodes:, total_channels:, total_liquidity:,
142+
mean_value_locked:, mean_fee_rate:, medium_value_locked:,
143+
medium_fee_rate:, created_at_unixtimestamp: }, unique_by: %i[created_at_unixtimestamp]
144+
)
145+
end
146+
147+
def calculate_median(array)
148+
sorted = array.sort
149+
count = sorted.size
150+
return nil if count.zero?
151+
152+
if count.odd?
153+
sorted[count / 2] # 奇数个,取中间值
154+
else
155+
(sorted[(count / 2) - 1] + sorted[count / 2]).to_f / 2 # 偶数个,取中间两个的平均值
156+
end
157+
end
158+
127159
def rpc
128160
@rpc ||= FiberCoordinator.instance
129161
end
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class UpdateFiberChannelWorker
2+
include Sidekiq::Worker
3+
sidekiq_options queue: "fiber"
4+
5+
def perform
6+
# check channel is closed
7+
FiberGraphChannel.open_channels.each do |channel|
8+
funding_cell = channel.funding_cell
9+
if funding_cell.consumed_by
10+
channel.update(closed_transaction_id: funding_cell.consumed_by_id)
11+
end
12+
end
13+
end
14+
end

app/workers/update_h24_ckb_transactions_count_on_collections_worker.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ class UpdateH24CkbTransactionsCountOnCollectionsWorker
33
sidekiq_options queue: "low"
44

55
def perform
6+
TokenCollection.update_all(h24_ckb_transactions_count: 0)
67
TokenItem.joins(:collection).includes(:collection).where("token_items.updated_at > ?", 1.hour.ago).each do |item|
78
item.collection.update_h24_ckb_transactions_count
89
end

config/routes/v2.rb

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,8 +103,11 @@
103103
namespace :fiber do
104104
resources :peers, param: :peer_id, only: %i[index show create]
105105
resources :channels, param: :channel_id, only: :show
106-
resources :graph_nodes, param: :node_id, only: %i[index show]
106+
resources :graph_nodes, param: :node_id, only: %i[index show] do
107+
get :addresses, on: :collection
108+
end
107109
resources :graph_channels, only: :index
110+
resources :statistics, only: %i[index show]
108111
end
109112
resources :udt_hourly_statistics, only: :show
110113
resources :rgb_assets_statistics, only: :index
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class CreateFiberStatistics < ActiveRecord::Migration[7.0]
2+
def change
3+
create_table :fiber_statistics do |t|
4+
t.integer :total_nodes
5+
t.integer :total_channels
6+
t.bigint :total_liquidity
7+
t.bigint :mean_value_locked
8+
t.integer :mean_fee_rate
9+
t.bigint :medium_value_locked
10+
t.integer :medium_fee_rate
11+
t.integer :created_at_unixtimestamp
12+
13+
t.timestamps
14+
end
15+
16+
add_index :fiber_statistics, :created_at_unixtimestamp, unique: true
17+
end
18+
end

db/structure.sql

Lines changed: 62 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1865,6 +1865,44 @@ CREATE SEQUENCE public.fiber_peers_id_seq
18651865
ALTER SEQUENCE public.fiber_peers_id_seq OWNED BY public.fiber_peers.id;
18661866

18671867

1868+
--
1869+
-- Name: fiber_statistics; Type: TABLE; Schema: public; Owner: -
1870+
--
1871+
1872+
CREATE TABLE public.fiber_statistics (
1873+
id bigint NOT NULL,
1874+
total_nodes integer,
1875+
total_channels integer,
1876+
total_liquidity bigint,
1877+
mean_value_locked bigint,
1878+
mean_fee_rate integer,
1879+
medium_value_locked bigint,
1880+
medium_fee_rate integer,
1881+
created_at_unixtimestamp integer,
1882+
created_at timestamp(6) without time zone NOT NULL,
1883+
updated_at timestamp(6) without time zone NOT NULL
1884+
);
1885+
1886+
1887+
--
1888+
-- Name: fiber_statistics_id_seq; Type: SEQUENCE; Schema: public; Owner: -
1889+
--
1890+
1891+
CREATE SEQUENCE public.fiber_statistics_id_seq
1892+
START WITH 1
1893+
INCREMENT BY 1
1894+
NO MINVALUE
1895+
NO MAXVALUE
1896+
CACHE 1;
1897+
1898+
1899+
--
1900+
-- Name: fiber_statistics_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
1901+
--
1902+
1903+
ALTER SEQUENCE public.fiber_statistics_id_seq OWNED BY public.fiber_statistics.id;
1904+
1905+
18681906
--
18691907
-- Name: fiber_transactions; Type: TABLE; Schema: public; Owner: -
18701908
--
@@ -3311,6 +3349,13 @@ ALTER TABLE ONLY public.fiber_graph_nodes ALTER COLUMN id SET DEFAULT nextval('p
33113349
ALTER TABLE ONLY public.fiber_peers ALTER COLUMN id SET DEFAULT nextval('public.fiber_peers_id_seq'::regclass);
33123350

33133351

3352+
--
3353+
-- Name: fiber_statistics id; Type: DEFAULT; Schema: public; Owner: -
3354+
--
3355+
3356+
ALTER TABLE ONLY public.fiber_statistics ALTER COLUMN id SET DEFAULT nextval('public.fiber_statistics_id_seq'::regclass);
3357+
3358+
33143359
--
33153360
-- Name: fiber_transactions id; Type: DEFAULT; Schema: public; Owner: -
33163361
--
@@ -3889,6 +3934,14 @@ ALTER TABLE ONLY public.fiber_peers
38893934
ADD CONSTRAINT fiber_peers_pkey PRIMARY KEY (id);
38903935

38913936

3937+
--
3938+
-- Name: fiber_statistics fiber_statistics_pkey; Type: CONSTRAINT; Schema: public; Owner: -
3939+
--
3940+
3941+
ALTER TABLE ONLY public.fiber_statistics
3942+
ADD CONSTRAINT fiber_statistics_pkey PRIMARY KEY (id);
3943+
3944+
38923945
--
38933946
-- Name: fiber_transactions fiber_transactions_pkey; Type: CONSTRAINT; Schema: public; Owner: -
38943947
--
@@ -5085,6 +5138,13 @@ CREATE UNIQUE INDEX index_fiber_graph_nodes_on_node_id ON public.fiber_graph_nod
50855138
CREATE UNIQUE INDEX index_fiber_peers_on_peer_id ON public.fiber_peers USING btree (peer_id);
50865139

50875140

5141+
--
5142+
-- Name: index_fiber_statistics_on_created_at_unixtimestamp; Type: INDEX; Schema: public; Owner: -
5143+
--
5144+
5145+
CREATE UNIQUE INDEX index_fiber_statistics_on_created_at_unixtimestamp ON public.fiber_statistics USING btree (created_at_unixtimestamp);
5146+
5147+
50885148
--
50895149
-- Name: index_fiber_udt_cfg_infos_on_fiber_graph_node_id_and_udt_id; Type: INDEX; Schema: public; Owner: -
50905150
--
@@ -6318,6 +6378,7 @@ INSERT INTO "schema_migrations" (version) VALUES
63186378
('20241225045757'),
63196379
('20241231022644'),
63206380
('20250103072945'),
6321-
('20250108053433');
6381+
('20250108053433'),
6382+
('20250126022459');
63226383

63236384

0 commit comments

Comments
 (0)