From 6d57d0bf83e60c66e311054204e304eacf655217 Mon Sep 17 00:00:00 2001 From: Rabbit Date: Tue, 12 Dec 2023 12:01:51 +0800 Subject: [PATCH 1/8] feat: search by type id (#1530) --- app/models/suggest_query.rb | 11 ++++++++++- .../api/v1/suggest_queries_controller_test.rb | 12 ++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/app/models/suggest_query.rb b/app/models/suggest_query.rb index d53e613ef..84afbec93 100644 --- a/app/models/suggest_query.rb +++ b/app/models/suggest_query.rb @@ -55,7 +55,16 @@ def find_udt_by_type_hash UdtSerializer.new(udt) if udt.present? end + def find_type_script_by_type_id + type_script = TypeScript.find_by(script_hash: query_key) + { data: { args: type_script.args } } if type_script.present? + end + def find_by_hex - Block.cached_find(query_key) || find_ckb_transaction_by_hash || find_address_by_lock_hash || find_udt_by_type_hash + Block.cached_find(query_key) || + find_ckb_transaction_by_hash || + find_address_by_lock_hash || + find_udt_by_type_hash || + find_type_script_by_type_id end end diff --git a/test/controllers/api/v1/suggest_queries_controller_test.rb b/test/controllers/api/v1/suggest_queries_controller_test.rb index c6bec9e09..3adcec79d 100644 --- a/test/controllers/api/v1/suggest_queries_controller_test.rb +++ b/test/controllers/api/v1/suggest_queries_controller_test.rb @@ -185,6 +185,18 @@ class SuggestQueriesControllerTest < ActionDispatch::IntegrationTest assert_equal response_json, response.body end + + test "should return a type_script when query key is a exist script hash" do + type_script = create( + :type_script, + code_hash: Settings.type_id_code_hash, + script_hash: "0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8" + ) + + valid_get api_v1_suggest_queries_url, params: { q: type_script.script_hash } + + assert_equal type_script.args, json.dig("data", "args") + end end end end From 54d5fe60f9ecbfe76ea316a6d401bd92f6dd0c18 Mon Sep 17 00:00:00 2001 From: Rabbit Date: Wed, 13 Dec 2023 17:16:48 +0800 Subject: [PATCH 2/8] fix: scripts query empty result lead deadlock (#1532) --- app/controllers/api/v2/scripts_controller.rb | 21 +++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/app/controllers/api/v2/scripts_controller.rb b/app/controllers/api/v2/scripts_controller.rb index 41347a4d9..c9835741e 100644 --- a/app/controllers/api/v2/scripts_controller.rb +++ b/app/controllers/api/v2/scripts_controller.rb @@ -17,21 +17,36 @@ def ckb_transactions head :not_found and return if @contract.blank? expires_in 15.seconds, public: true, must_revalidate: true, stale_while_revalidate: 5.seconds - @ckb_transactions = @contract.ckb_transactions.order(id: :desc).page(@page).per(@page_size) + @ckb_transactions = + if @contract.ckb_transactions_count.zero? + CkbTransaction.none + else + @contract.ckb_transactions.order(id: :desc).page(@page).per(@page_size) + end end def deployed_cells head :not_found and return if @contract.blank? expires_in 15.seconds, public: true, must_revalidate: true, stale_while_revalidate: 5.seconds - @deployed_cells = @contract.deployed_cell_outputs.live.page(@page).per(@page_size) + @deployed_cells = + if @contract.deployed_cells_count.zero? + CellOutput.none + else + @contract.deployed_cell_outputs.live.page(@page).per(@page_size) + end end def referring_cells head :not_found and return if @contract.blank? expires_in 15.seconds, public: true, must_revalidate: true, stale_while_revalidate: 5.seconds - @referring_cells = @contract.referring_cell_outputs.live.page(@page).per(@page_size) + @referring_cells = + if @contract.referring_cells_count.zero? + CellOutput.none + else + @contract.referring_cell_outputs.live.page(@page).per(@page_size) + end end private From 8e1d98e70f89ab8094e718905e4ffa316020c866 Mon Sep 17 00:00:00 2001 From: Rabbit Date: Thu, 14 Dec 2023 09:56:05 +0800 Subject: [PATCH 3/8] fix: type id search using typescript args (#1533) * fix: type id search using typescript args * chore: adjust tests --- app/models/suggest_query.rb | 4 ++-- app/serializers/type_script_serializer.rb | 2 +- .../api/v1/cell_input_type_scripts_controller_test.rb | 2 +- .../api/v1/cell_output_type_scripts_controller_test.rb | 2 +- test/controllers/api/v1/suggest_queries_controller_test.rb | 6 ++++-- 5 files changed, 9 insertions(+), 7 deletions(-) diff --git a/app/models/suggest_query.rb b/app/models/suggest_query.rb index 84afbec93..1940b3c05 100644 --- a/app/models/suggest_query.rb +++ b/app/models/suggest_query.rb @@ -56,8 +56,8 @@ def find_udt_by_type_hash end def find_type_script_by_type_id - type_script = TypeScript.find_by(script_hash: query_key) - { data: { args: type_script.args } } if type_script.present? + type_script = TypeScript.find_by(args: query_key, code_hash: Settings.type_id_code_hash) + TypeScriptSerializer.new(type_script) if type_script.present? end def find_by_hex diff --git a/app/serializers/type_script_serializer.rb b/app/serializers/type_script_serializer.rb index 017e2120f..fcc6585e9 100644 --- a/app/serializers/type_script_serializer.rb +++ b/app/serializers/type_script_serializer.rb @@ -1,5 +1,5 @@ class TypeScriptSerializer include FastJsonapi::ObjectSerializer - attributes :args, :code_hash, :hash_type + attributes :args, :code_hash, :hash_type, :script_hash end diff --git a/test/controllers/api/v1/cell_input_type_scripts_controller_test.rb b/test/controllers/api/v1/cell_input_type_scripts_controller_test.rb index b277ea390..8f5ce45f4 100644 --- a/test/controllers/api/v1/cell_input_type_scripts_controller_test.rb +++ b/test/controllers/api/v1/cell_input_type_scripts_controller_test.rb @@ -78,7 +78,7 @@ class CellInputTypeScriptsControllerTest < ActionDispatch::IntegrationTest valid_get api_v1_cell_input_type_script_url(cell_input.id) - assert_equal %w(args code_hash hash_type).sort, json["data"]["attributes"].keys.sort + assert_equal %w(args code_hash hash_type script_hash).sort, json["data"]["attributes"].keys.sort end test "should return error object when no cell input found by id" do diff --git a/test/controllers/api/v1/cell_output_type_scripts_controller_test.rb b/test/controllers/api/v1/cell_output_type_scripts_controller_test.rb index 33662845e..fd359b6bb 100644 --- a/test/controllers/api/v1/cell_output_type_scripts_controller_test.rb +++ b/test/controllers/api/v1/cell_output_type_scripts_controller_test.rb @@ -86,7 +86,7 @@ class CellOutputTypeScriptsControllerTest < ActionDispatch::IntegrationTest valid_get api_v1_cell_output_type_script_url(cell_output.id) - assert_equal %w(args code_hash hash_type).sort, json["data"]["attributes"].keys.sort + assert_equal %w(args code_hash hash_type script_hash).sort, json["data"]["attributes"].keys.sort end test "should return error object when no cell output found by id" do diff --git a/test/controllers/api/v1/suggest_queries_controller_test.rb b/test/controllers/api/v1/suggest_queries_controller_test.rb index 3adcec79d..90c644bf2 100644 --- a/test/controllers/api/v1/suggest_queries_controller_test.rb +++ b/test/controllers/api/v1/suggest_queries_controller_test.rb @@ -190,12 +190,14 @@ class SuggestQueriesControllerTest < ActionDispatch::IntegrationTest type_script = create( :type_script, code_hash: Settings.type_id_code_hash, + args: "0x2ab17f74009a9948ae2d3623dac853cc3ff1ef8270304ea5d9980b1f2b6810d5", script_hash: "0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8" ) + response_json = TypeScriptSerializer.new(type_script).serialized_json - valid_get api_v1_suggest_queries_url, params: { q: type_script.script_hash } + valid_get api_v1_suggest_queries_url, params: { q: type_script.args } - assert_equal type_script.args, json.dig("data", "args") + assert_equal response_json, response.body end end end From 291581d28aa6f7cc791dd59deb891ac55e4f56de Mon Sep 17 00:00:00 2001 From: Miles Zhang Date: Tue, 19 Dec 2023 10:32:02 +0800 Subject: [PATCH 4/8] Issue 424 (#1534) * chore: use latest thoughtbot rubocop yml Signed-off-by: Miles Zhang * feat: add ckb_hodl_waves column to statistic_infos Signed-off-by: Miles Zhang * feat: run job to calculate ckb_hodl_waves Signed-off-by: Miles Zhang * feat: add ckb_hodl_waves to api Signed-off-by: Miles Zhang * fix: typo Signed-off-by: Miles Zhang --------- Signed-off-by: Miles Zhang --- .rubocop.yml | 665 +++++++++++++++--- .rubocop_thoughtbot.yml | 650 ----------------- app/models/statistic_info.rb | 26 +- app/serializers/statistic_serializer.rb | 4 + .../charts/ckb_hodl_waves_statistic.rb | 49 ++ ...38_add_ckb_hodl_waves_to_statistic_info.rb | 5 + db/structure.sql | 6 +- lib/scheduler.rb | 8 +- .../api/v1/statistics_controller_test.rb | 74 +- test/factories/statistic_infos.rb | 1 + 10 files changed, 686 insertions(+), 802 deletions(-) mode change 100644 => 100755 .rubocop.yml delete mode 100644 .rubocop_thoughtbot.yml create mode 100644 app/workers/charts/ckb_hodl_waves_statistic.rb create mode 100644 db/migrate/20231218082938_add_ckb_hodl_waves_to_statistic_info.rb diff --git a/.rubocop.yml b/.rubocop.yml old mode 100644 new mode 100755 index 72562a7b2..94304388b --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,222 +1,653 @@ -inherit_from: - - .rubocop_thoughtbot.yml -inherit_mode: - merge: - - Exclude -require: - - rubocop-performance - - rubocop-rails AllCops: - DisplayCopNames: true - DisplayStyleGuide: true Exclude: - - vendor/**/* - - app/controllers/devise/users/registrations_controller.rb - - app/javascript/**/* - - config/routes/manager.rb - - lib/**/* - - db/migrate/* - - db/seed.rb - - node_modules/**/* - - bin/* - ExtraDetails: true - TargetRubyVersion: 3.0 + - db/schema.rb +require: + - rubocop-rails + - rubocop-performance -# ThoughtBot Overwrite - -Style/TrailingCommaInHashLiteral: +Naming/AccessorMethodName: + Description: Check the naming of accessor methods for get_/set_. Enabled: false -Style/TrailingCommaInArguments: - EnforcedStyleForMultiline: no_comma +Style/Alias: + Description: 'Use alias_method instead of alias.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#alias-method' + Enabled: false -Style/TrailingCommaInArrayLiteral: - EnforcedStyleForMultiline: no_comma +Style/ArrayJoin: + Description: 'Use Array#join instead of Array#*.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#array-join' + Enabled: false -Style/TrailingCommaInHashLiteral: - EnforcedStyleForMultiline: no_comma +Style/AsciiComments: + Description: 'Use only ascii symbols in comments.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#english-comments' + Enabled: false -Metrics/LineLength: - Description: 'Limit lines to 80 characters.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#80-character-limits' - Max: 120 +Naming/AsciiIdentifiers: + Description: 'Use only ascii symbols in identifiers.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#english-identifiers' + Enabled: false -Layout/FirstHashElementIndentation: - EnforcedStyle: consistent +Style/Attr: + Description: 'Checks for uses of Module#attr.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#attr' + Enabled: false -Style/BlockDelimiters: - EnforcedStyle: braces_for_chaining +Metrics/BlockNesting: + Description: 'Avoid excessive block nesting' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#three-is-the-number-thou-shalt-count' + Enabled: false -Style/SymbolArray: +Style/CaseEquality: + Description: 'Avoid explicit use of the case equality operator(===).' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-case-equality' Enabled: false -Lint/AmbiguousBlockAssociation: - Exclude: - - spec/**/* +Style/CharacterLiteral: + Description: 'Checks for uses of character literals.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-character-literals' + Enabled: false -Lint/UselessAssignment: - Exclude: - - spec/**/* +Style/ClassAndModuleChildren: + Description: 'Checks style of children classes and modules.' + Enabled: true + EnforcedStyle: nested -Naming/VariableNumber: - Exclude: - - spec/**/* +Metrics/ClassLength: + Description: 'Avoid classes longer than 100 lines of code.' + Enabled: false -Rails/DynamicFindBy: +Metrics/ModuleLength: + Description: 'Avoid modules longer than 100 lines of code.' Enabled: false -Metrics/ClassLength: +Style/ClassVars: + Description: 'Avoid the use of class variables.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-class-vars' Enabled: false -Metrics/PerceivedComplexity: +Style/CollectionMethods: + Enabled: true + PreferredMethods: + find: detect + inject: reduce + collect: map + find_all: select + +Style/ColonMethodCall: + Description: 'Do not use :: for method call.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#double-colons' Enabled: false -Metrics/BlockNesting: - Exclude: - - app/workers/coins/sync/eth_blocks.rb +Style/CommentAnnotation: + Description: >- + Checks formatting of special comments + (TODO, FIXME, OPTIMIZE, HACK, REVIEW). + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#annotate-keywords' + Enabled: false -Metrics/ModuleLength: - Max: 200 +Metrics/AbcSize: + Description: >- + A calculated magnitude based on number of assignments, + branches, and conditions. + Enabled: false Metrics/BlockLength: - CountComments: true + CountComments: true # count full line comments? Max: 25 - ExcludedMethods: [] Exclude: - - "test/**/*" - - "config/environments/**/*" + - "spec/**/*" -Style/For: +Metrics/CyclomaticComplexity: + Description: >- + A complexity metric that is strongly correlated to the number + of test cases needed to validate a method. Enabled: false -Style/AsciiComments: +Rails/Delegate: + Description: 'Prefer delegate method for delegations.' Enabled: false -Rails: - Enabled: true +Style/PreferredHashMethods: + Description: 'Checks use of `has_key?` and `has_value?` Hash methods.' + StyleGuide: '#hash-key' + Enabled: false -Rails/FilePath: +Style/Documentation: + Description: 'Document classes and non-namespace modules.' Enabled: false -Style/AutoResourceCleanup: - Enabled: true +Style/DoubleNegation: + Description: 'Checks for uses of double negation (!!).' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-bang-bang' + Enabled: false + +Style/EachWithObject: + Description: 'Prefer `each_with_object` over `inject` or `reduce`.' + Enabled: false -Style/BlockDelimiters: - EnforcedStyle: braces_for_chaining +Style/EmptyLiteral: + Description: 'Prefer literals to Array.new/Hash.new/String.new.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#literal-array-hash' + Enabled: false -Layout/FirstArrayElementLineBreak: - Enabled: true +# Checks whether the source file has a utf-8 encoding comment or not +# AutoCorrectEncodingComment must match the regex +# /#.*coding\s?[:=]\s?(?:UTF|utf)-8/ +Style/Encoding: + Enabled: false -Layout/FirstHashElementLineBreak: - Enabled: true +Style/EvenOdd: + Description: 'Favor the use of Fixnum#even? && Fixnum#odd?' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#predicate-methods' + Enabled: false -Layout/FirstMethodArgumentLineBreak: - Enabled: true +Naming/FileName: + Description: 'Use snake_case for source file names.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#snake-case-files' + Enabled: false -Layout/FirstMethodParameterLineBreak: - Enabled: true +Style/FrozenStringLiteralComment: + Description: >- + Add the frozen_string_literal comment to the top of files + to help transition from Ruby 2.3.0 to Ruby 3.0. + Enabled: false + +Lint/FlipFlop: + Description: 'Checks for flip flops' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-flip-flops' + Enabled: false -Style/MethodCalledOnDoEndBlock: +Style/FormatString: + Description: 'Enforce the use of Kernel#sprintf, Kernel#format or String#%.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#sprintf' + Enabled: false + +Style/GlobalVars: + Description: 'Do not introduce global variables.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#instance-vars' + Reference: 'http://www.zenspider.com/Languages/Ruby/QuickRef.html' + Enabled: false + +Style/GuardClause: + Description: 'Check for conditionals that can be replaced with guard clauses' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-nested-conditionals' + Enabled: false + +Style/IfUnlessModifier: + Description: >- + Favor modifier if/unless usage when you have a + single-line body. + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#if-as-a-modifier' + Enabled: false + +Style/IfWithSemicolon: + Description: 'Do not use if x; .... Use the ternary operator instead.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-semicolon-ifs' + Enabled: false + +Style/InlineComment: + Description: 'Avoid inline comments.' + Enabled: false + +Style/Lambda: + Description: 'Use the new lambda literal syntax for single-line blocks.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#lambda-multi-line' + Enabled: false + +Style/LambdaCall: + Description: 'Use lambda.call(...) instead of lambda.(...).' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#proc-call' + Enabled: false + +Style/LineEndConcatenation: + Description: >- + Use \ instead of + or << to concatenate two string literals at + line end. + Enabled: false + +Metrics/MethodLength: + Description: 'Avoid methods longer than 10 lines of code.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#short-methods' + Enabled: false + +Style/ModuleFunction: + Description: 'Checks for usage of `extend self` in modules.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#module-function' + Enabled: false + +Style/MultilineBlockChain: + Description: 'Avoid multi-line chains of blocks.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#single-line-blocks' + Enabled: false + +Style/NegatedIf: + Description: >- + Favor unless over if for negative conditions + (or control flow or). + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#unless-for-negatives' + Enabled: false + +Style/NegatedWhile: + Description: 'Favor until over while for negative conditions.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#until-for-negatives' + Enabled: false + +Style/Next: + Description: 'Use `next` to skip iteration instead of a condition at the end.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-nested-conditionals' + Enabled: false + +Style/NilComparison: + Description: 'Prefer x.nil? to x == nil.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#predicate-methods' + Enabled: false + +Style/Not: + Description: 'Use ! instead of not.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#bang-not-not' + Enabled: false + +Style/NumericLiterals: + Description: >- + Add underscores to large numeric literals to improve their + readability. + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#underscores-in-numerics' + Enabled: false + +Style/OneLineConditional: + Description: >- + Favor the ternary operator(?:) over + if/then/else/end constructs. + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#ternary-operator' + Enabled: false + +Naming/BinaryOperatorParameterName: + Description: 'When defining binary operators, name the argument other.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#other-arg' + Enabled: false + +Metrics/ParameterLists: + Description: 'Avoid parameter lists longer than three or four parameters.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#too-many-params' + Enabled: false + +Style/PercentLiteralDelimiters: + Description: 'Use `%`-literal delimiters consistently' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#percent-literal-braces' + Enabled: false + +Style/PerlBackrefs: + Description: 'Avoid Perl-style regex back references.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-perl-regexp-last-matchers' + Enabled: false + +Naming/PredicateName: + Description: 'Check the names of predicate methods.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#bool-methods-qmark' + ForbiddenPrefixes: + - is_ + Exclude: + - spec/**/* + +Style/Proc: + Description: 'Use proc instead of Proc.new.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#proc' + Enabled: false + +Style/RaiseArgs: + Description: 'Checks the arguments passed to raise/fail.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#exception-class-messages' + Enabled: false + +Style/RegexpLiteral: + Description: 'Use / or %r around regular expressions.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#percent-r' + Enabled: false + +Style/Sample: + Description: >- + Use `sample` instead of `shuffle.first`, + `shuffle.last`, and `shuffle[Fixnum]`. + Reference: 'https://github.com/JuanitoFatas/fast-ruby#arrayshufflefirst-vs-arraysample-code' + Enabled: false + +Style/SelfAssignment: + Description: >- + Checks for places where self-assignment shorthand should have + been used. + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#self-assignment' + Enabled: false + +Style/SingleLineBlockParams: + Description: 'Enforces the names of some block params.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#reduce-blocks' + Enabled: false + +Style/SingleLineMethods: + Description: 'Avoid single-line methods.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-single-line-methods' + Enabled: false + +Style/SignalException: + Description: 'Checks for proper usage of fail and raise.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#fail-method' + Enabled: false + +Style/SpecialGlobalVars: + Description: 'Avoid Perl-style global variables.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-cryptic-perlisms' + Enabled: false + +Style/StringLiterals: + Description: 'Checks if uses of quotes match the configured preference.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#consistent-string-literals' + EnforcedStyle: double_quotes Enabled: true -Layout/MultilineArrayBraceLayout: +Style/TrailingCommaInArguments: + Description: 'Checks for trailing comma in argument lists.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-trailing-array-commas' + EnforcedStyleForMultiline: comma + SupportedStylesForMultiline: + - comma + - consistent_comma + - no_comma Enabled: true -Layout/MultilineAssignmentLayout: +Style/TrailingCommaInArrayLiteral: + Description: 'Checks for trailing comma in array literals.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-trailing-array-commas' + EnforcedStyleForMultiline: comma + SupportedStylesForMultiline: + - comma + - consistent_comma + - no_comma Enabled: true -Layout/MultilineHashBraceLayout: +Style/TrailingCommaInHashLiteral: + Description: 'Checks for trailing comma in hash literals.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-trailing-array-commas' + EnforcedStyleForMultiline: comma + SupportedStylesForMultiline: + - comma + - consistent_comma + - no_comma Enabled: true -Layout/MultilineMethodCallBraceLayout: +Style/TrivialAccessors: + Description: 'Prefer attr_* methods to trivial readers/writers.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#attr_family' + Enabled: false + +Style/VariableInterpolation: + Description: >- + Don't interpolate global, instance and class variables + directly in strings. + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#curlies-interpolate' + Enabled: false + +Style/WhenThen: + Description: 'Use when x then ... for one-line cases.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#one-line-cases' + Enabled: false + +Style/WhileUntilModifier: + Description: >- + Favor modifier while/until usage when you have a + single-line body. + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#while-as-a-modifier' + Enabled: false + +Style/WordArray: + Description: 'Use %w or %W for arrays of words.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#percent-w' + Enabled: false + +# Layout + +Layout/ParameterAlignment: + Description: 'Here we check if the parameters on a multi-line method call or definition are aligned.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-double-indent' + Enabled: false + +Layout/ConditionPosition: + Description: >- + Checks for condition placed in a confusing position relative to + the keyword. + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#same-line-condition' + Enabled: false + +Layout/DotPosition: + Description: 'Checks the position of the dot in multi-line method calls.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#consistent-multi-line-chains' + EnforcedStyle: trailing + +Layout/ExtraSpacing: + Description: 'Do not use unnecessary spacing.' Enabled: true -Layout/MultilineMethodDefinitionBraceLayout: +Layout/MultilineOperationIndentation: + Description: >- + Checks indentation of binary operations that span more than + one line. Enabled: true + EnforcedStyle: indented -Style/OptionHash: +Layout/MultilineMethodCallIndentation: + Description: >- + Checks indentation of method calls with the dot operator + that span more than one line. Enabled: true + EnforcedStyle: indented + +Layout/InitialIndentation: + Description: >- + Checks the indentation of the first non-blank non-comment line in a file. + Enabled: false + +Layout/LineLength: + Description: 'Limit lines to 80 characters.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#80-character-limits' + Max: 80 + +# Lint -Style/RescueModifier: +Lint/AmbiguousOperator: + Description: >- + Checks for ambiguous operators in the first argument of a + method invocation without parentheses. + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#parens-as-args' Enabled: false -Style/SafeNavigation: +Lint/AmbiguousRegexpLiteral: + Description: >- + Checks for ambiguous regexp literals in the first argument of + a method invocation without parenthesis. Enabled: false -Style/Send: - Enabled: true +Lint/AssignmentInCondition: + Description: "Don't use assignment in conditions." + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#safe-assignment-in-condition' + Enabled: false -Style/StringMethods: - Enabled: true +Lint/CircularArgumentReference: + Description: "Don't refer to the keyword argument in the default value." + Enabled: false -Style/RedundantSelf: +Lint/DeprecatedClassMethods: + Description: 'Check for deprecated class method calls.' Enabled: false -Rails/SkipsModelValidations: +Lint/DuplicateHashKey: + Description: 'Check for duplicate keys in hash literals.' Enabled: false -Rails/ApplicationRecord: - Exclude: - - 'app/models/withdraw.rb' +Lint/EachWithObjectArgument: + Description: 'Check for immutable argument given to each_with_object.' + Enabled: false -Style/BlockComments: - Exclude: - - 'spec/spec_helper.rb' +Lint/ElseLayout: + Description: 'Check for odd code arrangement in an else block.' + Enabled: false -Rails/ReversibleMigration: +Lint/FormatParameterMismatch: + Description: 'The number of parameters to format/sprint must match the fields.' Enabled: false -Bundler/OrderedGems: +Lint/SuppressedException: + Description: "Don't suppress exception." + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#dont-hide-exceptions' Enabled: false -Layout/MultilineHashBraceLayout: +Lint/LiteralAsCondition: + Description: 'Checks of literals used in conditions.' Enabled: false -Style/EmptyMethod: +Lint/LiteralInInterpolation: + Description: 'Checks for literals used in interpolation.' Enabled: false -Lint/UnusedMethodArgument: +Lint/Loop: + Description: >- + Use Kernel#loop with break rather than begin/end/until or + begin/end/while for post-loop tests. + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#loop-with-break' Enabled: false -Layout/CaseIndentation: +Lint/NestedMethodDefinition: + Description: 'Do not use nested method definitions.' + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-nested-methods' Enabled: false -Style/RedundantReturn: +Lint/NonLocalExitFromIterator: + Description: 'Do not use return in iterator to cause non-local exit.' Enabled: false -Style/IdenticalConditionalBranches: +Lint/ParenthesesAsGroupedExpression: + Description: >- + Checks for method calls with a space before the opening + parenthesis. + StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#parens-no-spaces' Enabled: false -FirstMethodArgumentLineBreak: +Lint/RequireParentheses: + Description: >- + Use parentheses in the method call to avoid confusion + about precedence. Enabled: false -SymbolProc: +Lint/UnderscorePrefixedVariableName: + Description: 'Do not use prefix `_` for a variable that is used.' + Enabled: false + +Lint/RedundantCopDisableDirective: + Description: >- + Checks for rubocop:disable comments that can be removed. + Note: this cop is not disabled when disabling all cops. + It must be explicitly disabled. + Enabled: false + +Lint/Void: + Description: 'Possible use of operator/literal/variable in void context.' + Enabled: false + +# Performance + +Performance/CaseWhenSplat: + Description: >- + Place `when` conditions that use splat at the end + of the list of `when` branches. + Enabled: false + +Performance/Count: + Description: >- + Use `count` instead of `select...size`, `reject...size`, + `select...count`, `reject...count`, `select...length`, + and `reject...length`. + Enabled: false + +Performance/Detect: + Description: >- + Use `detect` instead of `select.first`, `find_all.first`, + `select.last`, and `find_all.last`. + Reference: 'https://github.com/JuanitoFatas/fast-ruby#enumerabledetect-vs-enumerableselectfirst-code' + Enabled: false + +Performance/FlatMap: + Description: >- + Use `Enumerable#flat_map` + instead of `Enumerable#map...Array#flatten(1)` + or `Enumberable#collect..Array#flatten(1)` + Reference: 'https://github.com/JuanitoFatas/fast-ruby#enumerablemaparrayflatten-vs-enumerableflat_map-code' + Enabled: false + +Performance/ReverseEach: + Description: 'Use `reverse_each` instead of `reverse.each`.' + Reference: 'https://github.com/JuanitoFatas/fast-ruby#enumerablereverseeach-vs-enumerablereverse_each-code' + Enabled: false + +Performance/Size: + Description: >- + Use `size` instead of `count` for counting + the number of elements in `Array` and `Hash`. + Reference: 'https://github.com/JuanitoFatas/fast-ruby#arraycount-vs-arraysize-code' + Enabled: false + +Performance/StringReplacement: + Description: >- + Use `tr` instead of `gsub` when you are replacing the same + number of characters. Use `delete` instead of `gsub` when + you are deleting characters. + Reference: 'https://github.com/JuanitoFatas/fast-ruby#stringgsub-vs-stringtr-code' + Enabled: false + +# Rails + +Rails/ActionFilter: + Description: 'Enforces consistent use of action filter methods.' Enabled: false -ParenthesesAroundCondition: +Rails/Date: + Description: >- + Checks the correct usage of date aware methods, + such as Date.today, Date.current etc. Enabled: false -Style/OptionHash: +Rails/FindBy: + Description: 'Prefer find_by over where.first.' Enabled: false -Style/RedundantParentheses: +Rails/FindEach: + Description: 'Prefer all.find_each over all.find.' Enabled: false -Style/Send: +Rails/HasAndBelongsToMany: + Description: 'Prefer has_many :through to has_and_belongs_to_many.' Enabled: false -Style/ConditionalAssignment: +Rails/Output: + Description: 'Checks for calls to puts, print, etc.' Enabled: false -Rails/HasManyOrHasOneDependent: +Rails/ReadWriteAttribute: + Description: >- + Checks for read_attribute(:attr) and + write_attribute(:attr, val). Enabled: false -Lint/ShadowingOuterLocalVariable: +Rails/ScopeArgs: + Description: 'Checks the arguments of ActiveRecord scopes.' Enabled: false -Style/RescueStandardError: +Rails/TimeZone: + Description: 'Checks the correct usage of time zone aware methods.' + StyleGuide: 'https://github.com/bbatsov/rails-style-guide#time' + Reference: 'http://danilenko.org/2012/7/6/rails_timezones' Enabled: false -Style/NumericPredicate: +Rails/Validation: + Description: 'Use validates :attribute, hash of validations.' Enabled: false diff --git a/.rubocop_thoughtbot.yml b/.rubocop_thoughtbot.yml deleted file mode 100644 index b12f77d99..000000000 --- a/.rubocop_thoughtbot.yml +++ /dev/null @@ -1,650 +0,0 @@ -AllCops: - Exclude: - - db/schema.rb - -Naming/AccessorMethodName: - Description: Check the naming of accessor methods for get_/set_. - Enabled: false - -Style/Alias: - Description: 'Use alias_method instead of alias.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#alias-method' - Enabled: false - -Style/ArrayJoin: - Description: 'Use Array#join instead of Array#*.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#array-join' - Enabled: false - -Style/AsciiComments: - Description: 'Use only ascii symbols in comments.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#english-comments' - Enabled: false - -Naming/AsciiIdentifiers: - Description: 'Use only ascii symbols in identifiers.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#english-identifiers' - Enabled: false - -Style/Attr: - Description: 'Checks for uses of Module#attr.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#attr' - Enabled: false - -Metrics/BlockNesting: - Description: 'Avoid excessive block nesting' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#three-is-the-number-thou-shalt-count' - Enabled: false - -Style/CaseEquality: - Description: 'Avoid explicit use of the case equality operator(===).' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-case-equality' - Enabled: false - -Style/CharacterLiteral: - Description: 'Checks for uses of character literals.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-character-literals' - Enabled: false - -Style/ClassAndModuleChildren: - Description: 'Checks style of children classes and modules.' - Enabled: true - EnforcedStyle: nested - -Metrics/ClassLength: - Description: 'Avoid classes longer than 100 lines of code.' - Enabled: false - -Metrics/ModuleLength: - Description: 'Avoid modules longer than 100 lines of code.' - Enabled: false - -Style/ClassVars: - Description: 'Avoid the use of class variables.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-class-vars' - Enabled: false - -Style/CollectionMethods: - Enabled: true - PreferredMethods: - find: detect - inject: reduce - collect: map - find_all: select - -Style/ColonMethodCall: - Description: 'Do not use :: for method call.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#double-colons' - Enabled: false - -Style/CommentAnnotation: - Description: >- - Checks formatting of special comments - (TODO, FIXME, OPTIMIZE, HACK, REVIEW). - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#annotate-keywords' - Enabled: false - -Metrics/AbcSize: - Description: >- - A calculated magnitude based on number of assignments, - branches, and conditions. - Enabled: false - -Metrics/BlockLength: - CountComments: true # count full line comments? - Max: 25 - ExcludedMethods: [] - Exclude: - - "spec/**/*" - -Metrics/CyclomaticComplexity: - Description: >- - A complexity metric that is strongly correlated to the number - of test cases needed to validate a method. - Enabled: false - -Rails/Delegate: - Description: 'Prefer delegate method for delegations.' - Enabled: false - -Style/PreferredHashMethods: - Description: 'Checks use of `has_key?` and `has_value?` Hash methods.' - StyleGuide: '#hash-key' - Enabled: false - -Style/Documentation: - Description: 'Document classes and non-namespace modules.' - Enabled: false - -Style/DoubleNegation: - Description: 'Checks for uses of double negation (!!).' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-bang-bang' - Enabled: false - -Style/EachWithObject: - Description: 'Prefer `each_with_object` over `inject` or `reduce`.' - Enabled: false - -Style/EmptyLiteral: - Description: 'Prefer literals to Array.new/Hash.new/String.new.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#literal-array-hash' - Enabled: false - -# Checks whether the source file has a utf-8 encoding comment or not -# AutoCorrectEncodingComment must match the regex -# /#.*coding\s?[:=]\s?(?:UTF|utf)-8/ -Style/Encoding: - Enabled: false - -Style/EvenOdd: - Description: 'Favor the use of Fixnum#even? && Fixnum#odd?' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#predicate-methods' - Enabled: false - -Naming/FileName: - Description: 'Use snake_case for source file names.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#snake-case-files' - Enabled: false - -Style/FrozenStringLiteralComment: - Description: >- - Add the frozen_string_literal comment to the top of files - to help transition from Ruby 2.3.0 to Ruby 3.0. - Enabled: false - -Lint/FlipFlop: - Description: 'Checks for flip flops' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-flip-flops' - Enabled: false - -Style/FormatString: - Description: 'Enforce the use of Kernel#sprintf, Kernel#format or String#%.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#sprintf' - Enabled: false - -Style/GlobalVars: - Description: 'Do not introduce global variables.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#instance-vars' - Reference: 'http://www.zenspider.com/Languages/Ruby/QuickRef.html' - Enabled: false - -Style/GuardClause: - Description: 'Check for conditionals that can be replaced with guard clauses' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-nested-conditionals' - Enabled: false - -Style/IfUnlessModifier: - Description: >- - Favor modifier if/unless usage when you have a - single-line body. - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#if-as-a-modifier' - Enabled: false - -Style/IfWithSemicolon: - Description: 'Do not use if x; .... Use the ternary operator instead.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-semicolon-ifs' - Enabled: false - -Style/InlineComment: - Description: 'Avoid inline comments.' - Enabled: false - -Style/Lambda: - Description: 'Use the new lambda literal syntax for single-line blocks.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#lambda-multi-line' - Enabled: false - -Style/LambdaCall: - Description: 'Use lambda.call(...) instead of lambda.(...).' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#proc-call' - Enabled: false - -Style/LineEndConcatenation: - Description: >- - Use \ instead of + or << to concatenate two string literals at - line end. - Enabled: false - -Metrics/LineLength: - Description: 'Limit lines to 80 characters.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#80-character-limits' - Max: 80 - -Metrics/MethodLength: - Description: 'Avoid methods longer than 10 lines of code.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#short-methods' - Enabled: false - -Style/ModuleFunction: - Description: 'Checks for usage of `extend self` in modules.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#module-function' - Enabled: false - -Style/MultilineBlockChain: - Description: 'Avoid multi-line chains of blocks.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#single-line-blocks' - Enabled: false - -Style/NegatedIf: - Description: >- - Favor unless over if for negative conditions - (or control flow or). - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#unless-for-negatives' - Enabled: false - -Style/NegatedWhile: - Description: 'Favor until over while for negative conditions.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#until-for-negatives' - Enabled: false - -Style/Next: - Description: 'Use `next` to skip iteration instead of a condition at the end.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-nested-conditionals' - Enabled: false - -Style/NilComparison: - Description: 'Prefer x.nil? to x == nil.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#predicate-methods' - Enabled: false - -Style/Not: - Description: 'Use ! instead of not.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#bang-not-not' - Enabled: false - -Style/NumericLiterals: - Description: >- - Add underscores to large numeric literals to improve their - readability. - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#underscores-in-numerics' - Enabled: false - -Style/OneLineConditional: - Description: >- - Favor the ternary operator(?:) over - if/then/else/end constructs. - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#ternary-operator' - Enabled: false - -Naming/BinaryOperatorParameterName: - Description: 'When defining binary operators, name the argument other.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#other-arg' - Enabled: false - -Metrics/ParameterLists: - Description: 'Avoid parameter lists longer than three or four parameters.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#too-many-params' - Enabled: false - -Style/PercentLiteralDelimiters: - Description: 'Use `%`-literal delimiters consistently' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#percent-literal-braces' - Enabled: false - -Style/PerlBackrefs: - Description: 'Avoid Perl-style regex back references.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-perl-regexp-last-matchers' - Enabled: false - -Naming/PredicateName: - Description: 'Check the names of predicate methods.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#bool-methods-qmark' - ForbiddenPrefixes: - - is_ - Exclude: - - spec/**/* - -Style/Proc: - Description: 'Use proc instead of Proc.new.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#proc' - Enabled: false - -Style/RaiseArgs: - Description: 'Checks the arguments passed to raise/fail.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#exception-class-messages' - Enabled: false - -Style/RegexpLiteral: - Description: 'Use / or %r around regular expressions.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#percent-r' - Enabled: false - -Style/SelfAssignment: - Description: >- - Checks for places where self-assignment shorthand should have - been used. - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#self-assignment' - Enabled: false - -Style/SingleLineBlockParams: - Description: 'Enforces the names of some block params.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#reduce-blocks' - Enabled: false - -Style/SingleLineMethods: - Description: 'Avoid single-line methods.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-single-line-methods' - Enabled: false - -Style/SignalException: - Description: 'Checks for proper usage of fail and raise.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#fail-method' - Enabled: false - -Style/SpecialGlobalVars: - Description: 'Avoid Perl-style global variables.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-cryptic-perlisms' - Enabled: false - -Style/StringLiterals: - Description: 'Checks if uses of quotes match the configured preference.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#consistent-string-literals' - EnforcedStyle: double_quotes - Enabled: true - -Style/TrailingCommaInArguments: - Description: 'Checks for trailing comma in argument lists.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-trailing-array-commas' - EnforcedStyleForMultiline: comma - SupportedStylesForMultiline: - - comma - - consistent_comma - - no_comma - Enabled: true - -Style/TrailingCommaInArrayLiteral: - Description: 'Checks for trailing comma in array literals.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-trailing-array-commas' - EnforcedStyleForMultiline: comma - SupportedStylesForMultiline: - - comma - - consistent_comma - - no_comma - Enabled: true - -Style/TrailingCommaInHashLiteral: - Description: 'Checks for trailing comma in hash literals.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-trailing-array-commas' - EnforcedStyleForMultiline: comma - SupportedStylesForMultiline: - - comma - - consistent_comma - - no_comma - Enabled: true - -Style/TrivialAccessors: - Description: 'Prefer attr_* methods to trivial readers/writers.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#attr_family' - Enabled: false - -Style/VariableInterpolation: - Description: >- - Don't interpolate global, instance and class variables - directly in strings. - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#curlies-interpolate' - Enabled: false - -Style/WhenThen: - Description: 'Use when x then ... for one-line cases.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#one-line-cases' - Enabled: false - -Style/WhileUntilModifier: - Description: >- - Favor modifier while/until usage when you have a - single-line body. - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#while-as-a-modifier' - Enabled: false - -Style/WordArray: - Description: 'Use %w or %W for arrays of words.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#percent-w' - Enabled: false - -# Layout - -Layout/ParameterAlignment: - Description: 'Here we check if the parameters on a multi-line method call or definition are aligned.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-double-indent' - Enabled: false - -Layout/ConditionPosition: - Description: >- - Checks for condition placed in a confusing position relative to - the keyword. - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#same-line-condition' - Enabled: false - -Layout/DotPosition: - Description: 'Checks the position of the dot in multi-line method calls.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#consistent-multi-line-chains' - EnforcedStyle: trailing - -Layout/ExtraSpacing: - Description: 'Do not use unnecessary spacing.' - Enabled: true - -Layout/MultilineOperationIndentation: - Description: >- - Checks indentation of binary operations that span more than - one line. - Enabled: true - EnforcedStyle: indented - -Layout/MultilineMethodCallIndentation: - Description: >- - Checks indentation of method calls with the dot operator - that span more than one line. - Enabled: true - EnforcedStyle: indented - -Layout/InitialIndentation: - Description: >- - Checks the indentation of the first non-blank non-comment line in a file. - Enabled: false - -# Lint - -Lint/AmbiguousOperator: - Description: >- - Checks for ambiguous operators in the first argument of a - method invocation without parentheses. - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#parens-as-args' - Enabled: false - -Lint/AmbiguousRegexpLiteral: - Description: >- - Checks for ambiguous regexp literals in the first argument of - a method invocation without parenthesis. - Enabled: false - -Lint/AssignmentInCondition: - Description: "Don't use assignment in conditions." - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#safe-assignment-in-condition' - Enabled: false - -Lint/CircularArgumentReference: - Description: "Don't refer to the keyword argument in the default value." - Enabled: false - -Lint/DeprecatedClassMethods: - Description: 'Check for deprecated class method calls.' - Enabled: false - -Lint/DuplicateHashKey: - Description: 'Check for duplicate keys in hash literals.' - Enabled: false - -Lint/EachWithObjectArgument: - Description: 'Check for immutable argument given to each_with_object.' - Enabled: false - -Lint/ElseLayout: - Description: 'Check for odd code arrangement in an else block.' - Enabled: false - -Lint/FormatParameterMismatch: - Description: 'The number of parameters to format/sprint must match the fields.' - Enabled: false - -Lint/SuppressedException: - Description: "Don't suppress exception." - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#dont-hide-exceptions' - Enabled: false - -Lint/LiteralAsCondition: - Description: 'Checks of literals used in conditions.' - Enabled: false - -Lint/LiteralInInterpolation: - Description: 'Checks for literals used in interpolation.' - Enabled: false - -Lint/Loop: - Description: >- - Use Kernel#loop with break rather than begin/end/until or - begin/end/while for post-loop tests. - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#loop-with-break' - Enabled: false - -Lint/NestedMethodDefinition: - Description: 'Do not use nested method definitions.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-nested-methods' - Enabled: false - -Lint/NonLocalExitFromIterator: - Description: 'Do not use return in iterator to cause non-local exit.' - Enabled: false - -Lint/ParenthesesAsGroupedExpression: - Description: >- - Checks for method calls with a space before the opening - parenthesis. - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#parens-no-spaces' - Enabled: false - -Lint/RequireParentheses: - Description: >- - Use parentheses in the method call to avoid confusion - about precedence. - Enabled: false - -Lint/UnderscorePrefixedVariableName: - Description: 'Do not use prefix `_` for a variable that is used.' - Enabled: false - -Lint/RedundantCopDisableDirective: - Description: >- - Checks for rubocop:disable comments that can be removed. - Note: this cop is not disabled when disabling all cops. - It must be explicitly disabled. - Enabled: false - -Lint/Void: - Description: 'Possible use of operator/literal/variable in void context.' - Enabled: false - -# Performance - -Performance/CaseWhenSplat: - Description: >- - Place `when` conditions that use splat at the end - of the list of `when` branches. - Enabled: false - -Performance/Count: - Description: >- - Use `count` instead of `select...size`, `reject...size`, - `select...count`, `reject...count`, `select...length`, - and `reject...length`. - Enabled: false - -Performance/Detect: - Description: >- - Use `detect` instead of `select.first`, `find_all.first`, - `select.last`, and `find_all.last`. - Reference: 'https://github.com/JuanitoFatas/fast-ruby#enumerabledetect-vs-enumerableselectfirst-code' - Enabled: false - -Performance/FlatMap: - Description: >- - Use `Enumerable#flat_map` - instead of `Enumerable#map...Array#flatten(1)` - or `Enumberable#collect..Array#flatten(1)` - Reference: 'https://github.com/JuanitoFatas/fast-ruby#enumerablemaparrayflatten-vs-enumerableflat_map-code' - Enabled: false - -Performance/ReverseEach: - Description: 'Use `reverse_each` instead of `reverse.each`.' - Reference: 'https://github.com/JuanitoFatas/fast-ruby#enumerablereverseeach-vs-enumerablereverse_each-code' - Enabled: false - -Performance/Sample: - Description: >- - Use `sample` instead of `shuffle.first`, - `shuffle.last`, and `shuffle[Fixnum]`. - Reference: 'https://github.com/JuanitoFatas/fast-ruby#arrayshufflefirst-vs-arraysample-code' - Enabled: false - -Performance/Size: - Description: >- - Use `size` instead of `count` for counting - the number of elements in `Array` and `Hash`. - Reference: 'https://github.com/JuanitoFatas/fast-ruby#arraycount-vs-arraysize-code' - Enabled: false - -Performance/StringReplacement: - Description: >- - Use `tr` instead of `gsub` when you are replacing the same - number of characters. Use `delete` instead of `gsub` when - you are deleting characters. - Reference: 'https://github.com/JuanitoFatas/fast-ruby#stringgsub-vs-stringtr-code' - Enabled: false - -# Rails - -Rails/ActionFilter: - Description: 'Enforces consistent use of action filter methods.' - Enabled: false - -Rails/Date: - Description: >- - Checks the correct usage of date aware methods, - such as Date.today, Date.current etc. - Enabled: false - -Rails/FindBy: - Description: 'Prefer find_by over where.first.' - Enabled: false - -Rails/FindEach: - Description: 'Prefer all.find_each over all.find.' - Enabled: false - -Rails/HasAndBelongsToMany: - Description: 'Prefer has_many :through to has_and_belongs_to_many.' - Enabled: false - -Rails/Output: - Description: 'Checks for calls to puts, print, etc.' - Enabled: false - -Rails/ReadWriteAttribute: - Description: >- - Checks for read_attribute(:attr) and - write_attribute(:attr, val). - Enabled: false - -Rails/ScopeArgs: - Description: 'Checks the arguments of ActiveRecord scopes.' - Enabled: false - -Rails/TimeZone: - Description: 'Checks the correct usage of time zone aware methods.' - StyleGuide: 'https://github.com/bbatsov/rails-style-guide#time' - Reference: 'http://danilenko.org/2012/7/6/rails_timezones' - Enabled: false - -Rails/Validation: - Description: 'Use validates :attribute, hash of validations.' - Enabled: false diff --git a/app/models/statistic_info.rb b/app/models/statistic_info.rb index 2b64e14ad..fb6ea5054 100644 --- a/app/models/statistic_info.rb +++ b/app/models/statistic_info.rb @@ -28,7 +28,7 @@ def epoch_info { epoch_number: tip_block.epoch.to_s, epoch_length: tip_block.length.to_s, - index: (tip_block_number - tip_block.start_number).to_s + index: (tip_block_number - tip_block.start_number).to_s, } end @@ -49,7 +49,8 @@ def current_epoch_difficulty define_logic :transactions_count_per_minute do interval = 100 start_block_number = [tip_block_number.to_i - interval + 1, 0].max - timestamps = Block.where(number: [start_block_number, tip_block_number]).recent.pluck(:timestamp) + timestamps = Block.where(number: [start_block_number, + tip_block_number]).recent.pluck(:timestamp) next if timestamps.empty? transactions_count = Block.where(number: start_block_number..tip_block_number).sum(:ckb_transactions_count) @@ -60,7 +61,8 @@ def current_epoch_difficulty define_logic :average_block_time do interval = (Settings.average_block_time_interval || 100) start_block_number = [tip_block_number.to_i - interval + 1, 0].max - timestamps = Block.where(number: [start_block_number, tip_block_number]).recent.pluck(:timestamp) + timestamps = Block.where(number: [start_block_number, + tip_block_number]).recent.pluck(:timestamp) next if timestamps.empty? total_block_time(timestamps) / blocks_count(interval) @@ -90,14 +92,17 @@ def self.hash_rate(block_number) define_logic :address_balance_ranking do addresses = Address.visible.where("balance > 0").order(balance: :desc).limit(50) addresses.each.with_index(1).map do |address, index| - { address: address.address_hash, balance: address.balance.to_s, ranking: index.to_s } + { address: address.address_hash, balance: address.balance.to_s, + ranking: index.to_s } end end define_logic :blockchain_info do message_need_to_be_filtered_out = "CKB v0.105.* have bugs. Please upgrade to the latest version." result = CkbSync::Api.instance.get_blockchain_info - result.alerts.delete_if { |alert| alert.message == message_need_to_be_filtered_out } + result.alerts.delete_if do |alert| + alert.message == message_need_to_be_filtered_out + end JSON.generate(result.as_json) end @@ -108,10 +113,10 @@ def self.hash_rate(block_number) pluck(:id, :created_at, :transaction_fee, :bytes, :confirmation_time) txs.map do |id, created_at, transaction_fee, bytes, confirmation_time| { - id: id, + id:, timestamp: created_at.to_i, fee_rate: (transaction_fee.to_f / bytes), - confirmation_time: confirmation_time + confirmation_time:, } end end @@ -123,7 +128,7 @@ def self.hash_rate(block_number) order("id desc").limit(100) # This is a patch for those pending tx which has no `bytes` - fee_rates = fee_rates.map { |tx| + fee_rates = fee_rates.map do |tx| tx_bytes = 0 if tx.bytes.blank? || tx.bytes == 0 Rails.logger.info "== checking tx bytes: #{tx.tx_hash}, #{tx.id}" @@ -137,12 +142,12 @@ def self.hash_rate(block_number) end tx - }.select { |e| e.bytes > 0 } + end.select { |e| e.bytes > 0 } fee_rates.map do |tx| { id: tx.id, - fee_rate: (tx.transaction_fee.to_f / tx.bytes) + fee_rate: (tx.transaction_fee.to_f / tx.bytes), } end end @@ -210,4 +215,5 @@ def tip_block # updated_at :datetime not null # pending_transaction_fee_rates :jsonb # transaction_fee_rates :jsonb +# ckb_hodl_waves :jsonb # diff --git a/app/serializers/statistic_serializer.rb b/app/serializers/statistic_serializer.rb index 409723813..c3c9c7f47 100644 --- a/app/serializers/statistic_serializer.rb +++ b/app/serializers/statistic_serializer.rb @@ -38,4 +38,8 @@ class StatisticSerializer attribute :maintenance_info, if: Proc.new { |_record, params| params && params[:info_name] == "maintenance_info" } + + attribute :ckb_hodl_waves, if: Proc.new { |_record, params| + params && params[:info_name] == "ckb_hodl_waves" + } end diff --git a/app/workers/charts/ckb_hodl_waves_statistic.rb b/app/workers/charts/ckb_hodl_waves_statistic.rb new file mode 100644 index 000000000..eafda1c3a --- /dev/null +++ b/app/workers/charts/ckb_hodl_waves_statistic.rb @@ -0,0 +1,49 @@ +module Charts + class CkbbHodlWavesStatistic + include Sidekiq::Worker + sidekiq_options queue: "critical" + + def perform + over_three_years = CellOutput.live.generated_before(3.years.ago.to_i * 1000).sum(:capacity) + one_year_to_three_years = CellOutput.live.generated_between( + 3.years.ago.to_i * 1000, 1.year.ago.to_i * 1000 + ).sum(:capacity) + six_months_to_one_year = CellOutput.live.generated_between( + 1.year.ago.to_i * 1000, 6.months.ago.to_i * 1000 + ).sum(:capacity) + three_months_to_six_months = CellOutput.live.generated_between( + 6.months.ago.to_i * 1000, 3.months.ago.to_i * 1000 + ).sum(:capacity) + one_month_to_three_months = CellOutput.live.generated_between( + 3.months.ago.to_i * 1000, 1.month.ago.to_i * 1000 + ).sum(:capacity) + one_week_to_one_month = CellOutput.live.generated_between( + 1.month.ago.to_i * 1000, 1.week.ago.to_i * 1000 + ).sum(:capacity) + day_to_one_week = CellOutput.live.generated_between( + 1.week.ago.to_i * 1000, 1.day.ago.to_i * 1000 + ).sum(:capacity) + latest_day = CellOutput.live.generated_between( + 1.day.ago.beginning_of_day.to_i * 1000, 1.day.ago.end_of_day.to_i * 1000 + ).sum(:capacity) + + info = { + total_supply: MarketData.new.indicators_json["total_supply"], + updated_at: Time.current.to_i, + } + + ckb = { + over_three_years:, + one_year_to_three_years:, + six_months_to_one_year:, + three_months_to_six_months:, + one_month_to_three_months:, + one_week_to_one_month:, + day_to_one_week:, + latest_day:, + }.transform_values { |value| (value / 10**8).truncate(8) } + + StatisticInfo.first.update(ckb_hodl_waves: ckb.merge!(info)) + end + end +end diff --git a/db/migrate/20231218082938_add_ckb_hodl_waves_to_statistic_info.rb b/db/migrate/20231218082938_add_ckb_hodl_waves_to_statistic_info.rb new file mode 100644 index 000000000..fe7ccb089 --- /dev/null +++ b/db/migrate/20231218082938_add_ckb_hodl_waves_to_statistic_info.rb @@ -0,0 +1,5 @@ +class AddCkbHodlWavesToStatisticInfo < ActiveRecord::Migration[7.0] + def change + add_column :statistic_infos, :ckb_hodl_waves, :jsonb + end +end diff --git a/db/structure.sql b/db/structure.sql index dcfe4f495..a7fcda3ce 100644 --- a/db/structure.sql +++ b/db/structure.sql @@ -1863,7 +1863,8 @@ CREATE TABLE public.statistic_infos ( created_at timestamp(6) without time zone NOT NULL, updated_at timestamp(6) without time zone NOT NULL, pending_transaction_fee_rates jsonb, - transaction_fee_rates jsonb + transaction_fee_rates jsonb, + ckb_hodl_waves jsonb ); @@ -4750,6 +4751,7 @@ INSERT INTO "schema_migrations" (version) VALUES ('20230913091025'), ('20230914120928'), ('20230918033957'), -('20231017074221'); +('20231017074221'), +('20231218082938'); diff --git a/lib/scheduler.rb b/lib/scheduler.rb index f1147f86f..3819d74d0 100644 --- a/lib/scheduler.rb +++ b/lib/scheduler.rb @@ -39,6 +39,10 @@ def call_worker(clz) call_worker Charts::DailyStatistic end +s.cron "10 8 * * *" do + call_worker Charts::CkbHodlWavesStatistic +end + s.every "10m", overlap: false do call_worker Charts::BlockStatistic end @@ -95,7 +99,8 @@ def call_worker(clz) s.every "4h", overlap: false do puts "reset address_balance_ranking, miner_ranking, last_n_days_transaction_fee_rates" - StatisticInfo.default.reset! :address_balance_ranking, :miner_ranking, :last_n_days_transaction_fee_rates + StatisticInfo.default.reset! :address_balance_ranking, :miner_ranking, + :last_n_days_transaction_fee_rates end s.every "1h", overlap: false do @@ -112,7 +117,6 @@ def call_worker(clz) call_worker Charts::ForkedEventProcessor end -# run at every mondy 06:00 s.cron "0 6 * * 1" do call_worker CleanAddressBlockSnapshotWorker end diff --git a/test/controllers/api/v1/statistics_controller_test.rb b/test/controllers/api/v1/statistics_controller_test.rb index d5da73c49..ef58105ee 100644 --- a/test/controllers/api/v1/statistics_controller_test.rb +++ b/test/controllers/api/v1/statistics_controller_test.rb @@ -6,15 +6,15 @@ class StatisticsControllerTest < ActionDispatch::IntegrationTest setup do CkbSync::Api.any_instance.stubs(:get_tip_block_number).returns(100) CkbSync::Api.any_instance.stubs(:get_blockchain_info).returns( - OpenStruct.new(alerts: OpenStruct.new(message: "test")) + OpenStruct.new(alerts: OpenStruct.new(message: "test")), ) CkbSync::Api.any_instance.stubs(:get_current_epoch).returns( CKB::Types::Epoch.new( compact_target: "0x1000", length: "0x07d0", number: "0x0", - start_number: "0x0" - ) + start_number: "0x0", + ), ) # StatisticInfo.any_instance.stubs(:id).returns(1) end @@ -43,7 +43,8 @@ class StatisticsControllerTest < ActionDispatch::IntegrationTest test "should respond with error object when Content-Type is wrong" do error_object = Api::V1::Exceptions::InvalidContentTypeError.new - response_json = RequestErrorSerializer.new([error_object], message: error_object.title).serialized_json + response_json = RequestErrorSerializer.new([error_object], + message: error_object.title).serialized_json get api_v1_statistics_url, headers: { "Content-Type": "text/plain" } @@ -51,16 +52,21 @@ class StatisticsControllerTest < ActionDispatch::IntegrationTest end test "should respond with 406 Not Acceptable when Accept is wrong" do - get api_v1_statistics_url, headers: { "Content-Type": "application/vnd.api+json", "Accept": "application/json" } + get api_v1_statistics_url, + headers: { "Content-Type": "application/vnd.api+json", + "Accept": "application/json" } assert_equal 406, response.status end test "should respond with error object when Accept is wrong" do error_object = Api::V1::Exceptions::InvalidAcceptError.new - response_json = RequestErrorSerializer.new([error_object], message: error_object.title).serialized_json + response_json = RequestErrorSerializer.new([error_object], + message: error_object.title).serialized_json - get api_v1_statistics_url, headers: { "Content-Type": "application/vnd.api+json", "Accept": "application/json" } + get api_v1_statistics_url, + headers: { "Content-Type": "application/vnd.api+json", + "Accept": "application/json" } assert_equal response_json, response.body end @@ -80,7 +86,8 @@ class StatisticsControllerTest < ActionDispatch::IntegrationTest statistic_info.reset_all! valid_get api_v1_statistics_url - assert_equal IndexStatisticSerializer.new(statistic_info).serialized_json, response.body + assert_equal IndexStatisticSerializer.new(statistic_info).serialized_json, + response.body end test "should get success code when call show" do @@ -99,8 +106,8 @@ class StatisticsControllerTest < ActionDispatch::IntegrationTest compact_target: "0x1000", length: "0x07d0", number: "0x0", - start_number: "0x0" - ) + start_number: "0x0", + ), ) generate_miner_ranking_related_data StatisticInfo.default.reset_all! @@ -116,8 +123,8 @@ class StatisticsControllerTest < ActionDispatch::IntegrationTest compact_target: "0x1000", length: "0x07d0", number: "0x0", - start_number: "0x0" - ) + start_number: "0x0", + ), ) generate_miner_ranking_related_data statistic_info = StatisticInfo.default @@ -134,8 +141,8 @@ class StatisticsControllerTest < ActionDispatch::IntegrationTest compact_target: "0x1000", length: "0x07d0", number: "0x0", - start_number: "0x0" - ) + start_number: "0x0", + ), ) generate_miner_ranking_related_data(1550578400000) StatisticInfo.default.reset! :miner_ranking @@ -164,7 +171,8 @@ class StatisticsControllerTest < ActionDispatch::IntegrationTest valid_get api_v1_statistic_url("tip_block_number") - assert_equal tip_block_number, json.dig("data", "attributes", "tip_block_number") + assert_equal tip_block_number, + json.dig("data", "attributes", "tip_block_number") end test "should return average block time when param is average_block_time" do @@ -174,7 +182,8 @@ class StatisticsControllerTest < ActionDispatch::IntegrationTest valid_get api_v1_statistic_url("average_block_time") - assert_equal average_block_time, json.dig("data", "attributes", "average_block_time") + assert_equal average_block_time, + json.dig("data", "attributes", "average_block_time") end test "should return current epoch difficulty when param is current_epoch_difficulty" do @@ -183,7 +192,8 @@ class StatisticsControllerTest < ActionDispatch::IntegrationTest valid_get api_v1_statistic_url("current_epoch_difficulty") - assert_equal current_epoch_difficulty, json.dig("data", "attributes", "current_epoch_difficulty") + assert_equal current_epoch_difficulty, + json.dig("data", "attributes", "current_epoch_difficulty") end test "should return current hash rate when param is hash_rate" do @@ -202,7 +212,7 @@ class StatisticsControllerTest < ActionDispatch::IntegrationTest difficulty: "0x100", median_time: "0x16bd6605e65", chain: "ckb_testnet", - alerts: [] + alerts: [], ) CkbSync::Api.any_instance.stubs(:get_blockchain_info).returns(blockchain_info) statistic_info = StatisticInfo.default @@ -211,7 +221,8 @@ class StatisticsControllerTest < ActionDispatch::IntegrationTest assert_equal StatisticSerializer.new(statistic_info, { params: { info_name: "blockchain_info" } }).serialized_json, response.body - assert_equal blockchain_info.as_json, json.dig("data", "attributes", "blockchain_info") + assert_equal blockchain_info.as_json, + json.dig("data", "attributes", "blockchain_info") end test "should return top 50 addresses balance list when param is address balance ranking" do @@ -222,19 +233,40 @@ class StatisticsControllerTest < ActionDispatch::IntegrationTest statistic_info.reset! :address_balance_ranking valid_get api_v1_statistic_url("address_balance_ranking") assert_equal %w(ranking address balance).sort, - json.dig("data", "attributes", "address_balance_ranking").map(&:keys).uniq.flatten.sort + json.dig("data", "attributes", + "address_balance_ranking").map(&:keys).uniq.flatten.sort assert_equal StatisticSerializer.new(statistic_info, { params: { info_name: "address_balance_ranking" } }).serialized_json, response.body end test "should respond with error object when statistic info name is invalid" do error_object = Api::V1::Exceptions::StatisticInfoNameInvalidError.new - response_json = RequestErrorSerializer.new([error_object], message: error_object.title).serialized_json + response_json = RequestErrorSerializer.new([error_object], + message: error_object.title).serialized_json valid_get api_v1_statistic_url("hash_rates") assert_equal response_json, response.body end + + test "should return current ckb_hodl_waves when param is ckb_hodl_waves" do + ckb_hodl_waves = { "over_three_years" => 19531171649.691193, + "one_year_to_three_years" => 23338346194.19826, + "six_months_to_one_year" => 19609620799.532352, + "three_months_to_six_months" => 2236264635.3570275, + "one_month_to_three_months" => 814754775.4523662, + "one_week_to_one_month" => 456541010.49045384, + "day_to_one_week" => 104631888.5063308, + "latest_day" => 22211617.27774267, + "total_supply" => 40845092357.49983, + "updated_at" => 1702895323 } + create(:statistic_info, ckb_hodl_waves:) + + valid_get api_v1_statistic_url("ckb_hodl_waves") + + assert_equal ckb_hodl_waves, + json.dig("data", "attributes", "ckb_hodl_waves") + end end end end diff --git a/test/factories/statistic_infos.rb b/test/factories/statistic_infos.rb index 1b4762578..ce89cc078 100644 --- a/test/factories/statistic_infos.rb +++ b/test/factories/statistic_infos.rb @@ -8,5 +8,6 @@ miner_ranking { "" } blockchain_info { "MyString" } last_n_days_transaction_fee_rates { "" } + ckb_hodl_waves { "" } end end From 3007936f869858f7134224cc3ba8c4ca9db8f75c Mon Sep 17 00:00:00 2001 From: Miles Zhang Date: Tue, 19 Dec 2023 11:01:34 +0800 Subject: [PATCH 5/8] fix: typo (#1535) Signed-off-by: Miles Zhang --- app/workers/charts/ckb_hodl_waves_statistic.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/workers/charts/ckb_hodl_waves_statistic.rb b/app/workers/charts/ckb_hodl_waves_statistic.rb index eafda1c3a..19b8d324f 100644 --- a/app/workers/charts/ckb_hodl_waves_statistic.rb +++ b/app/workers/charts/ckb_hodl_waves_statistic.rb @@ -1,5 +1,5 @@ module Charts - class CkbbHodlWavesStatistic + class CkbHodlWavesStatistic include Sidekiq::Worker sidekiq_options queue: "critical" From 3b88a4457fa86e3a9120d0fbb0a858c5699137b1 Mon Sep 17 00:00:00 2001 From: Rabbit Date: Tue, 19 Dec 2023 13:49:42 +0800 Subject: [PATCH 6/8] fix: optimize transaction display cells cache key (#1536) --- app/serializers/ckb_transactions_serializer.rb | 6 ++++-- test/controllers/api/v1/suggest_queries_controller_test.rb | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/app/serializers/ckb_transactions_serializer.rb b/app/serializers/ckb_transactions_serializer.rb index f100d2964..1fe281648 100644 --- a/app/serializers/ckb_transactions_serializer.rb +++ b/app/serializers/ckb_transactions_serializer.rb @@ -24,7 +24,8 @@ class CkbTransactionsSerializer end attribute :display_inputs do |object, params| - Rails.cache.fetch("display_inputs_previews_#{params[:previews].present?}_#{object.id}", expires_in: 1.day) do + cache_key = "display_inputs_previews_#{params[:previews].present?}_#{object.id}_#{object.inputs.cache_key}" + Rails.cache.fetch(cache_key, expires_in: 1.day) do if params && params[:previews] object.display_inputs(previews: true) else @@ -34,7 +35,8 @@ class CkbTransactionsSerializer end attribute :display_outputs do |object, params| - Rails.cache.fetch("display_outputs_previews_#{params[:previews].present?}_#{object.id}", expires_in: 1.day) do + cache_key = "display_outputs_previews_#{params[:previews].present?}_#{object.id}_#{object.outputs.cache_key}" + Rails.cache.fetch(cache_key, expires_in: 1.day) do if params && params[:previews] object.display_outputs(previews: true) else diff --git a/test/controllers/api/v1/suggest_queries_controller_test.rb b/test/controllers/api/v1/suggest_queries_controller_test.rb index 90c644bf2..15b04686b 100644 --- a/test/controllers/api/v1/suggest_queries_controller_test.rb +++ b/test/controllers/api/v1/suggest_queries_controller_test.rb @@ -190,7 +190,7 @@ class SuggestQueriesControllerTest < ActionDispatch::IntegrationTest type_script = create( :type_script, code_hash: Settings.type_id_code_hash, - args: "0x2ab17f74009a9948ae2d3623dac853cc3ff1ef8270304ea5d9980b1f2b6810d5", + args: "0x8536c9d5d908bd89fc70099e4284870708b6632356aad98734fcf43f6f71c304", script_hash: "0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8" ) response_json = TypeScriptSerializer.new(type_script).serialized_json From 40e4c19866d93ad6fff1967a0cc5f54b289f6107 Mon Sep 17 00:00:00 2001 From: Rabbit Date: Tue, 19 Dec 2023 19:32:34 +0800 Subject: [PATCH 7/8] chore: enhance 'created_at' return in ckb transactions serializer (#1537) --- .../api/v1/address_dao_transactions_controller.rb | 2 +- app/controllers/api/v1/address_transactions_controller.rb | 2 +- .../api/v1/address_udt_transactions_controller.rb | 4 +++- app/controllers/api/v1/block_transactions_controller.rb | 2 +- app/controllers/api/v1/ckb_transactions_controller.rb | 6 +++--- .../api/v1/contract_transactions_controller.rb | 2 +- app/controllers/api/v1/udt_transactions_controller.rb | 2 +- app/serializers/ckb_transactions_serializer.rb | 8 ++++++++ .../api/v1/address_dao_transactions_controller_test.rb | 2 +- .../v1/address_pending_transactions_controller_test.rb | 2 ++ .../api/v1/address_transactions_controller_test.rb | 2 ++ .../api/v1/address_udt_transactions_controller_test.rb | 2 +- .../api/v1/block_transactions_controller_test.rb | 2 +- .../api/v1/contract_transactions_controller_test.rb | 2 +- .../api/v1/udt_transactions_controller_test.rb | 2 +- 15 files changed, 28 insertions(+), 14 deletions(-) diff --git a/app/controllers/api/v1/address_dao_transactions_controller.rb b/app/controllers/api/v1/address_dao_transactions_controller.rb index 77a19922f..4231efae1 100644 --- a/app/controllers/api/v1/address_dao_transactions_controller.rb +++ b/app/controllers/api/v1/address_dao_transactions_controller.rb @@ -8,7 +8,7 @@ def show address = Address.find_address!(params[:id]) raise Api::V1::Exceptions::AddressNotFoundError if address.is_a?(NullAddress) - ckb_dao_transactions = address.ckb_dao_transactions.select(:id, :tx_hash, :block_id, :block_number, :block_timestamp, :is_cellbase, :updated_at).recent.page(@page).per(@page_size).fast_page + ckb_dao_transactions = address.ckb_dao_transactions.select(:id, :tx_hash, :block_id, :block_number, :block_timestamp, :is_cellbase, :updated_at, :created_at).recent.page(@page).per(@page_size).fast_page json = Rails.cache.realize(ckb_dao_transactions.cache_key, version: ckb_dao_transactions.cache_version) do records_counter = RecordCounters::AddressDaoTransactions.new(address) diff --git a/app/controllers/api/v1/address_transactions_controller.rb b/app/controllers/api/v1/address_transactions_controller.rb index debafcb4e..86d9c2a7d 100644 --- a/app/controllers/api/v1/address_transactions_controller.rb +++ b/app/controllers/api/v1/address_transactions_controller.rb @@ -21,7 +21,7 @@ def show ckb_transaction_ids = tx_ids.map(&:ckb_transaction_id) ckb_transactions = CkbTransaction.where(id: ckb_transaction_ids). select(:id, :tx_hash, :block_id, :block_number, :block_timestamp, - :is_cellbase, :updated_at, :capacity_involved). + :is_cellbase, :updated_at, :capacity_involved, :created_at). order(order_by => asc_or_desc) options = FastJsonapi::PaginationMetaGenerator.new( diff --git a/app/controllers/api/v1/address_udt_transactions_controller.rb b/app/controllers/api/v1/address_udt_transactions_controller.rb index 1e52bc3b7..5d95c3503 100644 --- a/app/controllers/api/v1/address_udt_transactions_controller.rb +++ b/app/controllers/api/v1/address_udt_transactions_controller.rb @@ -12,7 +12,9 @@ def show udt = Udt.find_by(type_hash: params[:type_hash], published: true) raise Api::V1::Exceptions::UdtNotFoundError if udt.blank? - ckb_dao_transactions = address.ckb_udt_transactions(udt.id).select(:id, :tx_hash, :block_id, :block_number, :block_timestamp, :is_cellbase, :updated_at).recent.page(@page).per(@page_size).fast_page + ckb_dao_transactions = address.ckb_udt_transactions(udt.id). + select(:id, :tx_hash, :block_id, :block_number, :block_timestamp, :is_cellbase, :updated_at, :created_at). + recent.page(@page).per(@page_size).fast_page json = Rails.cache.realize(ckb_dao_transactions.cache_key, version: ckb_dao_transactions.cache_version) do records_counter = RecordCounters::AddressUdtTransactions.new(address, udt.id) diff --git a/app/controllers/api/v1/block_transactions_controller.rb b/app/controllers/api/v1/block_transactions_controller.rb index 27272b167..7ee14019a 100644 --- a/app/controllers/api/v1/block_transactions_controller.rb +++ b/app/controllers/api/v1/block_transactions_controller.rb @@ -6,7 +6,7 @@ class BlockTransactionsController < ApplicationController def show block = Block.find_by!(block_hash: params[:id]) ckb_transactions = block.ckb_transactions. - select(:id, :tx_hash, :block_id, :block_number, :block_timestamp, :is_cellbase, :updated_at). + select(:id, :tx_hash, :block_id, :block_number, :block_timestamp, :is_cellbase, :updated_at, :created_at). order(is_cellbase: :desc, id: :asc) if params[:tx_hash].present? diff --git a/app/controllers/api/v1/ckb_transactions_controller.rb b/app/controllers/api/v1/ckb_transactions_controller.rb index 58d5d7e00..97a12fd36 100644 --- a/app/controllers/api/v1/ckb_transactions_controller.rb +++ b/app/controllers/api/v1/ckb_transactions_controller.rb @@ -8,7 +8,7 @@ class CkbTransactionsController < ApplicationController def index if from_home_page? ckb_transactions = CkbTransaction.tx_committed.recent.normal.select( - :id, :tx_hash, :block_number, :block_timestamp, :live_cell_changes, :capacity_involved, :updated_at + :id, :tx_hash, :block_number, :block_timestamp, :live_cell_changes, :capacity_involved, :updated_at, :created_at ).limit((Settings.homepage_transactions_records_count || 15).to_i) json = Rails.cache.realize(ckb_transactions.cache_key, @@ -18,7 +18,7 @@ def index render json: json else ckb_transactions = CkbTransaction.tx_committed.normal.select( - :id, :tx_hash, :block_number, :block_timestamp, :live_cell_changes, :capacity_involved, :updated_at + :id, :tx_hash, :block_number, :block_timestamp, :live_cell_changes, :capacity_involved, :updated_at, :created_at ) params[:sort] ||= "id.desc" @@ -84,7 +84,7 @@ def query CkbTransaction.recent.normal.page(@page).per(@page_size).fast_page end ckb_transactions = ckb_transactions.select(:id, :tx_hash, :block_id, - :block_number, :block_timestamp, :is_cellbase, :updated_at) + :block_number, :block_timestamp, :is_cellbase, :updated_at, :created_at) json = Rails.cache.realize(ckb_transactions.cache_key, version: ckb_transactions.cache_version, race_condition_ttl: 1.minute) do diff --git a/app/controllers/api/v1/contract_transactions_controller.rb b/app/controllers/api/v1/contract_transactions_controller.rb index 57389f5cf..de2f093ea 100644 --- a/app/controllers/api/v1/contract_transactions_controller.rb +++ b/app/controllers/api/v1/contract_transactions_controller.rb @@ -12,7 +12,7 @@ def show expires_in 10.seconds, public: true, must_revalidate: true, stale_while_revalidate: 5.seconds ckb_transactions = dao_contract.ckb_transactions.includes(:cell_inputs, :cell_outputs).tx_committed.select( - :id, :tx_hash, :block_id, :block_number, :block_timestamp, :is_cellbase, :updated_at + :id, :tx_hash, :block_id, :block_number, :block_timestamp, :is_cellbase, :updated_at, :created_at ).order("ckb_transactions.block_timestamp desc nulls last, ckb_transactions.id desc") if params[:tx_hash].present? diff --git a/app/controllers/api/v1/udt_transactions_controller.rb b/app/controllers/api/v1/udt_transactions_controller.rb index 0d9012dc2..c91208775 100644 --- a/app/controllers/api/v1/udt_transactions_controller.rb +++ b/app/controllers/api/v1/udt_transactions_controller.rb @@ -9,7 +9,7 @@ def show ckb_transactions = udt.ckb_transactions.tx_committed. select(:id, :tx_hash, :block_id, :block_number, - :block_timestamp, :is_cellbase, :updated_at). + :block_timestamp, :is_cellbase, :updated_at, :created_at). order("ckb_transactions.block_timestamp desc nulls last, ckb_transactions.id desc") if params[:tx_hash].present? diff --git a/app/serializers/ckb_transactions_serializer.rb b/app/serializers/ckb_transactions_serializer.rb index 1fe281648..092895152 100644 --- a/app/serializers/ckb_transactions_serializer.rb +++ b/app/serializers/ckb_transactions_serializer.rb @@ -50,4 +50,12 @@ class CkbTransactionsSerializer object.income(params[:address]) end end + + attribute :created_at do |object| + object.created_at.to_s + end + + attribute :create_timestamp do |object| + (object.created_at.to_f * 1000).to_s + end end diff --git a/test/controllers/api/v1/address_dao_transactions_controller_test.rb b/test/controllers/api/v1/address_dao_transactions_controller_test.rb index 90c533b9d..7e736a078 100644 --- a/test/controllers/api/v1/address_dao_transactions_controller_test.rb +++ b/test/controllers/api/v1/address_dao_transactions_controller_test.rb @@ -89,7 +89,7 @@ class AddressDaoTransactionsControllerTest < ActionDispatch::IntegrationTest response_tx_transaction = json["data"].first - assert_equal %w(block_number block_timestamp display_inputs display_inputs_count display_outputs display_outputs_count income is_cellbase transaction_hash).sort, response_tx_transaction["attributes"].keys.sort + assert_equal %w(block_number block_timestamp display_inputs display_inputs_count display_outputs display_outputs_count income is_cellbase transaction_hash created_at create_timestamp).sort, response_tx_transaction["attributes"].keys.sort end test "should return error object when no records found by id" do diff --git a/test/controllers/api/v1/address_pending_transactions_controller_test.rb b/test/controllers/api/v1/address_pending_transactions_controller_test.rb index d9958fa57..c8a767963 100644 --- a/test/controllers/api/v1/address_pending_transactions_controller_test.rb +++ b/test/controllers/api/v1/address_pending_transactions_controller_test.rb @@ -148,6 +148,8 @@ class AddressPendingTransactionsControllerTest < ActionDispatch::IntegrationTest income is_cellbase transaction_hash + created_at + create_timestamp ).sort, response_tx_transaction["attributes"].keys.sort end diff --git a/test/controllers/api/v1/address_transactions_controller_test.rb b/test/controllers/api/v1/address_transactions_controller_test.rb index 0dd218518..000cf5edf 100644 --- a/test/controllers/api/v1/address_transactions_controller_test.rb +++ b/test/controllers/api/v1/address_transactions_controller_test.rb @@ -150,6 +150,8 @@ class AddressTransactionsControllerTest < ActionDispatch::IntegrationTest income is_cellbase transaction_hash + created_at + create_timestamp ).sort, response_tx_transaction["attributes"].keys.sort end diff --git a/test/controllers/api/v1/address_udt_transactions_controller_test.rb b/test/controllers/api/v1/address_udt_transactions_controller_test.rb index b15b6ea70..96499c036 100644 --- a/test/controllers/api/v1/address_udt_transactions_controller_test.rb +++ b/test/controllers/api/v1/address_udt_transactions_controller_test.rb @@ -94,7 +94,7 @@ class AddressUdtTransactionsControllerTest < ActionDispatch::IntegrationTest response_tx_transaction = json["data"].first - assert_equal %w(block_number block_timestamp display_inputs display_inputs_count display_outputs display_outputs_count income is_cellbase transaction_hash).sort, response_tx_transaction["attributes"].keys.sort + assert_equal %w(block_number block_timestamp display_inputs display_inputs_count display_outputs display_outputs_count income is_cellbase transaction_hash created_at create_timestamp).sort, response_tx_transaction["attributes"].keys.sort end test "should return error object when no records found by id" do diff --git a/test/controllers/api/v1/block_transactions_controller_test.rb b/test/controllers/api/v1/block_transactions_controller_test.rb index 0a074f0fa..99763ec8d 100644 --- a/test/controllers/api/v1/block_transactions_controller_test.rb +++ b/test/controllers/api/v1/block_transactions_controller_test.rb @@ -102,7 +102,7 @@ class BlockTransactionsControllerTest < ActionDispatch::IntegrationTest assert_equal %w( block_number block_timestamp display_inputs display_inputs_count display_outputs display_outputs_count - income is_cellbase transaction_hash + income is_cellbase transaction_hash created_at create_timestamp ).sort, response_tx_transaction["attributes"].keys.sort end diff --git a/test/controllers/api/v1/contract_transactions_controller_test.rb b/test/controllers/api/v1/contract_transactions_controller_test.rb index f937b97ee..7a938c4be 100644 --- a/test/controllers/api/v1/contract_transactions_controller_test.rb +++ b/test/controllers/api/v1/contract_transactions_controller_test.rb @@ -59,7 +59,7 @@ class ContractTransactionsControllerTest < ActionDispatch::IntegrationTest response_tx_transaction = json["data"].first - assert_equal %w(block_number block_timestamp display_inputs display_inputs_count display_outputs display_outputs_count income is_cellbase transaction_hash).sort, response_tx_transaction["attributes"].keys.sort + assert_equal %w(block_number block_timestamp display_inputs display_inputs_count display_outputs display_outputs_count income is_cellbase transaction_hash created_at create_timestamp).sort, response_tx_transaction["attributes"].keys.sort end test "should return error object when no records found by give contract name" do diff --git a/test/controllers/api/v1/udt_transactions_controller_test.rb b/test/controllers/api/v1/udt_transactions_controller_test.rb index feeabb370..2c3fea165 100644 --- a/test/controllers/api/v1/udt_transactions_controller_test.rb +++ b/test/controllers/api/v1/udt_transactions_controller_test.rb @@ -90,7 +90,7 @@ class UdtTransactionsControllerTest < ActionDispatch::IntegrationTest response_tx_transaction = json["data"].first assert_equal %w( - block_number block_timestamp display_inputs display_inputs_count + block_number block_timestamp display_inputs display_inputs_count created_at create_timestamp display_outputs display_outputs_count income is_cellbase transaction_hash ).sort, response_tx_transaction["attributes"].keys.sort From 8864b57e82a7f6616f1f97ab9201bc0ca420702f Mon Sep 17 00:00:00 2001 From: Rabbit Date: Thu, 21 Dec 2023 12:55:30 +0800 Subject: [PATCH 8/8] fix: return integer for create_timestamp time extraction (#1538) * fix: return integer for create_timestamp time extraction * fix: pending transaction income --- app/models/ckb_transaction.rb | 6 +++++- app/serializers/ckb_transaction_serializer.rb | 6 ++++-- app/serializers/ckb_transactions_serializer.rb | 2 +- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/app/models/ckb_transaction.rb b/app/models/ckb_transaction.rb index a2f63c7eb..e8f6b6863 100644 --- a/app/models/ckb_transaction.rb +++ b/app/models/ckb_transaction.rb @@ -189,7 +189,11 @@ def cell_deps end def income(address) - outputs.where(address: address).sum(:capacity) - inputs.where(address: address).sum(:capacity) + if tx_pending? + cell_outputs.where(address: address).sum(:capacity) - input_cells.where(address: address).sum(:capacity) + else + outputs.where(address: address).sum(:capacity) - inputs.where(address: address).sum(:capacity) + end end def dao_transaction? diff --git a/app/serializers/ckb_transaction_serializer.rb b/app/serializers/ckb_transaction_serializer.rb index 7c8e742fb..b1c700eee 100644 --- a/app/serializers/ckb_transaction_serializer.rb +++ b/app/serializers/ckb_transaction_serializer.rb @@ -45,7 +45,8 @@ class CkbTransactionSerializer end attribute :display_inputs do |object, params| - Rails.cache.fetch("display_inputs_previews_#{params[:previews].present?}_#{object.id}", expires_in: 1.day) do + cache_key = "display_inputs_previews_#{params[:previews].present?}_#{object.id}_#{object.inputs.cache_key}" + Rails.cache.fetch(cache_key, expires_in: 1.day) do if params && params[:previews] object.display_inputs(previews: true) else @@ -55,7 +56,8 @@ class CkbTransactionSerializer end attribute :display_outputs do |object, params| - Rails.cache.fetch("display_outputs_previews_#{params[:previews].present?}_#{object.id}", expires_in: 1.day) do + cache_key = "display_outputs_previews_#{params[:previews].present?}_#{object.id}_#{object.outputs.cache_key}" + Rails.cache.fetch(cache_key, expires_in: 1.day) do if params && params[:previews] object.display_outputs(previews: true) else diff --git a/app/serializers/ckb_transactions_serializer.rb b/app/serializers/ckb_transactions_serializer.rb index 092895152..aba90613f 100644 --- a/app/serializers/ckb_transactions_serializer.rb +++ b/app/serializers/ckb_transactions_serializer.rb @@ -56,6 +56,6 @@ class CkbTransactionsSerializer end attribute :create_timestamp do |object| - (object.created_at.to_f * 1000).to_s + (object.created_at.to_f * 1000).to_i.to_s end end