@onecraft/wallet 0.0.0-stage → 0.1.145
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +20 -0
- package/.openclaw/AGENTS.md +100 -0
- package/.openclaw/extensions/agent-wallet/README.md +195 -0
- package/.openclaw/extensions/agent-wallet/dist/index.js +2198 -0
- package/.openclaw/extensions/agent-wallet/index.ts +2198 -0
- package/.openclaw/extensions/agent-wallet/openclaw.plugin.json +251 -0
- package/.openclaw/extensions/agent-wallet/package.json +49 -0
- package/.openclaw/extensions/agent-wallet/skills/cards/SKILL.md +211 -0
- package/.openclaw/extensions/agent-wallet/skills/wallet-operator/SKILL.md +30 -0
- package/CHANGELOG.md +1232 -0
- package/LICENSE +104 -0
- package/README.md +193 -2
- package/VERSION +1 -0
- package/agent-wallet/.env.example +63 -0
- package/agent-wallet/AGENTS.md +130 -0
- package/agent-wallet/CARD_VAULT.md +640 -0
- package/agent-wallet/README.md +615 -0
- package/agent-wallet/UPGRADE_COMPATIBILITY.md +66 -0
- package/agent-wallet/agent_wallet/__init__.py +16 -0
- package/agent-wallet/agent_wallet/approval.py +165 -0
- package/agent-wallet/agent_wallet/autonomous_permissions.py +281 -0
- package/agent-wallet/agent_wallet/autonomous_policy.py +305 -0
- package/agent-wallet/agent_wallet/autonomous_session.py +236 -0
- package/agent-wallet/agent_wallet/boot_key_migration.py +155 -0
- package/agent-wallet/agent_wallet/boot_key_recovery.py +57 -0
- package/agent-wallet/agent_wallet/bootstrap.py +194 -0
- package/agent-wallet/agent_wallet/card_catalog.py +243 -0
- package/agent-wallet/agent_wallet/card_runtime_secrets.py +108 -0
- package/agent-wallet/agent_wallet/card_vault.py +331 -0
- package/agent-wallet/agent_wallet/card_vault_cli.py +174 -0
- package/agent-wallet/agent_wallet/card_vault_import.py +65 -0
- package/agent-wallet/agent_wallet/card_vault_keychain.py +239 -0
- package/agent-wallet/agent_wallet/config.py +719 -0
- package/agent-wallet/agent_wallet/connector_cli.py +198 -0
- package/agent-wallet/agent_wallet/connectors/__init__.py +28 -0
- package/agent-wallet/agent_wallet/connectors/catalog.py +68 -0
- package/agent-wallet/agent_wallet/connectors/client.py +308 -0
- package/agent-wallet/agent_wallet/connectors/intent_policy.py +243 -0
- package/agent-wallet/agent_wallet/connectors/manifest.py +192 -0
- package/agent-wallet/agent_wallet/connectors/registry.py +341 -0
- package/agent-wallet/agent_wallet/encrypted_storage.py +314 -0
- package/agent-wallet/agent_wallet/evm_user_wallets.py +910 -0
- package/agent-wallet/agent_wallet/exceptions.py +10 -0
- package/agent-wallet/agent_wallet/file_ops.py +34 -0
- package/agent-wallet/agent_wallet/http_client.py +25 -0
- package/agent-wallet/agent_wallet/kernel_browser.py +479 -0
- package/agent-wallet/agent_wallet/kernel_cli.py +57 -0
- package/agent-wallet/agent_wallet/kernel_gateway.py +95 -0
- package/agent-wallet/agent_wallet/keystore.py +503 -0
- package/agent-wallet/agent_wallet/laso_card_vault.py +246 -0
- package/agent-wallet/agent_wallet/models.py +66 -0
- package/agent-wallet/agent_wallet/morpho_monitor.py +298 -0
- package/agent-wallet/agent_wallet/nonce_registry.py +59 -0
- package/agent-wallet/agent_wallet/openclaw_adapter.py +9129 -0
- package/agent-wallet/agent_wallet/openclaw_cli.py +658 -0
- package/agent-wallet/agent_wallet/openclaw_runtime.py +194 -0
- package/agent-wallet/agent_wallet/plugin_bundle.py +44 -0
- package/agent-wallet/agent_wallet/providers/__init__.py +1 -0
- package/agent-wallet/agent_wallet/providers/bags.py +202 -0
- package/agent-wallet/agent_wallet/providers/dexscreener.py +147 -0
- package/agent-wallet/agent_wallet/providers/evm_activity.py +257 -0
- package/agent-wallet/agent_wallet/providers/evm_portfolio.py +459 -0
- package/agent-wallet/agent_wallet/providers/imd.py +720 -0
- package/agent-wallet/agent_wallet/providers/jupiter.py +519 -0
- package/agent-wallet/agent_wallet/providers/kamino.py +404 -0
- package/agent-wallet/agent_wallet/providers/lifi.py +302 -0
- package/agent-wallet/agent_wallet/providers/solana_rpc.py +447 -0
- package/agent-wallet/agent_wallet/providers/tokenized_stocks.py +189 -0
- package/agent-wallet/agent_wallet/providers/wdk_evm_local.py +346 -0
- package/agent-wallet/agent_wallet/providers/x402.py +1972 -0
- package/agent-wallet/agent_wallet/sealed_keys.py +118 -0
- package/agent-wallet/agent_wallet/solana_stake.py +103 -0
- package/agent-wallet/agent_wallet/solana_tx.py +93 -0
- package/agent-wallet/agent_wallet/spending_limits.py +119 -0
- package/agent-wallet/agent_wallet/telemetry.py +481 -0
- package/agent-wallet/agent_wallet/transaction_policy.py +573 -0
- package/agent-wallet/agent_wallet/update_check.py +190 -0
- package/agent-wallet/agent_wallet/user_wallets.py +573 -0
- package/agent-wallet/agent_wallet/validation.py +31 -0
- package/agent-wallet/agent_wallet/vault_executor.py +456 -0
- package/agent-wallet/agent_wallet/wallet_layer/__init__.py +1 -0
- package/agent-wallet/agent_wallet/wallet_layer/base.py +1204 -0
- package/agent-wallet/agent_wallet/wallet_layer/base58.py +44 -0
- package/agent-wallet/agent_wallet/wallet_layer/factory.py +117 -0
- package/agent-wallet/agent_wallet/wallet_layer/solana.py +5246 -0
- package/agent-wallet/agent_wallet/wallet_layer/wdk_evm.py +2705 -0
- package/agent-wallet/examples/bootstrap_wallet.py +21 -0
- package/agent-wallet/examples/openclaw_runtime_onboarding.py +28 -0
- package/agent-wallet/examples/openclaw_user_wallet_example.py +31 -0
- package/agent-wallet/examples/openclaw_wallet_adapter_example.py +33 -0
- package/agent-wallet/openclaw.plugin.json +118 -0
- package/agent-wallet/pyproject.toml +36 -0
- package/agent-wallet/scripts/bootstrap_openclaw_evm.py +312 -0
- package/agent-wallet/scripts/build_release_bundle.py +210 -0
- package/agent-wallet/scripts/finalize_openclaw_local_wallet_config.py +121 -0
- package/agent-wallet/scripts/install_agent_wallet.py +1357 -0
- package/agent-wallet/scripts/install_openclaw_local_config.py +421 -0
- package/agent-wallet/scripts/install_openclaw_sealed_keys.py +117 -0
- package/agent-wallet/scripts/manage_openclaw_evm_wallet.py +333 -0
- package/agent-wallet/scripts/security_utils.py +37 -0
- package/agent-wallet/scripts/setup_evm_wallet.sh +140 -0
- package/agent-wallet/scripts/switch_openclaw_wallet_network.py +109 -0
- package/agent-wallet/skills/wallet-operator/SKILL.md +157 -0
- package/bin/lib/boot-key.mjs +184 -0
- package/bin/lib/evm-daemon.mjs +389 -0
- package/bin/lib/host-detection.mjs +259 -0
- package/bin/lib/integrations.mjs +578 -0
- package/bin/lib/release-python.mjs +9 -0
- package/bin/lib/update-transaction.mjs +235 -0
- package/bin/openclaw-agent-wallet.mjs +3354 -0
- package/claude-code/plugins/agent-wallet/.claude-plugin/plugin.json +19 -0
- package/claude-code/plugins/agent-wallet/.mcp.json +14 -0
- package/claude-code/plugins/agent-wallet/AGENTLAYER_AGENT_GUIDE.md +282 -0
- package/claude-code/plugins/agent-wallet/README.md +134 -0
- package/claude-code/plugins/agent-wallet/commands/agentlayer-autonomous-approve.md +39 -0
- package/claude-code/plugins/agent-wallet/commands/agentlayer-autonomous-revoke.md +17 -0
- package/claude-code/plugins/agent-wallet/commands/cards.md +129 -0
- package/claude-code/plugins/agent-wallet/commands/guide.md +40 -0
- package/claude-code/plugins/agent-wallet/commands/imd.md +125 -0
- package/claude-code/plugins/agent-wallet/commands/wallet-base.md +60 -0
- package/claude-code/plugins/agent-wallet/commands/wallet-ethereum.md +37 -0
- package/claude-code/plugins/agent-wallet/commands/wallet-evm.md +39 -0
- package/claude-code/plugins/agent-wallet/commands/wallet-setup.md +25 -0
- package/claude-code/plugins/agent-wallet/commands/wallet-sol.md +51 -0
- package/claude-code/plugins/agent-wallet/commands/wallet-statusline.md +34 -0
- package/claude-code/plugins/agent-wallet/commands/x402.md +121 -0
- package/claude-code/plugins/agent-wallet/commands/yield.md +62 -0
- package/claude-code/plugins/agent-wallet/hooks/hooks.json +16 -0
- package/claude-code/plugins/agent-wallet/scripts/bootstrap_backend.sh +136 -0
- package/claude-code/plugins/agent-wallet/scripts/enable_statusline.py +52 -0
- package/claude-code/plugins/agent-wallet/scripts/resolve_wallet_addresses.py +69 -0
- package/claude-code/plugins/agent-wallet/scripts/run_mcp.sh +66 -0
- package/claude-code/plugins/agent-wallet/scripts/wallet_statusline.py +130 -0
- package/claude-code/plugins/agent-wallet/scripts/wallet_statusline_setup.sh +40 -0
- package/claude-code/plugins/agent-wallet/skills/wallet-operator/SKILL.md +21 -0
- package/codex/plugins/agent-wallet/.codex-plugin/plugin.json +37 -0
- package/codex/plugins/agent-wallet/.mcp.json +15 -0
- package/codex/plugins/agent-wallet/README.md +158 -0
- package/codex/plugins/agent-wallet/scripts/run_mcp.sh +47 -0
- package/codex/plugins/agent-wallet/server.py +1797 -0
- package/codex/plugins/agent-wallet/skills/cards/SKILL.md +225 -0
- package/codex/plugins/agent-wallet/skills/imd/SKILL.md +145 -0
- package/codex/plugins/agent-wallet/skills/wallet-base/SKILL.md +56 -0
- package/codex/plugins/agent-wallet/skills/wallet-operator/SKILL.md +85 -0
- package/codex/plugins/agent-wallet/skills/wallet-sol/SKILL.md +29 -0
- package/codex/plugins/agent-wallet/skills/x402/SKILL.md +159 -0
- package/codex/plugins/agent-wallet/skills/yield/SKILL.md +65 -0
- package/connectors/AGENTS.md +37 -0
- package/connectors/DEVELOPER_GUIDE.md +131 -0
- package/connectors/README.md +139 -0
- package/connectors/READ_ONLY_BETA.md +54 -0
- package/connectors/RELEASING.md +48 -0
- package/connectors/conformance/README.md +31 -0
- package/connectors/conformance/package.json +54 -0
- package/connectors/conformance/scripts/sync-license.mjs +3 -0
- package/connectors/conformance/scripts/sync-spec.mjs +16 -0
- package/connectors/conformance/src/cli.ts +43 -0
- package/connectors/conformance/src/index.ts +7 -0
- package/connectors/conformance/src/runner.ts +314 -0
- package/connectors/conformance/src/types.ts +27 -0
- package/connectors/conformance/test/fixtures/invalid-response-identity.json +14 -0
- package/connectors/conformance/test/fixtures/missing-tool-fixture.json +4 -0
- package/connectors/conformance/test/runner.test.mjs +151 -0
- package/connectors/conformance/tsconfig.json +17 -0
- package/connectors/examples/reference-crypto-data/Dockerfile +21 -0
- package/connectors/examples/reference-crypto-data/README.md +51 -0
- package/connectors/examples/reference-crypto-data/conformance.json +11 -0
- package/connectors/examples/reference-crypto-data/connector.json +95 -0
- package/connectors/examples/reference-crypto-data/package.json +21 -0
- package/connectors/examples/reference-crypto-data/railway.toml +9 -0
- package/connectors/examples/reference-crypto-data/src/connector.ts +137 -0
- package/connectors/examples/reference-crypto-data/src/server.ts +13 -0
- package/connectors/examples/reference-crypto-data/test/connector.test.mjs +97 -0
- package/connectors/examples/reference-crypto-data/tsconfig.json +17 -0
- package/connectors/package-lock.json +561 -0
- package/connectors/package.json +19 -0
- package/connectors/scripts/smoke-packed-packages.mjs +121 -0
- package/connectors/sdk-typescript/README.md +47 -0
- package/connectors/sdk-typescript/package.json +49 -0
- package/connectors/sdk-typescript/scripts/sync-license.mjs +3 -0
- package/connectors/sdk-typescript/src/connector.ts +204 -0
- package/connectors/sdk-typescript/src/errors.ts +11 -0
- package/connectors/sdk-typescript/src/http.ts +116 -0
- package/connectors/sdk-typescript/src/index.ts +26 -0
- package/connectors/sdk-typescript/src/types.ts +101 -0
- package/connectors/sdk-typescript/test/sdk.test.mjs +181 -0
- package/connectors/sdk-typescript/tsconfig.json +21 -0
- package/connectors/spec/connector-manifest.schema.json +340 -0
- package/connectors/spec/connector-protocol.md +159 -0
- package/connectors/spec/transaction-intent.schema.json +281 -0
- package/connectors/templates/read-only/.env.example +1 -0
- package/connectors/templates/read-only/Dockerfile +11 -0
- package/connectors/templates/read-only/README.md +33 -0
- package/connectors/templates/read-only/conformance.json +11 -0
- package/connectors/templates/read-only/connector.json +64 -0
- package/connectors/templates/read-only/package.json +21 -0
- package/connectors/templates/read-only/railway.toml +9 -0
- package/connectors/templates/read-only/src/connector.ts +61 -0
- package/connectors/templates/read-only/src/server.ts +14 -0
- package/connectors/templates/read-only/test/connector.test.mjs +62 -0
- package/connectors/templates/read-only/tsconfig.json +17 -0
- package/cursor/plugins/agent-wallet/.cursor-plugin/plugin.json +14 -0
- package/cursor/plugins/agent-wallet/README.md +62 -0
- package/cursor/plugins/agent-wallet/mcp.json +16 -0
- package/cursor/plugins/agent-wallet/scripts/run_mcp.sh +33 -0
- package/cursor/plugins/agent-wallet/server.py +33 -0
- package/cursor/plugins/agent-wallet/skills/cards/SKILL.md +210 -0
- package/cursor/plugins/agent-wallet/skills/wallet-base/SKILL.md +56 -0
- package/cursor/plugins/agent-wallet/skills/wallet-operator/SKILL.md +23 -0
- package/cursor/plugins/agent-wallet/skills/wallet-sol/SKILL.md +29 -0
- package/cursor/plugins/agent-wallet/skills/x402/SKILL.md +130 -0
- package/hermes/plugins/agent_wallet/README.md +54 -0
- package/hermes/plugins/agent_wallet/__init__.py +55 -0
- package/hermes/plugins/agent_wallet/plugin.yaml +9 -0
- package/hermes/plugins/agent_wallet/schemas.py +211 -0
- package/hermes/plugins/agent_wallet/tools.py +622 -0
- package/install-from-github.sh +139 -0
- package/integrations/hedera/treasury-guard/README.md +92 -0
- package/integrations/hedera/treasury-guard/examples/treasury-policy.example.json +9 -0
- package/integrations/hedera/treasury-guard/package-lock.json +880 -0
- package/integrations/hedera/treasury-guard/package.json +8 -0
- package/integrations/hedera/treasury-guard/skills/onecraft-hedera-treasury/SKILL.md +22 -0
- package/integrations/hedera/treasury-guard/src/hedera-mirror-client.mjs +106 -0
- package/integrations/hedera/treasury-guard/src/hedera-signer.mjs +120 -0
- package/integrations/hedera/treasury-guard/src/treasury-cli.mjs +177 -0
- package/integrations/hedera/treasury-guard/src/treasury-policy.mjs +155 -0
- package/mcp/README.md +39 -0
- package/mcp/scripts/run_mcp.sh +37 -0
- package/mcp/server.py +33 -0
- package/package.json +106 -4
- package/scripts/check_release_version.mjs +72 -0
- package/scripts/version_targets.mjs +60 -0
- package/setup.sh +87 -0
- package/wdk-evm-wallet/.env.example +38 -0
- package/wdk-evm-wallet/README.md +254 -0
- package/wdk-evm-wallet/bootstrap.sh +8 -0
- package/wdk-evm-wallet/package-lock.json +2359 -0
- package/wdk-evm-wallet/package.json +43 -0
- package/wdk-evm-wallet/run-local.sh +12 -0
- package/wdk-evm-wallet/src/config.js +461 -0
- package/wdk-evm-wallet/src/imd.js +231 -0
- package/wdk-evm-wallet/src/json.js +35 -0
- package/wdk-evm-wallet/src/local_vault.js +407 -0
- package/wdk-evm-wallet/src/network_state.js +96 -0
- package/wdk-evm-wallet/src/pending_transactions.js +148 -0
- package/wdk-evm-wallet/src/server.js +849 -0
- package/wdk-evm-wallet/src/shutdown.js +63 -0
- package/wdk-evm-wallet/src/wdk_evm_wallet.js +10036 -0
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
"""Solana JSON-RPC provider with simple fallback logic."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import logging
|
|
7
|
+
import time
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
from agent_wallet.config import settings
|
|
13
|
+
from agent_wallet.exceptions import ProviderError
|
|
14
|
+
from agent_wallet.http_client import get_client
|
|
15
|
+
|
|
16
|
+
log = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
SOLANA_RPC_FALLBACK = "https://api.mainnet-beta.solana.com"
|
|
19
|
+
LAMPORTS_PER_SOL = 1_000_000_000
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _is_gateway_url(rpc_url: str) -> bool:
|
|
23
|
+
return rpc_url.startswith("gateway::")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _parse_gateway_url(rpc_url: str) -> tuple[str, str, str]:
|
|
27
|
+
try:
|
|
28
|
+
parts = rpc_url.split("::", 3)
|
|
29
|
+
except ValueError as exc:
|
|
30
|
+
raise ProviderError("solana-rpc", f"Malformed provider gateway rpc url: {rpc_url}") from exc
|
|
31
|
+
if len(parts) == 4:
|
|
32
|
+
_, provider, network, url = parts
|
|
33
|
+
elif len(parts) == 3:
|
|
34
|
+
_, provider, url = parts
|
|
35
|
+
network = "mainnet"
|
|
36
|
+
else:
|
|
37
|
+
raise ProviderError("solana-rpc", f"Malformed provider gateway rpc url: {rpc_url}")
|
|
38
|
+
if not url.strip():
|
|
39
|
+
raise ProviderError("solana-rpc", f"Malformed provider gateway rpc url: {rpc_url}")
|
|
40
|
+
return provider.strip() or "auto", network.strip().lower() or "mainnet", url.strip()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _fallback_for_rpc_url(rpc_url: str) -> str:
|
|
44
|
+
"""Choose a cluster-appropriate official fallback URL."""
|
|
45
|
+
return SOLANA_RPC_FALLBACK
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _normalize_rpc_urls(rpc_url: str | list[str]) -> list[str]:
|
|
49
|
+
if isinstance(rpc_url, list):
|
|
50
|
+
raw_values = rpc_url
|
|
51
|
+
else:
|
|
52
|
+
raw_values = [part.strip() for part in str(rpc_url).split(",")]
|
|
53
|
+
|
|
54
|
+
candidates: list[str] = []
|
|
55
|
+
for raw in raw_values:
|
|
56
|
+
if raw is None:
|
|
57
|
+
continue
|
|
58
|
+
value = str(raw).strip()
|
|
59
|
+
if value.lower() in {"", "none", "null"}:
|
|
60
|
+
continue
|
|
61
|
+
if value and value not in candidates:
|
|
62
|
+
candidates.append(value)
|
|
63
|
+
|
|
64
|
+
fallback = _fallback_for_rpc_url(candidates[0] if candidates else "")
|
|
65
|
+
if fallback and fallback not in candidates:
|
|
66
|
+
candidates.append(fallback)
|
|
67
|
+
return candidates
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _retry_after_seconds(response: httpx.Response) -> float:
|
|
71
|
+
header = response.headers.get("retry-after", "").strip()
|
|
72
|
+
if not header:
|
|
73
|
+
return 0.0
|
|
74
|
+
try:
|
|
75
|
+
return max(float(header), 0.0)
|
|
76
|
+
except ValueError:
|
|
77
|
+
return 0.0
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
async def _do_rpc_call(rpc_url: str, method: str, params: list[Any]) -> dict[str, Any]:
|
|
81
|
+
client = get_client()
|
|
82
|
+
gateway_mode = _is_gateway_url(rpc_url)
|
|
83
|
+
payload = {"jsonrpc": "2.0", "id": 1, "method": method, "params": params}
|
|
84
|
+
headers: dict[str, str] | None = None
|
|
85
|
+
|
|
86
|
+
if gateway_mode:
|
|
87
|
+
provider, network, gateway_url = _parse_gateway_url(rpc_url)
|
|
88
|
+
rpc_url = gateway_url
|
|
89
|
+
payload = {
|
|
90
|
+
"provider": provider,
|
|
91
|
+
"network": network,
|
|
92
|
+
"method": method,
|
|
93
|
+
"params": params,
|
|
94
|
+
}
|
|
95
|
+
bearer = settings.provider_gateway_bearer_token.strip()
|
|
96
|
+
if bearer:
|
|
97
|
+
headers = {"Authorization": f"Bearer {bearer}"}
|
|
98
|
+
|
|
99
|
+
last_exc: Exception | None = None
|
|
100
|
+
response: httpx.Response | None = None
|
|
101
|
+
for attempt in range(3):
|
|
102
|
+
try:
|
|
103
|
+
response = await client.post(rpc_url, json=payload, headers=headers)
|
|
104
|
+
if response.status_code == 429:
|
|
105
|
+
wait_seconds = max(_retry_after_seconds(response), 0.5 * (attempt + 1))
|
|
106
|
+
last_exc = ProviderError("solana-rpc", f"Rate limited on {rpc_url}")
|
|
107
|
+
if attempt == 2:
|
|
108
|
+
raise last_exc
|
|
109
|
+
await asyncio.sleep(wait_seconds)
|
|
110
|
+
continue
|
|
111
|
+
if response.status_code in {403, 500, 502, 503, 504}:
|
|
112
|
+
last_exc = ProviderError("solana-rpc", f"HTTP {response.status_code} on {rpc_url}")
|
|
113
|
+
if attempt == 2:
|
|
114
|
+
raise last_exc
|
|
115
|
+
await asyncio.sleep(0.5 * (attempt + 1))
|
|
116
|
+
continue
|
|
117
|
+
break
|
|
118
|
+
except (httpx.TimeoutException, httpx.ConnectError) as exc:
|
|
119
|
+
last_exc = exc
|
|
120
|
+
if attempt == 2:
|
|
121
|
+
raise ProviderError("solana-rpc", f"Network error on {rpc_url}: {exc}") from exc
|
|
122
|
+
await asyncio.sleep(0.5 * (attempt + 1))
|
|
123
|
+
if response is None:
|
|
124
|
+
raise ProviderError("solana-rpc", f"RPC request failed on {rpc_url}: {last_exc}")
|
|
125
|
+
if response.status_code == 429:
|
|
126
|
+
raise ProviderError("solana-rpc", f"Rate limited on {rpc_url}")
|
|
127
|
+
if response.status_code != 200:
|
|
128
|
+
raise ProviderError("solana-rpc", f"HTTP {response.status_code} on {rpc_url}")
|
|
129
|
+
data = response.json()
|
|
130
|
+
if gateway_mode:
|
|
131
|
+
if not isinstance(data, dict):
|
|
132
|
+
raise ProviderError("solana-rpc", "Provider gateway returned unexpected response shape.")
|
|
133
|
+
if not data.get("ok", False):
|
|
134
|
+
raise ProviderError(
|
|
135
|
+
"solana-rpc",
|
|
136
|
+
f"Provider gateway error: {data.get('error') or data}",
|
|
137
|
+
)
|
|
138
|
+
data = data.get("rpc")
|
|
139
|
+
if not isinstance(data, dict):
|
|
140
|
+
raise ProviderError("solana-rpc", "Provider gateway rpc payload is missing.")
|
|
141
|
+
if "error" in data:
|
|
142
|
+
raise ProviderError("solana-rpc", f"RPC error: {data['error']}")
|
|
143
|
+
return data
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
async def rpc_call(
|
|
147
|
+
method: str,
|
|
148
|
+
params: list[Any],
|
|
149
|
+
rpc_url: str | list[str],
|
|
150
|
+
) -> dict[str, Any]:
|
|
151
|
+
"""Execute a Solana RPC call with ordered failover across configured endpoints."""
|
|
152
|
+
candidates = _normalize_rpc_urls(rpc_url)
|
|
153
|
+
errors: list[str] = []
|
|
154
|
+
for index, candidate in enumerate(candidates):
|
|
155
|
+
try:
|
|
156
|
+
return await _do_rpc_call(candidate, method, params)
|
|
157
|
+
except Exception as exc:
|
|
158
|
+
errors.append(f"{candidate}: {exc}")
|
|
159
|
+
if index < len(candidates) - 1:
|
|
160
|
+
log.warning("Solana RPC failed on %s: %s -- trying next endpoint", candidate, exc)
|
|
161
|
+
continue
|
|
162
|
+
raise ProviderError(
|
|
163
|
+
"solana-rpc",
|
|
164
|
+
"All Solana RPC endpoints failed: " + " | ".join(errors),
|
|
165
|
+
) from exc
|
|
166
|
+
raise ProviderError("solana-rpc", "No Solana RPC endpoints are configured.")
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
async def fetch_balance(
|
|
170
|
+
address: str,
|
|
171
|
+
rpc_url: str,
|
|
172
|
+
commitment: str = "confirmed",
|
|
173
|
+
) -> dict[str, Any]:
|
|
174
|
+
"""Fetch native SOL balance for a wallet."""
|
|
175
|
+
data = await rpc_call(
|
|
176
|
+
"getBalance",
|
|
177
|
+
[address, {"commitment": commitment}],
|
|
178
|
+
rpc_url=rpc_url,
|
|
179
|
+
)
|
|
180
|
+
lamports = data.get("result", {}).get("value", 0)
|
|
181
|
+
return {
|
|
182
|
+
"address": address,
|
|
183
|
+
"chain": "solana",
|
|
184
|
+
"balance_native": lamports / LAMPORTS_PER_SOL,
|
|
185
|
+
"balance_usd": None,
|
|
186
|
+
"source": "solana-rpc",
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
async def account_exists(address: str, rpc_url: str) -> bool:
|
|
191
|
+
"""Return whether an on-chain account exists."""
|
|
192
|
+
data = await fetch_account_info(address, rpc_url=rpc_url)
|
|
193
|
+
return data is not None
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
async def fetch_account_info(
|
|
197
|
+
address: str,
|
|
198
|
+
rpc_url: str,
|
|
199
|
+
encoding: str = "jsonParsed",
|
|
200
|
+
) -> dict[str, Any] | None:
|
|
201
|
+
"""Fetch account info for any Solana account."""
|
|
202
|
+
data = await rpc_call(
|
|
203
|
+
"getAccountInfo",
|
|
204
|
+
[address, {"encoding": encoding}],
|
|
205
|
+
rpc_url=rpc_url,
|
|
206
|
+
)
|
|
207
|
+
return data.get("result", {}).get("value")
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
async def fetch_token_supply_info(mint: str, rpc_url: str) -> dict[str, Any]:
|
|
211
|
+
"""Fetch token supply metadata including decimals."""
|
|
212
|
+
data = await rpc_call(
|
|
213
|
+
"getTokenSupply",
|
|
214
|
+
[mint],
|
|
215
|
+
rpc_url=rpc_url,
|
|
216
|
+
)
|
|
217
|
+
value = data.get("result", {}).get("value", {})
|
|
218
|
+
return {
|
|
219
|
+
"mint": mint,
|
|
220
|
+
"amount": value.get("amount"),
|
|
221
|
+
"decimals": value.get("decimals"),
|
|
222
|
+
"ui_amount": value.get("uiAmount"),
|
|
223
|
+
"source": "solana-rpc",
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
async def fetch_token_account_balance(address: str, rpc_url: str) -> dict[str, Any]:
|
|
228
|
+
"""Fetch SPL token balance for a token account."""
|
|
229
|
+
data = await rpc_call(
|
|
230
|
+
"getTokenAccountBalance",
|
|
231
|
+
[address],
|
|
232
|
+
rpc_url=rpc_url,
|
|
233
|
+
)
|
|
234
|
+
value = data.get("result", {}).get("value", {})
|
|
235
|
+
return {
|
|
236
|
+
"amount": value.get("amount"),
|
|
237
|
+
"decimals": value.get("decimals"),
|
|
238
|
+
"ui_amount": value.get("uiAmount"),
|
|
239
|
+
"source": "solana-rpc",
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
async def fetch_token_accounts_by_owner(
|
|
244
|
+
owner: str,
|
|
245
|
+
rpc_url: str,
|
|
246
|
+
token_program_id: str = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
|
|
247
|
+
) -> list[dict[str, Any]]:
|
|
248
|
+
"""Fetch parsed SPL token accounts for a wallet owner."""
|
|
249
|
+
data = await rpc_call(
|
|
250
|
+
"getTokenAccountsByOwner",
|
|
251
|
+
[
|
|
252
|
+
owner,
|
|
253
|
+
{"programId": token_program_id},
|
|
254
|
+
{"encoding": "jsonParsed"},
|
|
255
|
+
],
|
|
256
|
+
rpc_url=rpc_url,
|
|
257
|
+
)
|
|
258
|
+
return data.get("result", {}).get("value", []) or []
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
async def fetch_latest_blockhash(rpc_url: str, commitment: str = "confirmed") -> dict[str, Any]:
|
|
262
|
+
"""Fetch latest blockhash for transaction building."""
|
|
263
|
+
data = await rpc_call(
|
|
264
|
+
"getLatestBlockhash",
|
|
265
|
+
[{"commitment": commitment}],
|
|
266
|
+
rpc_url=rpc_url,
|
|
267
|
+
)
|
|
268
|
+
value = data.get("result", {}).get("value", {})
|
|
269
|
+
return {
|
|
270
|
+
"blockhash": value.get("blockhash"),
|
|
271
|
+
"last_valid_block_height": value.get("lastValidBlockHeight"),
|
|
272
|
+
"source": "solana-rpc",
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
async def fetch_recent_prioritization_fees(
|
|
277
|
+
rpc_url: str,
|
|
278
|
+
writable_accounts: list[str] | None = None,
|
|
279
|
+
) -> dict[str, Any]:
|
|
280
|
+
"""Fetch prioritization fee samples for future tx construction."""
|
|
281
|
+
params: list[Any] = [writable_accounts or []]
|
|
282
|
+
data = await rpc_call("getRecentPrioritizationFees", params, rpc_url=rpc_url)
|
|
283
|
+
fees = data.get("result", []) or []
|
|
284
|
+
return {
|
|
285
|
+
"samples": fees,
|
|
286
|
+
"recommended_micro_lamports": max(
|
|
287
|
+
(item.get("prioritizationFee", 0) for item in fees),
|
|
288
|
+
default=0,
|
|
289
|
+
),
|
|
290
|
+
"source": "solana-rpc",
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
async def fetch_minimum_balance_for_rent_exemption(
|
|
295
|
+
space: int,
|
|
296
|
+
rpc_url: str,
|
|
297
|
+
commitment: str = "confirmed",
|
|
298
|
+
) -> dict[str, Any]:
|
|
299
|
+
"""Fetch rent-exempt minimum lamports for an account size."""
|
|
300
|
+
data = await rpc_call(
|
|
301
|
+
"getMinimumBalanceForRentExemption",
|
|
302
|
+
[space, {"commitment": commitment}],
|
|
303
|
+
rpc_url=rpc_url,
|
|
304
|
+
)
|
|
305
|
+
value = int(data.get("result") or 0)
|
|
306
|
+
return {
|
|
307
|
+
"space": space,
|
|
308
|
+
"lamports": value,
|
|
309
|
+
"source": "solana-rpc",
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
async def fetch_vote_accounts(
|
|
314
|
+
rpc_url: str,
|
|
315
|
+
commitment: str = "confirmed",
|
|
316
|
+
) -> dict[str, Any]:
|
|
317
|
+
"""Fetch current and delinquent vote accounts."""
|
|
318
|
+
data = await rpc_call(
|
|
319
|
+
"getVoteAccounts",
|
|
320
|
+
[{"commitment": commitment}],
|
|
321
|
+
rpc_url=rpc_url,
|
|
322
|
+
)
|
|
323
|
+
value = data.get("result", {}) or {}
|
|
324
|
+
return {
|
|
325
|
+
"current": value.get("current", []) or [],
|
|
326
|
+
"delinquent": value.get("delinquent", []) or [],
|
|
327
|
+
"source": "solana-rpc",
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
async def fetch_stake_activation(
|
|
332
|
+
stake_account: str,
|
|
333
|
+
rpc_url: str,
|
|
334
|
+
commitment: str = "confirmed",
|
|
335
|
+
) -> dict[str, Any]:
|
|
336
|
+
"""Fetch activation status for a stake account."""
|
|
337
|
+
try:
|
|
338
|
+
data = await rpc_call(
|
|
339
|
+
"getStakeActivation",
|
|
340
|
+
[stake_account, {"commitment": commitment}],
|
|
341
|
+
rpc_url=rpc_url,
|
|
342
|
+
)
|
|
343
|
+
except ProviderError as exc:
|
|
344
|
+
if "Method not found" in str(exc):
|
|
345
|
+
return {
|
|
346
|
+
"state": "unknown",
|
|
347
|
+
"active": None,
|
|
348
|
+
"inactive": None,
|
|
349
|
+
"source": "solana-rpc",
|
|
350
|
+
}
|
|
351
|
+
raise
|
|
352
|
+
value = data.get("result", {}) or {}
|
|
353
|
+
return {
|
|
354
|
+
"state": value.get("state"),
|
|
355
|
+
"active": value.get("active"),
|
|
356
|
+
"inactive": value.get("inactive"),
|
|
357
|
+
"source": "solana-rpc",
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
async def send_transaction(
|
|
362
|
+
transaction_base64: str,
|
|
363
|
+
rpc_url: str,
|
|
364
|
+
skip_preflight: bool = False,
|
|
365
|
+
max_retries: int | None = None,
|
|
366
|
+
) -> dict[str, Any]:
|
|
367
|
+
"""Send a pre-signed transaction encoded as base64."""
|
|
368
|
+
config: dict[str, Any] = {
|
|
369
|
+
"encoding": "base64",
|
|
370
|
+
"skipPreflight": skip_preflight,
|
|
371
|
+
"preflightCommitment": "confirmed",
|
|
372
|
+
}
|
|
373
|
+
if max_retries is not None:
|
|
374
|
+
config["maxRetries"] = max_retries
|
|
375
|
+
|
|
376
|
+
data = await rpc_call(
|
|
377
|
+
"sendTransaction",
|
|
378
|
+
[transaction_base64, config],
|
|
379
|
+
rpc_url=rpc_url,
|
|
380
|
+
)
|
|
381
|
+
return {"signature": data.get("result"), "source": "solana-rpc"}
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
async def simulate_transaction(
|
|
385
|
+
transaction_base64: str,
|
|
386
|
+
rpc_url: str | list[str],
|
|
387
|
+
*,
|
|
388
|
+
commitment: str = "confirmed",
|
|
389
|
+
sig_verify: bool = True,
|
|
390
|
+
replace_recent_blockhash: bool = False,
|
|
391
|
+
) -> dict[str, Any]:
|
|
392
|
+
"""Simulate a signed transaction encoded as base64."""
|
|
393
|
+
config: dict[str, Any] = {
|
|
394
|
+
"encoding": "base64",
|
|
395
|
+
"commitment": commitment,
|
|
396
|
+
"sigVerify": sig_verify,
|
|
397
|
+
"replaceRecentBlockhash": replace_recent_blockhash,
|
|
398
|
+
}
|
|
399
|
+
if replace_recent_blockhash:
|
|
400
|
+
config["sigVerify"] = False
|
|
401
|
+
data = await rpc_call(
|
|
402
|
+
"simulateTransaction",
|
|
403
|
+
[transaction_base64, config],
|
|
404
|
+
rpc_url=rpc_url,
|
|
405
|
+
)
|
|
406
|
+
return {
|
|
407
|
+
"result": data.get("result"),
|
|
408
|
+
"value": (data.get("result") or {}).get("value"),
|
|
409
|
+
"source": "solana-rpc",
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
async def get_signature_status(
|
|
414
|
+
signature: str,
|
|
415
|
+
rpc_url: str,
|
|
416
|
+
search_transaction_history: bool = True,
|
|
417
|
+
) -> dict[str, Any] | None:
|
|
418
|
+
"""Fetch signature status for a submitted transaction."""
|
|
419
|
+
data = await rpc_call(
|
|
420
|
+
"getSignatureStatuses",
|
|
421
|
+
[[signature], {"searchTransactionHistory": search_transaction_history}],
|
|
422
|
+
rpc_url=rpc_url,
|
|
423
|
+
)
|
|
424
|
+
values = data.get("result", {}).get("value", [])
|
|
425
|
+
if not values:
|
|
426
|
+
return None
|
|
427
|
+
return values[0]
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
async def wait_for_confirmation(
|
|
431
|
+
signature: str,
|
|
432
|
+
rpc_url: str,
|
|
433
|
+
timeout_seconds: float = 60.0,
|
|
434
|
+
poll_interval_seconds: float = 1.0,
|
|
435
|
+
) -> dict[str, Any] | None:
|
|
436
|
+
"""Poll signature status until confirmed/finalized or timeout."""
|
|
437
|
+
deadline = time.monotonic() + timeout_seconds
|
|
438
|
+
while time.monotonic() < deadline:
|
|
439
|
+
status = await get_signature_status(signature, rpc_url=rpc_url)
|
|
440
|
+
if status is not None:
|
|
441
|
+
if status.get("err") is not None:
|
|
442
|
+
raise ProviderError("solana-rpc", f"Transaction failed: {status['err']}")
|
|
443
|
+
confirmation_status = status.get("confirmationStatus")
|
|
444
|
+
if confirmation_status in {"confirmed", "finalized"}:
|
|
445
|
+
return status
|
|
446
|
+
await asyncio.sleep(poll_interval_seconds)
|
|
447
|
+
return None
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"""Canonical tokenized-stock registry for EVM chains.
|
|
2
|
+
|
|
3
|
+
Base: Coinbase Tokenized Stocks (B20 tokens issued by Coinbase Onchain SPV Ltd),
|
|
4
|
+
listed by the official, keyless, paginated API at
|
|
5
|
+
https://api.coinbase.com/v1/tokenized-stocks (see
|
|
6
|
+
https://docs.base.org/base-chain/asset-issuance/tokenized-stocks-on-base).
|
|
7
|
+
|
|
8
|
+
Free-text DEX search is unreliable for stocks: the on-chain symbol carries an
|
|
9
|
+
issuer suffix ("TSLAc", not "TSLA"), DexScreener's search returns at most 30
|
|
10
|
+
pairs across *all* chains (so Base results are often cut before the chain
|
|
11
|
+
filter runs), and impersonators reuse tickers. Resolving through the issuer's
|
|
12
|
+
own registry by address avoids all three.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import re
|
|
18
|
+
import time
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
from agent_wallet.exceptions import ProviderError
|
|
22
|
+
from agent_wallet.http_client import get_client
|
|
23
|
+
|
|
24
|
+
COINBASE_TOKENIZED_STOCKS_URL = "https://api.coinbase.com/v1/tokenized-stocks"
|
|
25
|
+
COINBASE_ISSUER = "Coinbase Onchain SPV Ltd (Coinbase Tokenized Stocks)"
|
|
26
|
+
COINBASE_REGISTRY_SOURCE = "https://base.org/stocks"
|
|
27
|
+
COINBASE_SYMBOL_SUFFIX = "c"
|
|
28
|
+
|
|
29
|
+
SUPPORTED_NETWORKS = frozenset({"base"})
|
|
30
|
+
|
|
31
|
+
_CACHE_TTL_SECONDS = 3600
|
|
32
|
+
_MAX_PAGES = 20
|
|
33
|
+
_cache: dict[str, tuple[float, list[dict[str, Any]]]] = {}
|
|
34
|
+
|
|
35
|
+
_BASE_NOTICES = [
|
|
36
|
+
"Issued by Coinbase Onchain SPV Ltd under Regulation S: not available to U.S. persons; "
|
|
37
|
+
"the user is responsible for their own eligibility.",
|
|
38
|
+
"A token is an onchain certificate giving economic exposure to the share, not a direct "
|
|
39
|
+
"shareholding. One token does not permanently equal one share: the share-to-token "
|
|
40
|
+
"multiplier changes with reinvested dividends and corporate actions.",
|
|
41
|
+
"Secondary-market trading is permissionless, but issuer policies can block addresses "
|
|
42
|
+
"(e.g. sanctioned ones); a blocked transfer reverts, so rely on the swap simulation.",
|
|
43
|
+
"DEX prices can drift from the underlying stock outside U.S. market hours.",
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _normalize_ticker(value: str) -> str:
|
|
48
|
+
return re.sub(r"[^a-z0-9]", "", value.strip().lower())
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _clean_token(raw: dict[str, Any]) -> dict[str, Any] | None:
|
|
52
|
+
address = str(raw.get("contract_address") or "").strip()
|
|
53
|
+
symbol = str(raw.get("symbol") or "").strip()
|
|
54
|
+
if not re.fullmatch(r"0x[0-9a-fA-F]{40}", address) or not symbol:
|
|
55
|
+
return None
|
|
56
|
+
try:
|
|
57
|
+
decimals = int(raw.get("decimals"))
|
|
58
|
+
except (TypeError, ValueError):
|
|
59
|
+
decimals = None
|
|
60
|
+
multiplier = raw.get("multiplier")
|
|
61
|
+
underlying = symbol[: -len(COINBASE_SYMBOL_SUFFIX)] if symbol.endswith(COINBASE_SYMBOL_SUFFIX) else symbol
|
|
62
|
+
return {
|
|
63
|
+
"address": address,
|
|
64
|
+
"symbol": symbol,
|
|
65
|
+
"underlying_ticker": underlying,
|
|
66
|
+
"name": str(raw.get("name") or "").strip() or None,
|
|
67
|
+
"decimals": decimals,
|
|
68
|
+
"isin": str(raw.get("isin") or "").strip() or None,
|
|
69
|
+
"multiplier": multiplier if isinstance(multiplier, (int, float)) else None,
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
async def _fetch_coinbase_registry() -> list[dict[str, Any]]:
|
|
74
|
+
cached = _cache.get("base")
|
|
75
|
+
if cached is not None and time.monotonic() - cached[0] <= _CACHE_TTL_SECONDS:
|
|
76
|
+
return cached[1]
|
|
77
|
+
client = get_client()
|
|
78
|
+
tokens: list[dict[str, Any]] = []
|
|
79
|
+
page_token: str | None = None
|
|
80
|
+
for _ in range(_MAX_PAGES):
|
|
81
|
+
params = {"page_token": page_token} if page_token else None
|
|
82
|
+
try:
|
|
83
|
+
response = await client.get(COINBASE_TOKENIZED_STOCKS_URL, params=params)
|
|
84
|
+
except Exception as exc: # network errors
|
|
85
|
+
if cached is not None:
|
|
86
|
+
return cached[1]
|
|
87
|
+
raise ProviderError("coinbase-tokenized-stocks", f"Request failed: {exc}") from exc
|
|
88
|
+
if response.status_code != 200:
|
|
89
|
+
if cached is not None:
|
|
90
|
+
return cached[1]
|
|
91
|
+
raise ProviderError(
|
|
92
|
+
"coinbase-tokenized-stocks", f"HTTP {response.status_code}: {response.text[:300]}"
|
|
93
|
+
)
|
|
94
|
+
try:
|
|
95
|
+
data = response.json()
|
|
96
|
+
except ValueError as exc:
|
|
97
|
+
raise ProviderError("coinbase-tokenized-stocks", "Unexpected non-JSON response.") from exc
|
|
98
|
+
for raw in data.get("tokens") or []:
|
|
99
|
+
if isinstance(raw, dict):
|
|
100
|
+
token = _clean_token(raw)
|
|
101
|
+
if token is not None:
|
|
102
|
+
tokens.append(token)
|
|
103
|
+
page_token = str(data.get("next_page_token") or "").strip() or None
|
|
104
|
+
if not page_token:
|
|
105
|
+
break
|
|
106
|
+
if not tokens:
|
|
107
|
+
if cached is not None:
|
|
108
|
+
return cached[1]
|
|
109
|
+
raise ProviderError("coinbase-tokenized-stocks", "Registry returned no tokens.")
|
|
110
|
+
_cache["base"] = (time.monotonic(), tokens)
|
|
111
|
+
return tokens
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _score(token: dict[str, Any], query: str) -> int:
|
|
115
|
+
"""Higher is better; 0 means no match."""
|
|
116
|
+
q = _normalize_ticker(query)
|
|
117
|
+
if not q:
|
|
118
|
+
return 0
|
|
119
|
+
if token["address"].lower() == query.strip().lower():
|
|
120
|
+
return 100
|
|
121
|
+
symbol = _normalize_ticker(token["symbol"])
|
|
122
|
+
underlying = _normalize_ticker(token["underlying_ticker"])
|
|
123
|
+
if q in {symbol, underlying} or (token.get("isin") and q == _normalize_ticker(token["isin"])):
|
|
124
|
+
return 90
|
|
125
|
+
name = (token.get("name") or "").lower()
|
|
126
|
+
name_key = _normalize_ticker(name)
|
|
127
|
+
words = [_normalize_ticker(word) for word in re.split(r"[\s,.]+", name) if word]
|
|
128
|
+
if q == name_key or (words and q == words[0]):
|
|
129
|
+
return 70
|
|
130
|
+
if len(q) >= 3 and (name_key.startswith(q) or q in words):
|
|
131
|
+
return 50
|
|
132
|
+
if len(q) >= 4 and q in name_key:
|
|
133
|
+
return 30
|
|
134
|
+
return 0
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def is_supported_network(network: str | None) -> bool:
|
|
138
|
+
return str(network or "").strip().lower() in SUPPORTED_NETWORKS
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
async def find_tokenized_stocks(
|
|
142
|
+
query: str,
|
|
143
|
+
*,
|
|
144
|
+
network: str = "base",
|
|
145
|
+
limit: int = 5,
|
|
146
|
+
) -> dict[str, Any]:
|
|
147
|
+
"""Resolve a ticker, company name, ISIN or address to canonical tokenized stocks."""
|
|
148
|
+
network = str(network or "").strip().lower()
|
|
149
|
+
query = str(query or "").strip()
|
|
150
|
+
if not query:
|
|
151
|
+
raise ProviderError("tokenized-stocks", "query must not be empty.")
|
|
152
|
+
if network not in SUPPORTED_NETWORKS:
|
|
153
|
+
raise ProviderError(
|
|
154
|
+
"tokenized-stocks",
|
|
155
|
+
f"No canonical tokenized-stock registry is wired for network '{network}'. "
|
|
156
|
+
"Supported: base (Coinbase Tokenized Stocks). For robinhood, verify the address "
|
|
157
|
+
"against docs.robinhood.com/chain/contracts.",
|
|
158
|
+
)
|
|
159
|
+
registry = await _fetch_coinbase_registry()
|
|
160
|
+
scored = [(score, token) for token in registry if (score := _score(token, query)) > 0]
|
|
161
|
+
scored.sort(key=lambda item: (-item[0], item[1]["symbol"]))
|
|
162
|
+
bounded = max(1, min(int(limit or 5), 20))
|
|
163
|
+
# A unique company-name match ("Tesla") is as unambiguous as a ticker match.
|
|
164
|
+
unique_name_match = sum(1 for score, _ in scored if score >= 70) == 1
|
|
165
|
+
matches = [
|
|
166
|
+
{
|
|
167
|
+
**token,
|
|
168
|
+
"match_score": score,
|
|
169
|
+
"exact_match": score >= 90 or (score >= 70 and unique_name_match),
|
|
170
|
+
}
|
|
171
|
+
for score, token in scored[:bounded]
|
|
172
|
+
]
|
|
173
|
+
return {
|
|
174
|
+
"network": network,
|
|
175
|
+
"query": query,
|
|
176
|
+
"issuer": COINBASE_ISSUER,
|
|
177
|
+
"registry_source": COINBASE_REGISTRY_SOURCE,
|
|
178
|
+
"registry_size": len(registry),
|
|
179
|
+
"count": len(matches),
|
|
180
|
+
"matches": matches,
|
|
181
|
+
"notices": list(_BASE_NOTICES),
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
async def canonical_address_set(network: str) -> set[str]:
|
|
186
|
+
if not is_supported_network(network):
|
|
187
|
+
return set()
|
|
188
|
+
registry = await _fetch_coinbase_registry()
|
|
189
|
+
return {token["address"].lower() for token in registry}
|