The personal finance app for everyone (by everyone)
Ruby
feat(onchain): track Polkadot (DOT) wallets (#4071)
PierroMojito42562d93c7d0
diff --git a/app/models/onchain/chains.rb b/app/models/onchain/chains.rbindex 90e2d5a006..9bb6463fdf 100644--- a/app/models/onchain/chains.rb+++ b/app/models/onchain/chains.rb@@ -92,6 +92,8 @@ module OnchainSOLANA = "solana"+ POLKADOT = "polkadot"+BUILTIN = [Definition.new(key: BITCOIN,@@ -119,6 +121,13 @@ module Onchaintoken_kind: "spl",adapter_class_name: "Onchain::SolanaAdapter",adapter_options: {}+ ),+ Definition.new(+ key: POLKADOT,+ native: NativeAsset.new(symbol: "DOT", name: "Polkadot", decimals: 10),+ token_kind: nil,+ adapter_class_name: "Onchain::PolkadotAdapter",+ adapter_options: {})].freezediff --git a/app/models/onchain/polkadot_adapter.rb b/app/models/onchain/polkadot_adapter.rbnew file mode 100644index 0000000000..48272ee7b7--- /dev/null+++ b/app/models/onchain/polkadot_adapter.rb@@ -0,0 +1,51 @@+# frozen_string_literal: true++# Polkadot DOT on Asset Hub: free plus reserved, so staked DOT counts. No keyless+# source indexes transfers, so only the balance is read.+class Onchain::PolkadotAdapter+ include Onchain::ChainAdapter++ PLANCK_PER_DOT = 10_000_000_000.to_d++ # SS58 with the Polkadot network prefix (0), which always starts with "1".+ # Base58: no 0, O, I or l.+ ADDRESS_PATTERN = /\A1[1-9A-HJ-NP-Za-km-z]{46,47}\z/++ def initialize(credentials: {})+ @credentials = credentials+ end++ def valid_address?(address)+ ADDRESS_PATTERN.match?(address.to_s.strip)+ end++ def fetch_snapshot(address)+ raise Onchain::Chains::Error, "Invalid Polkadot address" unless valid_address?(address)++ wrap_provider_errors do+ info = provider.balance_info(address)++ Onchain::Snapshot.new(+ assets: [ definition.native_asset(quantity: (info["free"].to_d + info["reserved"].to_d) / PLANCK_PER_DOT) ],+ movements: []+ )+ rescue Provider::PolkadotSidecar::InvalidAddressError+ raise Onchain::Chains::Error, "Invalid Polkadot address"+ end+ end++ def provider_error_classes+ [ Provider::PolkadotSidecar::RateLimitError, Provider::PolkadotSidecar::Error ]+ end++ private+ attr_reader :credentials++ def definition+ Onchain::Chains.find!(Onchain::Chains::POLKADOT)+ end++ def provider+ @provider ||= Provider::PolkadotSidecar.new+ end+enddiff --git a/app/models/provider/polkadot_sidecar.rb b/app/models/provider/polkadot_sidecar.rbnew file mode 100644index 0000000000..200546a885--- /dev/null+++ b/app/models/provider/polkadot_sidecar.rb@@ -0,0 +1,64 @@+# frozen_string_literal: true++# Keyless Polkadot data source backed by Parity's public Substrate API Sidecar+# for Asset Hub, where DOT balances live since the 2025 migration. Self-hosters+# can point it at their own instance with POLKADOT_SIDECAR_URL.+class Provider::PolkadotSidecar+ include HTTParty+ include Provider::HttpTransport+ extend SslConfigurable++ class Error < StandardError; end+ class InvalidAddressError < Error; end+ class RateLimitError < Error; end+ class ApiError < Error; end++ DEFAULT_BASE_URL = "https://polkadot-asset-hub-public-sidecar.parity-chains.parity.io"+ MAX_RETRIES = 3+ RETRY_BASE_DELAY = 0.5++ default_options.merge!({ timeout: 30 }.merge(httparty_ssl_options))++ def self.base_url+ ENV["POLKADOT_SIDECAR_URL"].presence || DEFAULT_BASE_URL+ end++ # Free and reserved balances, in planck.+ def balance_info(address)+ attempts = 0++ begin+ attempts += 1+ translate_transport_errors do+ handle_response(self.class.get("#{self.class.base_url}/accounts/#{ERB::Util.url_encode(address)}/balance-info"))+ end+ rescue RateLimitError => e+ raise if attempts > MAX_RETRIES++ Rails.logger.warn("Provider::PolkadotSidecar - rate limited (attempt #{attempts}/#{MAX_RETRIES}): #{e.message}")+ sleep(RETRY_BASE_DELAY * (2**(attempts - 1)))+ retry+ end+ end++ private+ def planck?(value)+ value.is_a?(String) && value.match?(/\A\d+\z/)+ end++ def handle_response(response)+ case response.code+ when 200..299+ body = response.parsed_response+ raise ApiError, "Polkadot Sidecar returned an unexpected body" unless body.is_a?(Hash) && planck?(body["free"]) && planck?(body["reserved"])++ body+ when 400+ raise InvalidAddressError, "Polkadot Sidecar rejected the address"+ when 429+ raise RateLimitError, "Polkadot Sidecar rate limit exceeded"+ else+ raise ApiError, "Polkadot Sidecar API error: #{response.code}"+ end+ end+enddiff --git a/config/locales/models/onchain_wallet_item/ca.yml b/config/locales/models/onchain_wallet_item/ca.ymlindex efa56fe2ef..cdb9230e61 100644--- a/config/locales/models/onchain_wallet_item/ca.yml+++ b/config/locales/models/onchain_wallet_item/ca.yml@@ -8,6 +8,7 @@ ca:ethereum: Ethereumgnosis: Gnosisoptimism: Optimism+ polkadot: Polkadotpolygon: Polygonsolana: Solanainstitution_name: Carteres d'autocustòdiadiff --git a/config/locales/models/onchain_wallet_item/en.yml b/config/locales/models/onchain_wallet_item/en.ymlindex 6a1eac6299..2189909b35 100644--- a/config/locales/models/onchain_wallet_item/en.yml+++ b/config/locales/models/onchain_wallet_item/en.yml@@ -8,6 +8,7 @@ en:ethereum: Ethereumgnosis: Gnosisoptimism: Optimism+ polkadot: Polkadotpolygon: Polygonsolana: Solanainstitution_name: Self-custody walletsdiff --git a/config/locales/models/onchain_wallet_item/fr.yml b/config/locales/models/onchain_wallet_item/fr.ymlindex 97cf91cd02..6395288e60 100644--- a/config/locales/models/onchain_wallet_item/fr.yml+++ b/config/locales/models/onchain_wallet_item/fr.yml@@ -8,6 +8,7 @@ fr:ethereum: Ethereumgnosis: Gnosisoptimism: Optimism+ polkadot: Polkadotpolygon: Polygonsolana: Solanainstitution_name: Portefeuilles en autoconservationdiff --git a/config/locales/models/onchain_wallet_item/pl.yml b/config/locales/models/onchain_wallet_item/pl.ymlindex 847871e2e1..362ce44bf8 100644--- a/config/locales/models/onchain_wallet_item/pl.yml+++ b/config/locales/models/onchain_wallet_item/pl.yml@@ -8,6 +8,7 @@ pl:ethereum: Ethereumgnosis: Gnosisoptimism: Optimism+ polkadot: Polkadotpolygon: Polygonsolana: Solanainstitution_name: Portfele niekustodialnediff --git a/config/locales/models/onchain_wallet_item/pt-PT.yml b/config/locales/models/onchain_wallet_item/pt-PT.ymlindex f91cb6418d..7562bbb689 100644--- a/config/locales/models/onchain_wallet_item/pt-PT.yml+++ b/config/locales/models/onchain_wallet_item/pt-PT.yml@@ -8,6 +8,7 @@ pt-PT:ethereum: Ethereumgnosis: Gnosisoptimism: Optimism+ polkadot: Polkadotpolygon: Polygonsolana: Solanainstitution_name: Carteiras de autocustódiadiff --git a/config/locales/models/onchain_wallet_item/ru.yml b/config/locales/models/onchain_wallet_item/ru.ymlindex 6e736a2a12..c5d3ea27cb 100644--- a/config/locales/models/onchain_wallet_item/ru.yml+++ b/config/locales/models/onchain_wallet_item/ru.yml@@ -8,6 +8,7 @@ ru:ethereum: Ethereumgnosis: Gnosisoptimism: Optimism+ polkadot: Polkadotpolygon: Polygonsolana: Solanainstitution_name: Некастодиальные кошелькиdiff --git a/config/locales/models/onchain_wallet_item/tr.yml b/config/locales/models/onchain_wallet_item/tr.ymlindex feb75606f9..b896fae522 100644--- a/config/locales/models/onchain_wallet_item/tr.yml+++ b/config/locales/models/onchain_wallet_item/tr.yml@@ -8,6 +8,7 @@ tr:ethereum: Ethereumgnosis: Gnosisoptimism: Optimism+ polkadot: Polkadotpolygon: Polygonsolana: Solanainstitution_name: Gözetimsiz cüzdanlardiff --git a/config/locales/models/onchain_wallet_item/uk.yml b/config/locales/models/onchain_wallet_item/uk.ymlindex 2494ab2509..ad5f956587 100644--- a/config/locales/models/onchain_wallet_item/uk.yml+++ b/config/locales/models/onchain_wallet_item/uk.yml@@ -8,6 +8,7 @@ uk:ethereum: Ethereumgnosis: Gnosisoptimism: Optimism+ polkadot: Polkadotpolygon: Polygonsolana: Solanainstitution_name: Гаманці із самостійним зберіганнямdiff --git a/config/locales/views/settings/ca.yml b/config/locales/views/settings/ca.ymlindex 993297974d..80fc13e348 100644--- a/config/locales/views/settings/ca.yml+++ b/config/locales/views/settings/ca.yml@@ -564,7 +564,7 @@ ca:fio: Sincronitza un compte de Fio banka amb un token API de només lectura.wise: Sincronitza automàticament els teus saldos multidivisa i les transferències internacionals de Wise.coinspot: Sincronitza saldos, valors en AUD, transferències, dipòsits, retirades i historial d'ordres de CoinSpot amb una clau API de només lectura.- onchain_wallet: Fes el seguiment de carteres Bitcoin, EVM i Solana d'autocustòdia a partir de les seves adreces públiques.+ onchain_wallet: Fes el seguiment de carteres Bitcoin, EVM, Solana i Polkadot d'autocustòdia a partir de les seves adreces públiques.trading212: Sincronitza la teva cartera d'inversió de Trading 212 amb una clau API de només lectura.trade_republic: Sincronitza el teu compte d'inversió de Trade Republic mitjançant un inici de sessió web segur de només lectura.questrade: Sincronitza els teus comptes d'inversió de Questrade directament a través de l'API de Questrade.diff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.ymlindex 685adee275..eb674eaa6a 100644--- a/config/locales/views/settings/en.yml+++ b/config/locales/views/settings/en.yml@@ -469,7 +469,7 @@ en:binance: Sync your Binance spot balances using a read-only API key.kraken: Sync Kraken balances and spot trade fills using a read-only API key.coinspot: Sync CoinSpot balances, AUD values, transfers, deposits, withdrawals, and order history using a read-only API key.- onchain_wallet: Track self-custody Bitcoin, EVM and Solana wallets from their public addresses.+ onchain_wallet: Track self-custody Bitcoin, EVM, Solana and Polkadot wallets from their public addresses.snaptrade: Connect brokerage accounts via the SnapTrade aggregation network.trading212: Sync your Trading 212 investment portfolio using a read-only API key.trade_republic: Sync your Trade Republic investment account via secure read-only web login.diff --git a/config/locales/views/settings/fr.yml b/config/locales/views/settings/fr.ymlindex b5eca021dd..d04272fe8a 100644--- a/config/locales/views/settings/fr.yml+++ b/config/locales/views/settings/fr.yml@@ -552,7 +552,7 @@ fr:kraken: Synchronisez vos soldes Kraken et transactions spot à l'aide d'une clé API en lecture seule.lunchflow: Connectez plus de 20k banques dans plus de 40 pays (UK, UE, USA, etc.)mercury: Synchronisez automatiquement vos comptes professionnels Mercury.- onchain_wallet: Suivez vos portefeuilles Bitcoin, EVM et Solana en autoconservation à partir de leurs adresses publiques.+ onchain_wallet: Suivez vos portefeuilles Bitcoin, EVM, Solana et Polkadot en autoconservation à partir de leurs adresses publiques.plaid: Connectez des milliers d'institutions financières américaines via Plaid.plaid_eu: Connectez des institutions financières européennes via Plaid (PSD2 / Open Banking).questrade: Synchronisez directement vos comptes d'investissement Questrade via l'API Questrade.diff --git a/config/locales/views/settings/pl.yml b/config/locales/views/settings/pl.ymlindex 363cab1186..a21ae04b3b 100644--- a/config/locales/views/settings/pl.yml+++ b/config/locales/views/settings/pl.yml@@ -691,7 +691,7 @@ pl:mercury: Synchronizuj automatycznie swoje firmowe konta bankowe Mercury.monobank: Synchronizuj ukraińskie karty i skarbonki Monobank za pomocą osobistegotokenu API.- onchain_wallet: Śledź portfele Bitcoin, EVM i Solana z samodzielną kontrolą+ onchain_wallet: Śledź portfele Bitcoin, EVM, Solana i Polkadot z samodzielną kontroląkluczy na podstawie ich publicznych adresów.plaid: Połącz tysiące amerykańskich instytucji finansowych przez Plaid.plaid_eu: Połącz europejskie instytucje finansowe przez Plaid (PSD2 / otwartadiff --git a/config/locales/views/settings/providers/onchain_wallet_panel/de.yml b/config/locales/views/settings/providers/onchain_wallet_panel/de.ymlindex bb83c11084..6b027abca4 100644--- a/config/locales/views/settings/providers/onchain_wallet_panel/de.yml+++ b/config/locales/views/settings/providers/onchain_wallet_panel/de.yml@@ -3,7 +3,7 @@ de:settings:providers:taglines:- onchain_wallet: Verfolgt selbstverwahrte Bitcoin-, EVM- und Solana-Wallets über ihre öffentlichen Adressen.+ onchain_wallet: Verfolgt selbstverwahrte Bitcoin-, EVM-, Solana- und Polkadot-Wallets über ihre öffentlichen Adressen.onchain_wallet_panel:add_wallet: Wallet hinzufügenadvanced: Erweitertdiff --git a/config/locales/views/settings/pt-PT.yml b/config/locales/views/settings/pt-PT.ymlindex d8856417b5..9d0218e34b 100644--- a/config/locales/views/settings/pt-PT.yml+++ b/config/locales/views/settings/pt-PT.yml@@ -427,7 +427,7 @@ pt-PT:coinbase: Importe as suas posições cripto Coinbase e acompanhe o desempenho.binance: Sincronize os seus saldos à vista Binance utilizando uma chave de API apenas de leitura.kraken: Sincronize os saldos Kraken e as execuções de negociação à vista utilizando uma chave de API apenas de leitura.- onchain_wallet: Acompanhe carteiras Bitcoin, EVM e Solana de autocustódia a partir dos seus endereços públicos.+ onchain_wallet: Acompanhe carteiras Bitcoin, EVM, Solana e Polkadot de autocustódia a partir dos seus endereços públicos.snaptrade: Ligue contas de corretagem através da rede de agregação SnapTrade.trading212: Sincronize a sua carteira de investimento Trading 212 utilizando uma chave de API apenas de leitura.ibkr: Sincronize contas de investimento Interactive Brokers através de importações de Flex Query.diff --git a/config/locales/views/settings/ru.yml b/config/locales/views/settings/ru.ymlindex 0102c9d896..747b369291 100644--- a/config/locales/views/settings/ru.yml+++ b/config/locales/views/settings/ru.yml@@ -604,7 +604,7 @@ ru:fio: Синхронизируйте счёт Fio banka с помощью API-токена только для чтения.wise: Автоматически синхронизируйте мультивалютные балансы Wise и международные переводы.coinspot: Синхронизируйте балансы CoinSpot, стоимость в AUD, переводы, пополнения, выводы и историю ордеров с помощью API-ключа только для чтения.- onchain_wallet: Отслеживайте некастодиальные кошельки Bitcoin, EVM и Solana по их публичным адресам.+ onchain_wallet: Отслеживайте некастодиальные кошельки Bitcoin, EVM, Solana и Polkadot по их публичным адресам.trading212: Синхронизируйте инвестиционный портфель Trading 212 с помощью API-ключа только для чтения.trade_republic: Синхронизируйте инвестиционный счёт Trade Republic через защищённый веб-вход только для чтения.questrade: Синхронизируйте инвестиционные счета Questrade напрямую через Questrade API.diff --git a/config/locales/views/settings/tr.yml b/config/locales/views/settings/tr.ymlindex 9861284916..e6bd5a62a6 100644--- a/config/locales/views/settings/tr.yml+++ b/config/locales/views/settings/tr.yml@@ -616,7 +616,7 @@ tr:monobank: Ukrayna Monobank kartlarını ve kumbaralarını kişisel bir API token ile senkronize edin.fio: Bir Fio banka hesabını salt okunur bir API token ile senkronize edin.coinspot: CoinSpot bakiyelerini, AUD değerlerini, transferleri, para yatırma, para çekme ve emir geçmişini salt okunur bir API anahtarıyla senkronize edin.- onchain_wallet: Gözetimsiz Bitcoin, EVM ve Solana cüzdanlarını herkese açık adresleri üzerinden takip edin.+ onchain_wallet: Gözetimsiz Bitcoin, EVM, Solana ve Polkadot cüzdanlarını herkese açık adresleri üzerinden takip edin.trading212: Trading 212 yatırım portföyünüzü salt okunur bir API anahtarıyla senkronize edin.trade_republic: Trade Republic yatırım hesabınızı güvenli, salt okunur web girişiyle senkronize edin.up_panel:diff --git a/config/locales/views/settings/uk.yml b/config/locales/views/settings/uk.ymlindex 054b6c40c1..be063f256c 100644--- a/config/locales/views/settings/uk.yml+++ b/config/locales/views/settings/uk.yml@@ -460,7 +460,7 @@ uk:redbark: Синхронізуйте австралійські банківські рахунки через open banking Redbark.fio: Синхронізуйте рахунок у Fio banka за допомогою токена API лише для читання.coinspot: Синхронізуйте баланси CoinSpot, вартість в AUD, перекази, поповнення, виведення коштів та історію ордерів за допомогою ключа API лише для читання.- onchain_wallet: Відстежуйте некастодіальні гаманці Bitcoin, EVM і Solana за їхніми публічними адресами.+ onchain_wallet: Відстежуйте некастодіальні гаманці Bitcoin, EVM, Solana і Polkadot за їхніми публічними адресами.trading212: Синхронізуйте свій інвестиційний портфель Trading 212 за допомогою ключа API лише для читання.trade_republic: Синхронізуйте свій інвестиційний рахунок Trade Republic через захищений вхід у вебверсію лише для читання.search_filters:diff --git a/docs/hosting/onchain-wallets.md b/docs/hosting/onchain-wallets.mdindex 333bcdf46f..01b0573297 100644--- a/docs/hosting/onchain-wallets.md+++ b/docs/hosting/onchain-wallets.md@@ -1,7 +1,7 @@# On-chain (self-custody) wallets-Sure can track wallets you hold the keys to — Bitcoin, six EVM networks and-Solana — from their **public addresses only**. Nothing is signed, no key or seed+Sure can track wallets you hold the keys to — Bitcoin, six EVM networks,+Solana and Polkadot — from their **public addresses only**. Nothing is signed, no key or seedphrase is ever entered, and no API key is required for any chain.This document covers where the data comes from, what needs configuring, the@@ -78,6 +78,7 @@ listed, so the cause is visible without having to reproduce it.| Gnosis | Blockscout (`gnosis.blockscout.com`) | No | `BLOCKSCOUT_GNOSIS_URL` || Solana | Public JSON-RPC (`api.mainnet-beta.solana.com`) | No | `SOLANA_RPC_URL` || Solana token names | Jupiter token search (`lite-api.jup.ag`) | No | `SOLANA_TOKEN_LIST_URL` |+| Polkadot | Parity's public Asset Hub Sidecar | No | `POLKADOT_SIDECAR_URL` (must be an Asset Hub Sidecar) |Every override expects the base URL of a compatible instance, without a trailingslash — useful if you run your own indexer or node, or if a public endpoint rate@@ -109,6 +110,7 @@ address, the cost is roughly:| Bitcoin | 1 + up to 10 history pages || EVM | 1 summary + up to 10 pages of transfers + up to 10 pages of token transfers || Solana | ~2 + up to 25 transaction reads |+| Polkadot | 1 |History is capped by default at 10 pages per source — 250 transactions forBitcoin, 10 pages per EVM collection — and at 25 transactions for Solana, which@@ -240,6 +242,10 @@ only, rather than being handed the real asset's price. A handful of major mintsresolve without the list, so they keep working if it is unreachable. Names arecached for 24 hours per mint, misses included.+**Polkadot has no transfer history.** No keyless source indexes transfers, so+only the DOT balance on Asset Hub is read, staked DOT included. Other Asset Hub+tokens are not. Past transfers are not imported.+**Fees are not itemised.** Network fees are included in the net effect of eachtransfer rather than recorded separately. On Solana, native balance changes below0.0001 SOL are treated as fees and ignored.diff --git a/test/models/onchain/polkadot_adapter_test.rb b/test/models/onchain/polkadot_adapter_test.rbnew file mode 100644index 0000000000..3315ef3e24--- /dev/null+++ b/test/models/onchain/polkadot_adapter_test.rb@@ -0,0 +1,108 @@+# frozen_string_literal: true++require "test_helper"++class Onchain::PolkadotAdapterTest < ActiveSupport::TestCase+ ADDRESS = "12KeSVQBwS9AjRA976mnJouSAoQuS5bkWudT367GBEHE8Ls"++ setup do+ @adapter = Onchain::Chains.adapter_for(Onchain::Chains::POLKADOT)+ end++ test "accepts a Polkadot address" do+ assert @adapter.valid_address?(ADDRESS)+ assert @adapter.valid_address?(" #{ADDRESS} ")+ end++ test "rejects malformed addresses without making a network call" do+ [+ "",+ "12KeSVQBwS9AjRA976mnJouSAoQuS5bkWudT367GBEHE8L", # too short+ "12KeSVQBwS9AjRA976mnJouSAoQuS5bkWudT367GBEHE8L0", # Base58 excludes 0+ "5C62W7ELLAAfjCQeBU3me9ykaYomD8XTg2B9Hk6ki6Cm3v58", # generic Substrate prefix+ "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa" # a Bitcoin address+ ].each do |address|+ assert_not @adapter.valid_address?(address), "#{address.inspect} should be rejected"+ end+ end++ test "no other chain claims a Polkadot address" do+ assert_equal [ Onchain::Chains::POLKADOT ], Onchain::Chains.matching(ADDRESS).map(&:key)+ end++ test "an address keeps its case" do+ assert_equal ADDRESS, @adapter.canonical_address(" #{ADDRESS} ")+ end++ test "balance is free plus reserved, with no history" do+ stub_balance(free: "25000000000", reserved: "10000000000")++ snapshot = @adapter.fetch_snapshot(ADDRESS)++ asset = snapshot.assets.sole+ assert asset.native?+ assert_equal "DOT", asset.symbol+ assert_equal 10, asset.decimals+ assert_equal BigDecimal("3.5"), asset.quantity+ assert_empty snapshot.movements+ end++ test "a response without a balance is not read as zero" do+ stub_request(:get, balance_url).to_return(status: 200, body: {}.to_json, headers: { "Content-Type" => "application/json" })++ assert_raises Onchain::Chains::UnreachableError do+ @adapter.fetch_snapshot(ADDRESS)+ end+ end++ test "a non-numeric balance is not read as a number" do+ stub_balance(free: "25000000000oops", reserved: "0")++ assert_raises Onchain::Chains::UnreachableError do+ @adapter.fetch_snapshot(ADDRESS)+ end+ end++ test "an address the node rejects is reported as invalid, not unreachable" do+ stub_request(:get, balance_url).to_return(status: 400)++ error = assert_raises(Onchain::Chains::Error) { @adapter.fetch_snapshot(ADDRESS) }+ assert_not_kind_of Onchain::Chains::UnreachableError, error+ end++ test "fetch_snapshot refuses a malformed address before any request" do+ assert_raises Onchain::Chains::Error do+ @adapter.fetch_snapshot("not-an-address")+ end+ end++ test "a timed-out sidecar is reported as unreachable" do+ stub_request(:get, balance_url).to_timeout++ assert_raises Onchain::Chains::UnreachableError do+ @adapter.fetch_snapshot(ADDRESS)+ end+ end++ test "a sidecar that keeps throttling is reported as rate limited" do+ Provider::PolkadotSidecar.any_instance.stubs(:sleep)+ stub_request(:get, balance_url).to_return(status: 429)++ assert_raises Onchain::Chains::RateLimitedError do+ @adapter.fetch_snapshot(ADDRESS)+ end+ end++ private+ def balance_url+ "#{Provider::PolkadotSidecar.base_url}/accounts/#{ADDRESS}/balance-info"+ end++ def stub_balance(free:, reserved:)+ stub_request(:get, balance_url).to_return(+ status: 200,+ body: { "tokenSymbol" => "DOT", "free" => free, "reserved" => reserved }.to_json,+ headers: { "Content-Type" => "application/json" }+ )+ end+end