Skip to main content

Proof of Trade Protocol — Python SDK for BTR-Trust soulbound reputation

Project description

[ B A R T E R ]
barter-sdk — Python SDK for the Proof of Trade Protocol

PyPI version Python versions License: MIT Downloads


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

pip install barter-sdk

That's it. Python 3.8+ required.


Try It in 30 Seconds

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:

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:

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:

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

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

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:

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:

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:

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:

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

# .env
ALCHEMY_RPC_URL=https://eth-sepolia.g.alchemy.com/v2/your-key
DEPLOYER_PRIVATE_KEY=0xYourPrivateKey
from dotenv import load_dotenv
load_dotenv()

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

Links


License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

barter_sdk-1.0.2.tar.gz (15.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

barter_sdk-1.0.2-py3-none-any.whl (15.4 kB view details)

Uploaded Python 3

File details

Details for the file barter_sdk-1.0.2.tar.gz.

File metadata

  • Download URL: barter_sdk-1.0.2.tar.gz
  • Upload date:
  • Size: 15.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.6

File hashes

Hashes for barter_sdk-1.0.2.tar.gz
Algorithm Hash digest
SHA256 81aae6df77443e9e135e3996af728ccc995d2c5423bf73b3086ebedbe963d3d8
MD5 fffc145d09bc811dd64a5dde48b71fab
BLAKE2b-256 643968984c8ac08ff1a4be680433f238adb6179d2ca75372727f0d948226bbae

See more details on using hashes here.

File details

Details for the file barter_sdk-1.0.2-py3-none-any.whl.

File metadata

  • Download URL: barter_sdk-1.0.2-py3-none-any.whl
  • Upload date:
  • Size: 15.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.6

File hashes

Hashes for barter_sdk-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 005ce565dc08d1be5e805dc000d37290b0395bccca6114c88357d88dc24c4c13
MD5 24cff74d8b0a0113e73bcaa5bce8dc3e
BLAKE2b-256 5bf73494dc033ef6a667fed75346f28946942f90212b3d3640722d8eaebb712a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page