Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,19 +110,16 @@ gh pr merge <pr#> --squash --delete-branch
- **Schema-first**: 服务开发必须先定义 `types.ts`。

<!-- OPENSPEC:START -->

# OpenSpec Instructions

These instructions are for AI assistants working in this project.

Always open `@/openspec/AGENTS.md` when the request:

- Mentions planning or proposals (words like proposal, spec, change, plan)
- Introduces new capabilities, breaking changes, architecture shifts, or big performance/security work
- Sounds ambiguous and you need the authoritative spec before coding

Use `@/openspec/AGENTS.md` to learn:

- How to create and apply change proposals
- Spec format and conventions
- Project structure and guidelines
Expand Down
3 changes: 0 additions & 3 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,19 +65,16 @@ rm -rf .turbo && pnpm typecheck
---

<!-- OPENSPEC:START -->

# OpenSpec Instructions

These instructions are for AI assistants working in this project.

Always open `@/openspec/AGENTS.md` when the request:

- Mentions planning or proposals (words like proposal, spec, change, plan)
- Introduces new capabilities, breaking changes, architecture shifts, or big performance/security work
- Sounds ambiguous and you need the authoritative spec before coding

Use `@/openspec/AGENTS.md` to learn:

- How to create and apply change proposals
- Spec format and conventions
- Project structure and guidelines
Expand Down
64 changes: 64 additions & 0 deletions docs/white-book/02-Driver-Ref/02-EVM/03-Wallet-Provider.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# EVM Wallet Provider (ethwallet / bscwallet)

> **Code Source**:
> - `src/services/chain-adapter/providers/ethwallet-provider.effect.ts`
> - `src/services/chain-adapter/providers/bscwallet-provider.effect.ts`

## Overview

`ethwallet-v1` 与 `bscwallet-v1` 是基于 walletapi 的 EVM Indexer Provider。
它们负责:

- **交易列表**:原生交易 + 代币交易混合输出
- **余额/资产**:依赖交易列表变化触发刷新,减少无效请求
- **缓存策略**:使用 `httpFetchCached` 的 TTL 策略避免重复请求

## API Endpoints (walletapi)

### Ethereum (`ethwallet-v1`)

- 交易列表(原生):`/wallet/eth/trans/normal/history`
- 交易列表(ERC20):`/wallet/eth/trans/erc20/history`
- 余额(原生):`/wallet/eth/balance`
- 余额(代币):`/wallet/eth/account/balance/v2`
- 代币列表:`/wallet/eth/contract/tokens`

### BSC (`bscwallet-v1`)

- 交易列表(原生):`/wallet/bsc/trans/normal/history`
- 交易列表(BEP20):`/wallet/bsc/trans/bep20/history`
- 余额(原生):`/wallet/bsc/balance`
- 余额(代币):`/wallet/bsc/account/balance/v2`
- 代币列表:`/wallet/bsc/contract/tokens`

## Behavior Notes

1. **交易列表混合**
原生/代币交易各自独立轮询,每个 contract 变化都会触发合并输出,避免等待全量返回。

2. **余额刷新策略**
余额请求仅在交易列表发生变化时触发;通过 TTL 复用缓存减少重复请求。

3. **异常处理**
`success: true + message: NOTOK` 会触发错误路径,避免缓存无效结果;
`No transactions found` 视为正常空结果。

## Configuration

在 `public/configs/default-chains.json` 中配置:

```json
{
"type": "ethwallet-v1",
"endpoint": "https://walletapi.bfmeta.info/wallet/eth"
}
```

或:

```json
{
"type": "bscwallet-v1",
"endpoint": "https://walletapi.bfmeta.info/wallet/bsc"
}
```
58 changes: 35 additions & 23 deletions docs/white-book/02-Driver-Ref/03-UTXO/01-BTC-Provider.md
Original file line number Diff line number Diff line change
@@ -1,47 +1,58 @@
# Bitcoin Provider (UTXO)

