Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(onchain): track Cosmos Hub (ATOM) wallets (#4070)

PierroMojitof387ca34baa2
diff --git a/app/models/onchain/chains.rb b/app/models/onchain/chains.rb
index 9bb6463fdf..b23cd13858 100644
--- a/app/models/onchain/chains.rb
+++ b/app/models/onchain/chains.rb
@@ -92,6 +92,8 @@ module Onchain
SOLANA = "solana"
+ COSMOS = "cosmos"
+
POLKADOT = "polkadot"
BUILTIN = [
@@ -122,6 +124,13 @@ module Onchain
adapter_class_name: "Onchain::SolanaAdapter",
adapter_options: {}
),
+ Definition.new(
+ key: COSMOS,
+ native: NativeAsset.new(symbol: "ATOM", name: "Cosmos Hub", decimals: 6),
+ token_kind: nil,
+ adapter_class_name: "Onchain::CosmosAdapter",
+ adapter_options: {}
+ ),
Definition.new(
key: POLKADOT,
native: NativeAsset.new(symbol: "DOT", name: "Polkadot", decimals: 10),
diff --git a/app/models/onchain/cosmos_adapter.rb b/app/models/onchain/cosmos_adapter.rb
new file mode 100644
index 0000000000..1eb3409fa8
--- /dev/null
+++ b/app/models/onchain/cosmos_adapter.rb
@@ -0,0 +1,72 @@
+# frozen_string_literal: true
+
+# Cosmos Hub ATOM: spendable, staked and unbonding. Public nodes do not index
+# transactions, so only the balance is read.
+class Onchain::CosmosAdapter
+ include Onchain::ChainAdapter
+
+ DENOM = "uatom"
+ UATOM_PER_ATOM = 1_000_000.to_d
+
+ # Bech32 account address: a 20-byte key (38 characters) or a 32-byte module or
+ # interchain account (58). The character set excludes 1, b, i and o.
+ ADDRESS_PATTERN = /\Acosmos1(?:[ac-hj-np-z02-9]{38}|[ac-hj-np-z02-9]{58})\z/i
+
+ def initialize(credentials: {})
+ @credentials = credentials
+ end
+
+ def valid_address?(address)
+ ADDRESS_PATTERN.match?(address.to_s.strip)
+ end
+
+ # Bech32 is case-insensitive and canonically lowercase.
+ def canonical_address(address)
+ address.to_s.strip.downcase
+ end
+
+ def fetch_snapshot(address)
+ raise Onchain::Chains::Error, "Invalid Cosmos address" unless valid_address?(address)
+
+ wrap_provider_errors do
+ Onchain::Snapshot.new(
+ assets: [ definition.native_asset(quantity: balance_of(address)) ],
+ movements: []
+ )
+ rescue Provider::CosmosRest::InvalidAddressError
+ raise Onchain::Chains::Error, "Invalid Cosmos address"
+ end
+ end
+
+ def provider_error_classes
+ [ Provider::CosmosRest::RateLimitError, Provider::CosmosRest::Error ]
+ end
+
+ private
+ attr_reader :credentials
+
+ def definition
+ Onchain::Chains.find!(Onchain::Chains::COSMOS)
+ end
+
+ def provider
+ @provider ||= Provider::CosmosRest.new
+ end
+
+ def balance_of(address)
+ spendable = uatom(provider.balance(address, DENOM))
+ staked = provider.delegations(address).sum { |delegation| uatom(delegation.dig("balance", "amount")) }
+ unbonding = provider.unbonding_delegations(address).sum do |validator|
+ Array(validator["entries"]).sum { |entry| uatom(entry["balance"]) }
+ end
+
+ (spendable + staked + unbonding) / UATOM_PER_ATOM
+ end
+
+ # A missing amount must fail the sync, not read as zero.
+ def uatom(amount)
+ raise Provider::CosmosRest::ApiError, "Cosmos REST returned a malformed amount" unless amount.is_a?(String) && amount.match?(/\A\d+\z/)
+
+ amount.to_d
+ end
+end
diff --git a/app/models/provider/cosmos_rest.rb b/app/models/provider/cosmos_rest.rb
new file mode 100644
index 0000000000..d1adcd7fce
--- /dev/null
+++ b/app/models/provider/cosmos_rest.rb
@@ -0,0 +1,99 @@
+# frozen_string_literal: true
+
+# Keyless Cosmos Hub data source backed by a public Cosmos SDK REST (LCD)
+# endpoint. Self-hosters can point it at their own node with COSMOS_REST_URL.
+class Provider::CosmosRest
+ include HTTParty
+ include Provider::HttpTransport
+ include Provider::RateLimitable
+ extend SslConfigurable
+
+ class Error < StandardError; end
+ class InvalidAddressError < Error; end
+ class RateLimitError < Error; end
+ class ApiError < Error; end
+
+ DEFAULT_BASE_URL = "https://cosmos-rest.publicnode.com"
+ # Delegations and unbondings are one entry per validator.
+ PAGE_LIMIT = 200
+ MAX_PAGES = 5
+ MIN_REQUEST_INTERVAL = 0.25
+ MAX_RETRIES = 3
+ RETRY_BASE_DELAY = 0.5
+
+ default_options.merge!({ timeout: 30 }.merge(httparty_ssl_options))
+
+ def self.base_url
+ ENV["COSMOS_REST_URL"].presence || DEFAULT_BASE_URL
+ end
+
+ # @return [String] the spendable amount of `denom`, in its smallest unit
+ def balance(address, denom)
+ amount = get_json("/cosmos/bank/v1beta1/balances/#{encode(address)}/by_denom", denom: denom).dig("balance", "amount")
+ raise ApiError, "Cosmos REST returned no balance" if amount.nil?
+
+ amount
+ end
+
+ def delegations(address)
+ all_pages("/cosmos/staking/v1beta1/delegations/#{encode(address)}", "delegation_responses")
+ end
+
+ def unbonding_delegations(address)
+ all_pages("/cosmos/staking/v1beta1/delegators/#{encode(address)}/unbonding_delegations", "unbonding_responses")
+ end
+
+ private
+ # Reads every page: a partial list would pass for a whole, lower balance.
+ def all_pages(path, key)
+ entries = []
+ next_key = nil
+
+ MAX_PAGES.times do
+ body = get_json(path, { "pagination.limit": PAGE_LIMIT, "pagination.key": next_key }.compact)
+ raise ApiError, "Cosmos REST returned no #{key}" unless body.key?(key)
+
+ entries.concat(Array(body[key]))
+ next_key = body.dig("pagination", "next_key").presence
+ return entries if next_key.nil?
+ end
+
+ raise ApiError, "Cosmos REST returned more than #{MAX_PAGES} pages"
+ end
+
+ def encode(address)
+ ERB::Util.url_encode(address)
+ end
+
+ def get_json(path, query = {})
+ attempts = 0
+
+ begin
+ attempts += 1
+ throttle_request
+ translate_transport_errors { handle_response(self.class.get("#{self.class.base_url}#{path}", query: query)) }
+ rescue RateLimitError => e
+ raise if attempts > MAX_RETRIES
+
+ Rails.logger.warn("Provider::CosmosRest - rate limited (attempt #{attempts}/#{MAX_RETRIES}): #{e.message}")
+ sleep(RETRY_BASE_DELAY * (2**(attempts - 1)))
+ retry
+ end
+ end
+
+ def handle_response(response)
+ case response.code
+ when 200..299
+ body = response.parsed_response
+ raise ApiError, "Cosmos REST returned an unexpected body" unless body.is_a?(Hash)
+
+ body
+ when 400
+ raise InvalidAddressError, "Cosmos REST rejected the address"
+ when 429
+ raise RateLimitError, "Cosmos REST rate limit exceeded"
+ else
+ raise ApiError, "Cosmos REST API error: #{response.code}"
+ end
+ end
+end
diff --git a/config/locales/models/onchain_wallet_item/ca.yml b/config/locales/models/onchain_wallet_item/ca.yml
index cdb9230e61..3f744abdfe 100644
--- a/config/locales/models/onchain_wallet_item/ca.yml
+++ b/config/locales/models/onchain_wallet_item/ca.yml
@@ -5,6 +5,7 @@ ca:
arbitrum: Arbitrum
base: Base
bitcoin: Bitcoin
+ cosmos: Cosmos Hub
ethereum: Ethereum
gnosis: Gnosis
optimism: Optimism
diff --git a/config/locales/models/onchain_wallet_item/en.yml b/config/locales/models/onchain_wallet_item/en.yml
index 2189909b35..e443d3ab50 100644
--- a/config/locales/models/onchain_wallet_item/en.yml
+++ b/config/locales/models/onchain_wallet_item/en.yml
@@ -5,6 +5,7 @@ en:
arbitrum: Arbitrum
base: Base
bitcoin: Bitcoin
+ cosmos: Cosmos Hub
ethereum: Ethereum
gnosis: Gnosis
optimism: Optimism
diff --git a/config/locales/models/onchain_wallet_item/fr.yml b/config/locales/models/onchain_wallet_item/fr.yml
index 6395288e60..27a6c8b764 100644
--- a/config/locales/models/onchain_wallet_item/fr.yml
+++ b/config/locales/models/onchain_wallet_item/fr.yml
@@ -5,6 +5,7 @@ fr:
arbitrum: Arbitrum
base: Base
bitcoin: Bitcoin
+ cosmos: Cosmos Hub
ethereum: Ethereum
gnosis: Gnosis
optimism: Optimism
diff --git a/config/locales/models/onchain_wallet_item/pl.yml b/config/locales/models/onchain_wallet_item/pl.yml
index 362ce44bf8..26548eddf4 100644
--- a/config/locales/models/onchain_wallet_item/pl.yml
+++ b/config/locales/models/onchain_wallet_item/pl.yml
@@ -5,6 +5,7 @@ pl:
arbitrum: Arbitrum
base: Base
bitcoin: Bitcoin
+ cosmos: Cosmos Hub
ethereum: Ethereum
gnosis: Gnosis
optimism: Optimism
diff --git a/config/locales/models/onchain_wallet_item/pt-PT.yml b/config/locales/models/onchain_wallet_item/pt-PT.yml
index 7562bbb689..ef6dc5edd1 100644
--- a/config/locales/models/onchain_wallet_item/pt-PT.yml
+++ b/config/locales/models/onchain_wallet_item/pt-PT.yml
@@ -5,6 +5,7 @@ pt-PT:
arbitrum: Arbitrum
base: Base
bitcoin: Bitcoin
+ cosmos: Cosmos Hub
ethereum: Ethereum
gnosis: Gnosis
optimism: Optimism
diff --git a/config/locales/models/onchain_wallet_item/ru.yml b/config/locales/models/onchain_wallet_item/ru.yml
index c5d3ea27cb..a1bc217da9 100644
--- a/config/locales/models/onchain_wallet_item/ru.yml
+++ b/config/locales/models/onchain_wallet_item/ru.yml
@@ -5,6 +5,7 @@ ru:
arbitrum: Arbitrum
base: Base
bitcoin: Bitcoin
+ cosmos: Cosmos Hub
ethereum: Ethereum
gnosis: Gnosis
optimism: Optimism
diff --git a/config/locales/models/onchain_wallet_item/tr.yml b/config/locales/models/onchain_wallet_item/tr.yml
index b896fae522..47e8baaee6 100644
--- a/config/locales/models/onchain_wallet_item/tr.yml
+++ b/config/locales/models/onchain_wallet_item/tr.yml
@@ -5,6 +5,7 @@ tr:
arbitrum: Arbitrum
base: Base
bitcoin: Bitcoin
+ cosmos: Cosmos Hub
ethereum: Ethereum
gnosis: Gnosis
optimism: Optimism
diff --git a/config/locales/models/onchain_wallet_item/uk.yml b/config/locales/models/onchain_wallet_item/uk.yml
index ad5f956587..d1ef6936bf 100644
--- a/config/locales/models/onchain_wallet_item/uk.yml
+++ b/config/locales/models/onchain_wallet_item/uk.yml
@@ -5,6 +5,7 @@ uk:
arbitrum: Arbitrum
base: Base
bitcoin: Bitcoin
+ cosmos: Cosmos Hub
ethereum: Ethereum
gnosis: Gnosis
optimism: Optimism
diff --git a/config/locales/views/settings/ca.yml b/config/locales/views/settings/ca.yml
index 80fc13e348..1171fde741 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, Solana i Polkadot d'autocustòdia a partir de les seves adreces públiques.
+ onchain_wallet: Fes el seguiment de carteres Bitcoin, EVM, Solana, Cosmos 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.yml
index eb674eaa6a..8cfdccaf7e 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, Solana and Polkadot wallets from their public addresses.
+ onchain_wallet: Track self-custody Bitcoin, EVM, Solana, Cosmos 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.yml
index d04272fe8a..4c18e6a114 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, Solana et Polkadot en autoconservation à partir de leurs adresses publiques.
+ onchain_wallet: Suivez vos portefeuilles Bitcoin, EVM, Solana, Cosmos 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.yml
index a21ae04b3b..3b7010808b 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ą osobistego
tokenu API.
- onchain_wallet: Śledź portfele Bitcoin, EVM, Solana i Polkadot z samodzielną kontrolą
+ onchain_wallet: Śledź portfele Bitcoin, EVM, Solana, Cosmos 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 / otwarta
diff --git a/config/locales/views/settings/providers/onchain_wallet_panel/de.yml b/config/locales/views/settings/providers/onchain_wallet_panel/de.yml
index 6b027abca4..05178a2692 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-, Solana- und Polkadot-Wallets über ihre öffentlichen Adressen.
+ onchain_wallet: Verfolgt selbstverwahrte Bitcoin-, EVM-, Solana-, Cosmos- und Polkadot-Wallets über ihre öffentlichen Adressen.
onchain_wallet_panel:
add_wallet: Wallet hinzufügen
advanced: Erweitert
diff --git a/config/locales/views/settings/pt-PT.yml b/config/locales/views/settings/pt-PT.yml
index 9d0218e34b..c2ba771cd7 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, Solana e Polkadot de autocustódia a partir dos seus endereços públicos.
+ onchain_wallet: Acompanhe carteiras Bitcoin, EVM, Solana, Cosmos 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.yml
index 747b369291..1a5376976c 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 и Polkadot по их публичным адресам.
+ onchain_wallet: Отслеживайте некастодиальные кошельки Bitcoin, EVM, Solana, Cosmos и 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.yml
index e6bd5a62a6..9d757c9fd7 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, Solana ve Polkadot cüzdanlarını herkese açık adresleri üzerinden takip edin.
+ onchain_wallet: Gözetimsiz Bitcoin, EVM, Solana, Cosmos 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.yml
index be063f256c..dc488adb9c 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 і Polkadot за їхніми публічними адресами.
+ onchain_wallet: Відстежуйте некастодіальні гаманці Bitcoin, EVM, Solana, Cosmos і Polkadot за їхніми публічними адресами.
trading212: Синхронізуйте свій інвестиційний портфель Trading 212 за допомогою ключа API лише для читання.
trade_republic: Синхронізуйте свій інвестиційний рахунок Trade Republic через захищений вхід у вебверсію лише для читання.
search_filters:
diff --git a/docs/hosting/onchain-wallets.md b/docs/hosting/onchain-wallets.md
index 01b0573297..568870baef 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,
-Solana and Polkadot — from their **public addresses only**. Nothing is signed, no key or seed
+Solana, Polkadot and the Cosmos Hub — from their **public addresses only**. Nothing is signed, no key or seed
phrase 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` |
+| Cosmos Hub | Public REST node (`cosmos-rest.publicnode.com`) | No | `COSMOS_REST_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 trailing
@@ -110,6 +111,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 |
+| Cosmos Hub | 3, plus a page per extra 200 validators staked with |
| Polkadot | 1 |
History is capped by default at 10 pages per source — 250 transactions for
@@ -242,6 +244,11 @@ only, rather than being handed the real asset's price. A handful of major mints
resolve without the list, so they keep working if it is unreachable. Names are
cached for 24 hours per mint, misses included.
+**Cosmos Hub has no transfer history.** Public nodes do not index
+transactions, so only the ATOM balance is read: spendable, staked and unbonding,
+but not unclaimed rewards or IBC tokens. Past transfers are not
+imported.
+
**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.
diff --git a/test/models/onchain/cosmos_adapter_test.rb b/test/models/onchain/cosmos_adapter_test.rb
new file mode 100644
index 0000000000..b49b4b21b8
--- /dev/null
+++ b/test/models/onchain/cosmos_adapter_test.rb
@@ -0,0 +1,150 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class Onchain::CosmosAdapterTest < ActiveSupport::TestCase
+ ADDRESS = "cosmos1qypqxpq9qcrsszg2pvxq6rs0zqg3yyc5lzv7xu"
+ MODULE_ADDRESS = "cosmos1qypqxpq9qcrsszg2pvxq6rs0zqg3yyc5z5tpwxqergd3c8g7rusqqlvp8l"
+
+ setup do
+ @adapter = Onchain::Chains.adapter_for(Onchain::Chains::COSMOS)
+ end
+
+ test "accepts account and module addresses" do
+ [ ADDRESS, MODULE_ADDRESS, ADDRESS.upcase ].each do |address|
+ assert @adapter.valid_address?(address), "#{address} should be accepted"
+ end
+ end
+
+ test "rejects malformed addresses without making a network call" do
+ [
+ "",
+ "cosmos1qypqxpq9qcrsszg2pvxq6rs0zqg3yyc5lzv7x", # too short
+ "cosmos1qypqxpq9qcrsszg2pvxq6rs0zqg3yyc5lzv7xb", # bech32 excludes b
+ "osmo1qypqxpq9qcrsszg2pvxq6rs0zqg3yyc5lzv7xu", # another Cosmos chain
+ "cosmosvaloper1qypqxpq9qcrsszg2pvxq6rs0zqg3yyc5lzv7xu",
+ "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
+ ].each do |address|
+ assert_not @adapter.valid_address?(address), "#{address.inspect} should be rejected"
+ end
+ end
+
+ test "no other chain claims a Cosmos address" do
+ assert_equal [ Onchain::Chains::COSMOS ], Onchain::Chains.matching(ADDRESS).map(&:key)
+ end
+
+ test "an address is canonically lowercase" do
+ assert_equal ADDRESS, @adapter.canonical_address(" #{ADDRESS.upcase} ")
+ end
+
+ test "balance is spendable plus staked plus unbonding, with no history" do
+ stub_balance("1500000")
+ stub_delegations([
+ { "balance" => { "denom" => "uatom", "amount" => "2000000" } },
+ { "balance" => { "denom" => "uatom", "amount" => "250000" } }
+ ])
+ stub_unbondings([ { "entries" => [ { "balance" => "100000" }, { "balance" => "50000" } ] } ])
+
+ snapshot = @adapter.fetch_snapshot(ADDRESS)
+
+ asset = snapshot.assets.sole
+ assert asset.native?
+ assert_equal "ATOM", asset.symbol
+ assert_equal 6, asset.decimals
+ assert_equal BigDecimal("3.9"), asset.quantity
+ assert_empty snapshot.movements
+ end
+
+ test "an empty address is worth zero" do
+ stub_balance("0")
+ stub_delegations([])
+ stub_unbondings([])
+
+ assert_equal 0, @adapter.fetch_snapshot(ADDRESS).assets.sole.quantity
+ end
+
+ test "staking spread over several pages is summed" do
+ stub_balance("0")
+ stub_json(
+ "/cosmos/staking/v1beta1/delegations/#{ADDRESS}", { "pagination.limit" => "200" },
+ { "delegation_responses" => [ { "balance" => { "denom" => "uatom", "amount" => "1000000" } } ], "pagination" => { "next_key" => "abc" } }
+ )
+ stub_json(
+ "/cosmos/staking/v1beta1/delegations/#{ADDRESS}", { "pagination.limit" => "200", "pagination.key" => "abc" },
+ { "delegation_responses" => [ { "balance" => { "denom" => "uatom", "amount" => "2000000" } } ], "pagination" => { "next_key" => nil } }
+ )
+ stub_unbondings([])
+
+ assert_equal BigDecimal("3"), @adapter.fetch_snapshot(ADDRESS).assets.sole.quantity
+ end
+
+ test "a response without a balance is not read as zero" do
+ stub_json("/cosmos/bank/v1beta1/balances/#{ADDRESS}/by_denom", { denom: "uatom" }, {})
+
+ assert_raises Onchain::Chains::UnreachableError do
+ @adapter.fetch_snapshot(ADDRESS)
+ end
+ end
+
+ test "a staking entry without a balance is not read as zero" do
+ stub_balance("1500000")
+ stub_delegations([ { "balance" => { "denom" => "uatom", "amount" => "2000000" } } ])
+ stub_unbondings([ { "entries" => [ { "balance" => "100000" }, {} ] } ])
+
+ 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, "#{base_url}/cosmos/bank/v1beta1/balances/#{ADDRESS}/by_denom").with(query: { denom: "uatom" }).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 node is reported as unreachable" do
+ stub_request(:get, "#{base_url}/cosmos/bank/v1beta1/balances/#{ADDRESS}/by_denom").with(query: { denom: "uatom" }).to_timeout
+
+ assert_raises Onchain::Chains::UnreachableError do
+ @adapter.fetch_snapshot(ADDRESS)
+ end
+ end
+
+ test "a node that keeps throttling is reported as rate limited" do
+ Provider::CosmosRest.any_instance.stubs(:sleep)
+ stub_request(:get, "#{base_url}/cosmos/bank/v1beta1/balances/#{ADDRESS}/by_denom").with(query: { denom: "uatom" }).to_return(status: 429)
+
+ assert_raises Onchain::Chains::RateLimitedError do
+ @adapter.fetch_snapshot(ADDRESS)
+ end
+ end
+
+ private
+ def base_url
+ Provider::CosmosRest.base_url
+ end
+
+ def stub_balance(amount)
+ stub_json("/cosmos/bank/v1beta1/balances/#{ADDRESS}/by_denom", { denom: "uatom" }, { "balance" => { "denom" => "uatom", "amount" => amount } })
+ end
+
+ def stub_delegations(responses)
+ stub_json("/cosmos/staking/v1beta1/delegations/#{ADDRESS}", { "pagination.limit" => "200" }, { "delegation_responses" => responses })
+ end
+
+ def stub_unbondings(responses)
+ stub_json("/cosmos/staking/v1beta1/delegators/#{ADDRESS}/unbonding_delegations", { "pagination.limit" => "200" }, { "unbonding_responses" => responses })
+ end
+
+ def stub_json(path, query, body)
+ stub_request(:get, "#{base_url}#{path}").with(query: query)
+ .to_return(status: 200, body: body.to_json, headers: { "Content-Type" => "application/json" })
+ end
+end