Metadata-Version: 2.4
Name: barter-sdk
Version: 1.0.2
Summary: Proof of Trade Protocol — Python SDK for BTR-Trust soulbound reputation
Author: TheBarmaEffect
License: MIT
Project-URL: Homepage, https://github.com/TheBarmaEffect/barter-protocol
Project-URL: Repository, https://github.com/TheBarmaEffect/barter-protocol
Project-URL: Documentation, https://github.com/TheBarmaEffect/barter-protocol/blob/main/sdk-python/README.md
Project-URL: Bug Tracker, https://github.com/TheBarmaEffect/barter-protocol/issues
Project-URL: Changelog, https://github.com/TheBarmaEffect/barter-protocol/blob/main/sdk-python/README.md#changelog
Project-URL: PyPI, https://pypi.org/project/barter-sdk/
Keywords: barter,bitcoin,lightning,trust,reputation,web3
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: web3>=6.0.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: python-dotenv>=1.0.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov; extra == "dev"
Requires-Dist: pytest-asyncio; extra == "dev"
Dynamic: license-file

<p align="center">
  <code>[ B A R T E R ]</code>
  <br />
  <strong>barter-sdk</strong> — Python SDK for the Proof of Trade Protocol
</p>

<p align="center">
  <a href="https://pypi.org/project/barter-sdk/"><img src="https://img.shields.io/pypi/v/barter-sdk.svg" alt="PyPI version"></a>
  <a href="https://pypi.org/project/barter-sdk/"><img src="https://img.shields.io/pypi/pyversions/barter-sdk.svg" alt="Python versions"></a>
  <a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-blue.svg" alt="License: MIT"></a>
  <a href="https://pypi.org/project/barter-sdk/"><img src="https://img.shields.io/pypi/dm/barter-sdk.svg" alt="Downloads"></a>
</p>

---

## What is Barter?

Credit scores exist for fiat. **Barter builds the equivalent for crypto wallets** — but instead of trusting a central authority, every score point comes from a real, cryptographically verified trade settled on the **Bitcoin Lightning Network**.

When two parties complete a trade, the Lightning payment reveals a SHA256 preimage. That preimage is submitted on-chain as irrefutable proof. The smart contract verifies it, updates both parties' **soulbound trust scores**, and mints **BTR-Credit** reward tokens. No fake reviews, no self-attestation, no gaming — just math and commerce.

**This SDK lets you read trust scores, execute trades, check compliance flags, and build applications on top of Barter — all in Python.**

---

## Install

```bash
pip install barter-sdk
```

That's it. Python 3.8+ required.

---

## Try It in 30 Seconds

```python
import btr

# Connect to the protocol (read-only, no keys needed)
client = btr.BarterClient(network="sepolia")

# Look up any wallet's trust score
score = client.trust.get_score("0x742d35Cc6634C0532925a3b844Bc9e7595f3F9a0")
print(f"Trust score: {score}")

# Get full trust profile
profile = client.trust.get_profile("0x742d35Cc6634C0532925a3b844Bc9e7595f3F9a0")
print(f"Score: {profile.score}")
print(f"Trades completed: {profile.trade_count}")
print(f"Unique counterparties: {profile.unique_counterparties}")
print(f"Completion rate: {profile.completion_rate}%")

# Run compliance analysis — detect wash trading, velocity anomalies, isolation
report = client.compliance.full_report("0x742d35Cc6634C0532925a3b844Bc9e7595f3F9a0")
print(f"Risk level: {report.risk_level}")
print(f"Flags: {report.flags}")
print(f"24h velocity: {report.velocity.trades_24h} trades")
print(f"Network isolation: {report.cluster.isolation_score}")
```

**Output:**
```
Trust score: 347
Score: 347
Trades completed: 18
Unique counterparties: 12
Completion rate: 94.2%
Risk level: low
Flags: []
24h velocity: 0 trades
Network isolation: 0.0
```

---

## Use Cases

### 1. Marketplace trust gating