> **Code Source**: [`src/services/chain-adapter/providers/btcwallet-provider.ts`](https://github.com/BioforestChain/KeyApp/blob/main/src/services/chain-adapter/providers/btcwallet-provider.ts)
> **Code Source**: `src/services/chain-adapter/providers/btcwallet-provider.effect.ts`

## Overview

The `BtcWalletProvider` implements the `ApiProvider` interface for Bitcoin-like UTXO chains. It relies on a Blockbook-compatible backend API (btcwallet) to fetch balances and transaction history.
The `BtcWalletProviderEffect` implements the `ApiProvider` interface for Bitcoin-like UTXO chains. It relies on a Blockbook-compatible backend API (btcwallet) to fetch balances, transaction history, and single-transaction detail. It also uses Blockbook endpoints for fee estimation, UTXO collection, and raw-transaction broadcast.

## Architecture

```mermaid
graph TD
A[ChainProvider] --> B[BtcWalletProvider]
B --> C[Blockbook API]
A[ChainProvider] --> B[BtcWalletProviderEffect]
B --> C[btcwallet-v1 (Blockbook Proxy)]
C --> D[Bitcoin Node]
```

## Implementation Details

### Class Structure

- **Class**: `BtcWalletProvider`
- **Class**: `BtcWalletProviderEffect`
- **Implements**: `ApiProvider`
- **Location**: [`src/services/chain-adapter/providers/btcwallet-provider.ts`](https://github.com/BioforestChain/KeyApp/blob/main/src/services/chain-adapter/providers/btcwallet-provider.ts)
- **Location**: `src/services/chain-adapter/providers/btcwallet-provider.effect.ts`

### Key Features

1. **Native Balance**:
- Fetches balance via `/api/v2/address/{address}`.
- Combines `balance` (confirmed) and `unconfirmedBalance`.
- Caching: 60 seconds.
- Fetches address info via `/api/v2/address/{address}?details=txs`.
- Balance derived from Blockbook `balance` field.
- Cache: TTL 5s (browser cache).

2. **Transaction History**:
- Fetches history via `/api/v2/address/{address}?details=txs`.
- Parses inputs (`vin`) and outputs (`vout`) to determine direction and net value.
- Supports pagination (limit).
- Caching: 5 minutes.
- Uses the same address info endpoint (`details=txs`) and maps `vin/vout`.
- Cache: TTL 5s (browser cache).

3. **Single Transaction Detail**:
- Fetches `/api/v2/tx/{txid}` and maps to standard `TransactionOutput`.
- Cache: TTL 5s (browser cache).

4. **Fee Estimate / UTXO / Broadcast**:
- Fee estimate: `/api/v2/estimatefee/{blocks}`
- UTXO list: `/api/v2/utxo/{address}`
- Broadcast raw tx: `/api/v2/sendtx/{hex}`

### Data Models

#### Blockbook Response Schemas
#### Blockbook Response Schemas (Proxy)

- `BlockbookAddressInfoSchema`: Contains balance and transaction list.
- `BlockbookTxSchema`: Detailed transaction info (inputs, outputs, block height).
btcwallet 使用 Blockbook 代理,所有请求通过 walletapi POST 代理执行:

```ts
POST /wallet/btc/blockbook
body: { url: "/api/v2/address/{address}", method: "GET" }
```

#### Logic: Direction & Value

Expand All @@ -63,12 +74,14 @@ const net = outSum - inSum
- **Endpoint**: URL of the Blockbook API (e.g., `https://btc.bioforest.io`).
- **Chain ID**: Passed during initialization to fetch symbol and decimals.

## Caching Strategy
## Caching Strategy (httpFetchCached)

| Data | TTL | Invalidation Tags |
|------|-----|-------------------|
| Balance | 60s | `balance:{chainId}:{address}` |
| History | 5m | `txhistory:{chainId}:{address}` |
| Data | Strategy | TTL |
|------|----------|-----|
| Address Info / History | ttl | 5s |
| Transaction Detail | ttl | 5s |
| UTXO | ttl | 15s |
| Estimate Fee | ttl | 30s |

## Error Handling

Expand All @@ -78,5 +91,4 @@ const net = outSum - inSum
## Future Improvements

- [ ] Support for XPUB derived addresses.
- [ ] Fee estimation via Blockbook.
- [ ] Raw transaction broadcasting.
- [ ] Enhanced fee strategy (multi-target).
50 changes: 30 additions & 20 deletions docs/white-book/02-Driver-Ref/04-TVM/01-Tron-Provider.md
Original file line number Diff line number Diff line change
@@ -1,42 +1,51 @@
# Tron Provider (TVM)

> **Code Source**: [`src/services/chain-adapter/providers/tronwallet-provider.ts`](https://github.com/BioforestChain/KeyApp/blob/main/src/services/chain-adapter/providers/tronwallet-provider.ts)
> **Code Source**: `src/services/chain-adapter/providers/tronwallet-provider.effect.ts`
> **API Spec**: `docs/white-book/99-Appendix/05-API-Providers.md#波场-api`

## Overview

The `TronWalletProvider` implements the `ApiProvider` interface for the Tron blockchain. It interacts with a TronGrid-compatible API to handle native (TRX) and TRC20 token operations.
The `TronWalletProviderEffect` implements the `ApiProvider` interface for the Tron blockchain. It interacts with `tronwallet-v1` (walletapi.bfmeta) to handle native (TRX) and TRC20 token operations.

## Architecture

```mermaid
graph TD
A[ChainProvider] --> B[TronWalletProvider]
B --> C[TronGrid API]
B --> C[TronWallet API]
C --> D[Tron Node]
```

## Implementation Details

### Class Structure

- **Class**: `TronWalletProvider`
- **Class**: `TronWalletProviderEffect`
- **Implements**: `ApiProvider`
- **Location**: [`src/services/chain-adapter/providers/tronwallet-provider.ts`](https://github.com/BioforestChain/KeyApp/blob/main/src/services/chain-adapter/providers/tronwallet-provider.ts)
- **Location**: `src/services/chain-adapter/providers/tronwallet-provider.effect.ts`

### Key Features

1. **Native Balance**:
- Fetches TRX balance via `/balance`.
- Supports both Base58 and Hex address formats.
- Caching: 60 seconds.
- Fetches TRX balance via `/wallet/tron/balance`.
- Supports Base58 + Hex address conversion.
- Caching handled by `httpFetchCached`.

2. **Transaction History**:
- Aggregates data from two endpoints:
- Native: `/trans/common/history`
- TRC20: `/trans/trc20/history`
- Native: `/wallet/tron/trans/common/history`
- TRC20: `/wallet/tron/trans/trc20/history`
- Merges and sorts transactions by timestamp.
- Deduplicates native transactions triggered by TRC20 transfers.
- Caching: 5 minutes.

3. **Token Balances (Local Mix)**:
- Uses `/wallet/tron/contract/tokens` to obtain TRC20 contract list (TTL cache).
- Batches balances via `/wallet/tron/account/balance/v2` with `contracts[]`.
- Mixes native + TRC20 balances into a single output list.

4. **Create & Broadcast**:
- Native transfer uses `/wallet/tron/trans/create` + `/wallet/tron/trans/broadcast`
- TRC20 transfer uses `/wallet/tron/trans/contract` + `/wallet/tron/trans/trc20/broadcast`

### Address Handling

Expand All @@ -46,8 +55,8 @@ Tron uses a dual-format address system. The provider includes utilities for conv
- **Hex**: Internal format used by the API (starts with `41...`).

Utilities:
- `tronBase58ToHex(address)`: Converts Base58 to Hex.
- `toTronBase58Address(address)`: Ensures Base58 format for UI display.
- `tronAddressToHex(address)`: Converts Base58 to Hex.
- `tronHexToAddress(address)`: Converts Hex to Base58.

### Data Models

Expand All @@ -71,20 +80,21 @@ TRC20 transfers often generate a corresponding native transaction record. The pr
## Configuration

- **Type**: `tronwallet-v1`
- **Endpoint**: URL of the Tron API proxy.
- **Endpoint**: URL of the TronWallet API proxy.
- **Chain ID**: Passed during initialization.

## Caching Strategy

| Data | TTL | Invalidation Tags |
|------|-----|-------------------|
| Balance | 60s | `balance:{chainId}:{address}` |
| History | 5m | `txhistory:{chainId}:{address}` |
Caching is controlled by `httpFetchCached` and depends on source usage and `forceRefresh`.

## Error Handling

- **Zod Validation**: Ensures API responses match expected schemas.
- **Upstream Errors**: Throws `Upstream API error` if the API reports failure.
- **Schema Validation**: Ensures API responses match expected schemas.
- **Upstream Errors**: Non-2xx responses throw `HttpError`.

## Reference

- Legacy service: `/Users/kzf/Dev/bioforestChain/legacy-apps/libs/wallet-base/services/wallet/tron/tron.service.ts`

## Future Improvements

Expand Down
5 changes: 3 additions & 2 deletions docs/white-book/02-Driver-Ref/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
* **02-EVM (以太坊生态)**
* [01-RPC-Provider.md](./02-EVM/01-RPC-Provider.md) - JSON-RPC 实现
* [02-Etherscan-Provider.md](./02-EVM/02-Etherscan-Provider.md) - Etherscan 实现
* [03-Wallet-Provider.md](./02-EVM/03-Wallet-Provider.md) - walletapi (ethwallet/bscwallet)
* **03-UTXO (比特币生态)**
* [01-BTC-Provider.md](./03-UTXO/01-BTC-Provider.md) - Mempool.space 实现
* [01-BTC-Provider.md](./03-UTXO/01-BTC-Provider.md) - btcwallet (Blockbook) 实现
* **04-TVM (波场生态)**
* [01-Tron-Provider.md](./04-TVM/01-Tron-Provider.md) - TronGrid 实现
* [01-Tron-Provider.md](./04-TVM/01-Tron-Provider.md) - tronwallet 实现
32 changes: 29 additions & 3 deletions docs/white-book/99-Appendix/05-API-Providers.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,13 @@ interface ApiResponse<T> {
| POST | `/wallet/eth/account/balance/v2` | 批量查余额 |
| GET | `/wallet/eth/getChainId` | 获取 chainId |

### 关键约定

- `/wallet/{eth|bsc}/balance` 为 **GET** 请求,使用查询参数 `address`。
- `/wallet/{eth|bsc}/trans/erc20/history` 与 `/wallet/bsc/trans/bep20/history` **必须**携带 `contractaddress`,否则可能返回 `success:false`。
- 交易历史返回结构为 `{ success, result: { status, message, result: [] } }`,当 `status !== "1"` 或 `message === "NOTOK"` 视为上游失败,需要触发 fallback 并禁止缓存。
- `/wallet/{eth|bsc}/account/balance/v2` 返回 `{ success, result: [...] }`。

---

## 比特币 API
Expand All @@ -126,7 +133,7 @@ interface ApiResponse<T> {

**特点**:
- UTXO 模型
- 代理 blockbook API
- 代理 blockbook API(POST 方式转发)
- 本地 PSBT 签名

### API 端点
Expand All @@ -151,6 +158,7 @@ interface ApiResponse<T> {
- 使用 tronweb
- 地址有 hex/base58 转换
- TRC20 合约
- **参考实现**: `/Users/kzf/Dev/bioforestChain/legacy-apps/libs/wallet-base/services/wallet/tron/tron.service.ts`

### API 端点

Expand All @@ -165,12 +173,30 @@ interface ApiResponse<T> {
| POST | `/wallet/tron/trans/broadcast` | 广播 TRX 交易 |
| POST | `/wallet/tron/trans/trc20/broadcast` | 广播 TRC20 交易 |
| POST | `/wallet/tron/trans/common/history` | TRX 交易历史 |
| POST | `/wallet/tron/trans/trc20/history` | TRC20 交易历史 |
| POST | `/wallet/tron/trans/trc20/history` | TRC20 交易历史(需要 `contract_address`) |
| POST | `/wallet/tron/trans/pending` | pending 交易 |
| POST | `/wallet/tron/trans/receipt` | 交易回执 |
| POST | `/wallet/tron/contract/tokens` | 代币列表 |
| POST | `/wallet/tron/contract/token/detail` | 代币详情 |
| POST | `/wallet/tron/account/balance/v2` | 批量查余额 |
| POST | `/wallet/tron/account/balance/v2` | 批量查余额(`contracts` 必填数组) |

### 请求/响应约定 (TronWallet)

- **地址格式**:
- `trans/*/history`, `trans/pending`: `address` 使用 Hex(`41...`)
- `account/balance/v2`: `address` 使用 Base58 (T-address)
- **/wallet/tron/balance**
- HTTP 方法: `GET` (query 参数 `address`)
- 响应常见为字符串或数字 (TRX in SUN)
- 兼容返回 `{ success, result }` 结构
- **/wallet/tron/account/balance/v2**
- `contracts` 必填,必须是数组;省略会返回 `success:false` / 400
- 返回 TRC20 余额列表 (数组或 `{ success, result }`)
- **/wallet/tron/trans/trc20/history**
- 需要 `contract_address`,否则返回 `success:false` / PARAMETER ERROR
- **/wallet/tron/contract/tokens**
- 返回 `{ success, result }` 包裹结构
- `result.data[].address` 为 Hex 地址,使用前需转 Base58

### TronGrid API Key

Expand Down
13 changes: 13 additions & 0 deletions openspec/changes/update-provider-tx-sync/proposal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Change: Align providers with biowallet pendingTx/txHistory sync

## Why
Pending transaction confirmations currently trigger txHistory refresh only for biowallet because other providers use isolated event buses. This causes stale transaction history and pending list mismatches across chains.

## What Changes
- Use the shared wallet event bus for all providers that register walletEvents.
- Ensure transactionHistory sources for every provider react to tx:confirmed/tx:sent events.
- Keep biowallet behavior as the benchmark for sync semantics.

## Impact
- Affected specs: sync-transactions (new)
- Affected code: provider effect files using walletEvents, shared wallet-event-bus usage
Loading