Gate access to high-value listings based on seller reputation:

```python
import btr

client = btr.BarterClient()

def can_list_premium(seller_address: str) -> bool:
    """Only allow sellers with score >= 200 and 5+ counterparties."""
    profile = client.trust.get_profile(seller_address)
    return profile.score >= 200 and profile.unique_counterparties >= 5

# Check before allowing a listing
if can_list_premium("0xSellerAddress..."):
    print("Approved for premium listings")
else:
    print("Build more trade history first")
```

### 2. Counterparty screening before settlement

Screen a counterparty for anomalies before agreeing to trade:

```python
import btr

client = btr.BarterClient()

def screen_counterparty(address: str) -> dict:
    """Run full compliance check before accepting a trade."""
    report = client.compliance.full_report(address)

    return {
        "address": address,
        "risk_level": report.risk_level,
        "flags": [str(f) for f in report.flags],
        "velocity_elevated": report.velocity.is_elevated,
        "isolation_score": report.cluster.isolation_score,
        "recommendation": "BLOCK" if report.risk_level == "high" else "PROCEED",
    }

result = screen_counterparty("0xSuspiciousWallet...")
print(result)
# {'address': '0x...', 'risk_level': 'high', 'flags': ['High velocity: 11 tx/day',
#  'Isolated: only 2 counterparties'], 'recommendation': 'BLOCK'}
```

### 3. Execute a full trade lifecycle

Propose, accept, and settle a trade — end to end:

```python
import os
import btr

# Write operations need a private key
client = btr.BarterClient(
    rpc_url=os.environ["ALCHEMY_RPC_URL"],
    private_key=os.environ["DEPLOYER_PRIVATE_KEY"],
)

# Step 1: Propose a trade with a Lightning payment hash
trade_id = client.trade.propose(
    counterparty="0xCounterpartyAddress...",
    payment_hash="0xabc123...def456",  # SHA256 hash of the Lightning preimage
    amount_sats=50_000,
    category="digital-goods",
    description="Logo design commission",
)
print(f"Trade proposed: {trade_id}")

# Step 2: Counterparty accepts the trade
receipt = client.trade.accept(trade_id)
print(f"Accepted in block {receipt['blockNumber']}")

# Step 3: After Lightning payment settles, submit the preimage
receipt = client.trade.settle(trade_id, preimage="0xdeadbeef...")
print(f"Settled in block {receipt['blockNumber']}")
# Both parties' BTR-Trust scores increase, BTR-Credit tokens minted
```

### 4. Analytics dashboard — trade network visualization

```python
import btr

client = btr.BarterClient()

def wallet_summary(address: str) -> dict:
    """Build a dashboard-ready summary for any wallet."""
    profile = client.trust.get_profile(address)
    compliance = client.compliance.full_report(address)
    credit = client.credit.balance_of(address)
    trades = client.trade.list_by_address(address)

    return {
        "address": address,
        "score": profile.score,
        "level": "A" if profile.score >= 700 else "B" if profile.score >= 400 else "C",
        "trades": len(trades),
        "completion_rate": f"{profile.completion_rate}%",
        "counterparties": profile.unique_counterparties,
        "btr_credit": credit,
        "risk": compliance.risk_level,
        "flags": len(compliance.flags),
    }
```

---

## Architecture

```
Your App
  │
  ▼
btr.BarterClient
  ├── client.trust       → BTR-Trust (Soulbound ERC-721/5192) — scores, profiles
  ├── client.trade       → BarterCore — propose, accept, settle, dispute
  ├── client.credit      → BTR-Credit (ERC-20) — balances, rewards
  └── client.compliance  → On-chain analysis — velocity, isolation, flags
          │
          ▼
    Ethereum Sepolia (via Web3.py + Alchemy/Infura RPC)
          │
          ▼
    Bitcoin Lightning Network (payment settlement layer)
```

---

## API Reference

### Client

```python
import btr

client = btr.BarterClient(
    rpc_url="https://eth-sepolia.g.alchemy.com/v2/YOUR_KEY",  # optional
    network="sepolia",                                          # default
    private_key="0x...",                                        # for write ops
)
```

| Parameter | Type | Default | Description |
|---|---|---|---|
| `rpc_url` | `str \| None` | env `ALCHEMY_RPC_URL` | Ethereum JSON-RPC endpoint |
| `network` | `str` | `"sepolia"` | Network for contract address resolution |
| `private_key` | `str \| None` | env `DEPLOYER_PRIVATE_KEY` | For signing transactions (write operations) |

**Read-only operations** (scores, profiles, balances, compliance) need no private key.
**Write operations** (propose, accept, settle, dispute) require a private key.

---

### Trust — `client.trust`

| Method | Returns | Description |
|---|---|---|
| `get_score(address)` | `int` | Current BTR-Trust score (0 if no history) |
| `get_profile(address)` | `TrustProfile` | Full profile: score, trade count, completion rate, counterparties |
| `get_pair_count(addr_a, addr_b)` | `int` | Number of trust-contributing trades between two addresses (max 5) |
| `get_history(address)` | `list[ScoreEvent]` | Score change history from on-chain events |

**TrustProfile fields:**

```python
class TrustProfile:
    address: str
    score: int                        # Soulbound trust score
    unique_counterparties: int        # Distinct addresses traded with
    member_since: datetime | None     # First trade timestamp
    trade_count: int                  # Total trades
    completion_rate: float            # % of trades successfully settled
    last_trade_at: datetime | None    # Most recent trade
```

---

### Trade — `client.trade`

| Method | Returns | Description |
|---|---|---|
| `propose(counterparty, payment_hash, amount_sats, category, description)` | `str` | Propose a trade, returns trade ID |
| `accept(trade_id)` | `dict` | Accept a proposed trade |
| `settle(trade_id, preimage)` | `dict` | Settle with Lightning preimage (SHA256 verified) |
| `dispute(trade_id)` | `dict` | Dispute an accepted trade |
| `get(trade_id)` | `Trade` | Get trade details by ID |
| `list_by_address(address)` | `list[Trade]` | All trades involving an address |

**Trade lifecycle:**
```
[ Proposed ] → [ Accepted ] → [ Settled ]  ← preimage submitted
     │              │
     │              └→ [ Disputed ]
     │
     └→ [ Expired ]  (after 7 days)
```

**Trade fields:**

```python
class Trade:
    trade_id: str
    party_a: str               # Proposer
    party_b: str               # Counterparty
    payment_hash: str          # SHA256 hash for HTLC verification
    amount_sats: int           # Trade amount in satoshis
    category: str              # goods, services, labor, digital, financial
    description: str           # Human-readable description
    status: TradeStatus        # proposed | accepted | settled | disputed | expired
    created_at: datetime
    settled_at: datetime | None
```

---

### Credit — `client.credit`

| Method | Returns | Description |
|---|---|---|
| `balance_of(address)` | `int` | BTR-Credit token balance |
| `total_supply()` | `int` | Total BTR-Credit tokens in circulation |
| `total_earned(address)` | `int` | Lifetime credits earned by address |

BTR-Credit is minted automatically when trades settle. Amount = `min(10000, max(1, sats / 1000))`.

---

### Compliance — `client.compliance`

| Method | Returns | Description |
|---|---|---|
| `get_flags(address)` | `list[AnomalyFlag]` | Active anomaly flags for an address |
| `get_velocity(address)` | `VelocityReport` | Trade velocity analysis (24h, 7d, 30d) |
| `detect_isolation(address)` | `ClusterReport` | Network isolation / clustering analysis |
| `full_report(address)` | `ComplianceReport` | Complete compliance analysis |

**What gets flagged:**

| Flag | Trigger | Why it matters |
|---|---|---|
| **High velocity** | > 50 trades/day | Potential bot or wash trading |
| **Isolation** | < 3 counterparties with high volume | Circular trading between colluding wallets |
| **Amount uniformity** | > 80% same amount | Artificial repetition pattern |
| **Off-hours activity** | > 60% in 2-5am UTC | Automated bot behavior |
| **Pair cap exceeded** | > 5 trades with same counterparty | Score farming between two wallets |

**ComplianceReport fields:**

```python
class ComplianceReport:
    address: str
    flags: list[AnomalyFlag]
    velocity: VelocityReport
    cluster: ClusterReport
    risk_level: str            # "low" | "medium" | "high"
    generated_at: datetime
```

---

## Error Handling

All SDK-specific errors inherit from `btr.BarterError`:

```python
import btr

try:
    client.trade.propose(
        counterparty="not-a-valid-address",
        payment_hash="0xabc",
        amount_sats=500,  # below 1000 minimum
    )
except btr.InvalidAddressError:
    print("Bad address format")
except btr.InsufficientAmountError:
    print("Minimum trade is 1,000 sats")
except btr.SelfTradeError:
    print("Cannot trade with yourself")
except btr.PreimageMismatchError:
    print("SHA256(preimage) doesn't match payment hash")
except btr.BarterError as e:
    print(f"Protocol error: {e}")
```

| Exception | When |
|---|---|
| `InvalidAddressError` | Malformed Ethereum address |
| `InsufficientAmountError` | Trade amount < 1,000 sats |
| `SelfTradeError` | party_a == party_b |
| `TradeNotFoundError` | Trade ID doesn't exist on-chain |
| `PreimageMismatchError` | `SHA256(preimage) != payment_hash` |

---

## Smart Contracts

The SDK interacts with three contracts deployed on Ethereum Sepolia:

| Contract | What it does | Token standard |
|---|---|---|
| **BarterCore** | Trade lifecycle (propose/accept/settle/dispute), SHA256 verification, pair cap enforcement | — |
| **BTR-Trust** | Soulbound reputation scores, non-transferable, logarithmic scoring | ERC-721 + ERC-5192 |
| **BTR-Credit** | Reward tokens minted on settlement, holder-burnable | ERC-20 |

**Key protocol parameters:**

| Parameter | Value | Purpose |
|---|---|---|
| Minimum trade | 1,000 sats | Prevent dust spam |
| Pair cap | 5 trades / pair | Prevent wash trading between two wallets |
| Score formula | `log2(sats/1000 + 1) + 1` | Logarithmic — diminishing returns on large amounts |
| Trade expiry | 7 days | Auto-expire unaccepted proposals |
| Credit formula | `min(10000, max(1, sats/1000))` | Linear reward capped at 10k |

---

## Configuration

### Environment variables

| Variable | Purpose |
|---|---|
| `ALCHEMY_RPC_URL` | Default RPC endpoint |
| `DEPLOYER_PRIVATE_KEY` | Default signing key for write operations |

### Using a `.env` file

```bash
# .env
ALCHEMY_RPC_URL=https://eth-sepolia.g.alchemy.com/v2/your-key
DEPLOYER_PRIVATE_KEY=0xYourPrivateKey
```

```python
from dotenv import load_dotenv
load_dotenv()

import btr
client = btr.BarterClient()  # picks up env vars automatically
```

---

## Links

- **GitHub**: [github.com/TheBarmaEffect/barter-protocol](https://github.com/TheBarmaEffect/barter-protocol)
- **Live Frontend**: [thebarmaeffect.github.io/barter-protocol](https://thebarmaeffect.github.io/barter-protocol)
- **PyPI**: [pypi.org/project/barter-sdk](https://pypi.org/project/barter-sdk/)
- **Smart Contracts**: [contracts/](https://github.com/TheBarmaEffect/barter-protocol/tree/main/contracts)
- **JS/TS SDK**: [@thebarmaeffect/barter-sdk](https://github.com/TheBarmaEffect/barter-protocol/tree/main/sdk-js)
- **React SDK**: [@thebarmaeffect/barter-react](https://github.com/TheBarmaEffect/barter-protocol/tree/main/sdk-react)

---

## License

MIT
