BARTER PROTOCOL
[ B A R T E R ]
Proof of Trade Protocol -- Verifiable Trust Anchored in Bitcoin Lightning
More than a coin. A coin is just money. Barter is money plus proof of who you are.
Three paths — pick the one that fits your time. All contracts are live on Sepolia and the frontend connects to them directly via MetaMask.
Prerequisites: MetaMask browser extension + some Sepolia ETH (faucet)
Step 1 — Run the frontend locally:
git clone https://github.com/thebarmaeffect/barter-protocol.git
cd barter-protocol/frontend
npm install
npm run dev
# Opens at http://localhost:5173Step 2 — Connect wallet:
- Click "Connect Wallet" in the top-right
- MetaMask will prompt you — approve the connection
- Ensure you're on the Sepolia network (the app shows a yellow warning if you're on the wrong chain)
Step 3 — Propose a trade:
- Go to the Trade page from the sidebar
- Enter a counterparty address (use the test address below, or a friend's wallet)
- Pick a category, enter a description, and set an amount (min 1,000 sats)
- Click through the steps — MetaMask will ask you to sign the transaction
- Your trade is now on-chain on Sepolia
Step 4 — Accept + Settle (two-wallet flow):
- To test the full flow, you need a second wallet to accept the trade
- The counterparty connects, opens the trade from their History page, and clicks Accept Trade
- After acceptance, enter the preimage (SHA256 hash pair from Lightning payment)
- Click Settle — this calls the real contract, updates trust scores, and mints BTR-Credit
Test Addresses (Sepolia):
| Role | Address |
|---|---|
| Deployer / Party A | 0x742d35Cc6634C0532925a3b844Bc9e7595f3F9a0 |
| Use any Sepolia wallet as Party B | Get test ETH from Alchemy faucet |
Verify on Etherscan: Every trade, score update, and token mint is visible on-chain:
- BarterCore — trade transactions
- BTRTrust — soulbound score updates
- BTRCredit — ERC-20 reward mints
JavaScript/TypeScript
git clone https://github.com/thebarmaeffect/barter-protocol.git
cd barter-protocol/sdk-js
npm install && npm run buildimport { BarterClient } from './dist/index.js';
// Read-only — no wallet needed, reads directly from Sepolia
const client = new BarterClient({ network: 'sepolia' });
const score = await client.trust.getScore('0x742d35Cc6634C0532925a3b844Bc9e7595f3F9a0');
const profile = await client.trust.getProfile('0x742d35Cc6634C0532925a3b844Bc9e7595f3F9a0');
const flags = await client.compliance.getFlags('0x742d35Cc6634C0532925a3b844Bc9e7595f3F9a0');Python
pip install barter-sdkimport btr
client = btr.BarterClient(network="sepolia")
score = client.trust.get_score("0x742d35Cc6634C0532925a3b844Bc9e7595f3F9a0")
profile = client.trust.get_profile("0x742d35Cc6634C0532925a3b844Bc9e7595f3F9a0")
report = client.compliance.full_report("0x742d35Cc6634C0532925a3b844Bc9e7595f3F9a0")All Solidity is in contracts/contracts/. Start with BarterCore.sol (trade lifecycle + SHA256 HTLC verification), then BTRTrust.sol (soulbound ERC-721 with logarithmic scoring).
cd barter-protocol/contracts
npm install && npx hardhat compile && npx hardhat test
# 52 tests, all passingAll three contracts are deployed and wired on Ethereum Sepolia. The frontend, SDKs, and CLI all point to these addresses.
| Contract | Address | Etherscan |
|---|---|---|
| BarterCore | 0x81B1bC47Adb530968922a50B6EF8A76c22c580C7 |
View |
| BTRTrust | 0xC1f38C789117BE52e1E00c8bfBf2c72dae6b5e1b |
View |
| BTRCredit | 0x2EEbD391Fe1FbadCc6B56C464c4090E68FC4b077 |
View |
| Component | Status | Notes |
|---|---|---|
| Smart Contracts (Solidity) | Deployed on Sepolia | 52 passing tests. All three contracts live and wired. |
| Frontend | Production | Real MetaMask + real contract calls. No mock data — all reads/writes go to Sepolia. |
| JS/TS SDK | Published on npm | npm install @thebarmaeffect/barter-sdk — full ethers.js v6 implementation. |
| React SDK | Published on npm | npm install @thebarmaeffect/barter-react — Provider + 4 hooks. |
| Python SDK | Published on PyPI | pip install barter-sdk — full Web3.py client. |
| REST API | Runnable | Express server with Zod validation, connects to deployed contracts. |
| CLI | Buildable | npm run build && npm link makes btr available globally. |
-
Full trade lifecycle (frontend) — Connect MetaMask, propose a trade, have a second wallet accept, settle with preimage. Watch trust score and BTR-Credit update in real-time. All on Sepolia.
-
Contract logic —
cd contracts && npx hardhat test. Look attest/BarterCore.test.tsfor the SHA256 preimage verification tests, pair cap enforcement, and reentrancy guard tests. -
On-chain verification — After any trade, check the Etherscan links above. Every
TradeProposed,TradeAccepted,TradeSettledevent is logged. Trust score updates and BTR-Credit mints are visible. -
SDK build —
cd sdk-js && npm install && npm run build. Or justpip install barter-sdkand run the Python examples above. -
Trust math — The scoring formula
delta = floor(log2(amountSats / 1000 + 1)) + 1is inBTRTrust.sol. The pair cap (5 per counterparty pair) is enforced inBarterCore.sol.
Barter is an on-chain reputation protocol that creates verifiable, soulbound trust scores from real economic activity. Unlike traditional credit systems that rely on centralized authorities and opaque algorithms, Barter derives trust from cryptographic proof of completed trades settled over the Bitcoin Lightning Network.
When two parties settle a trade via Lightning, the SHA256 preimage that proves payment is submitted on-chain as irrefutable evidence of a completed transaction. This proof is verified by the BarterCore smart contract, which then updates both parties' BTR-Trust soulbound scores and mints BTR-Credit utility tokens as rewards. Every score change is backed by a real economic interaction -- no self-attestation, no gaming, no centralized gatekeepers.
The BTR-Trust score is a soulbound token (ERC-721 with ERC-5192 lock) that is permanently bound to the wallet that earned it. It cannot be transferred, sold, or delegated. Trust is calculated using a logarithmic scoring function with a pair cap of 5 trades per counterparty pair, preventing wash trading and artificial inflation. The score reflects the breadth and depth of real trading relationships, not the volume of a single repeated interaction.
Barter bridges the gap between Bitcoin's unparalleled payment settlement layer and Ethereum's programmable identity infrastructure. By using Lightning HTLCs (Hash Time-Locked Contracts) as the proof mechanism and Ethereum as the trust ledger, Barter creates a cross-chain reputation system that is permissionless, tamper-proof, and universally verifiable.
Party A Lightning Network Party B
| | |
| 1. PROPOSE TRADE | |
| (paymentHash, amount, | |
| category, description) | |
|----------------------------->| |
| | |
| | 2. ACCEPT TRADE |
| |<------------------------------|
| | |
| 3. PAY VIA LIGHTNING | |
| (HTLC settles, preimage | |
| revealed) | |
|----------------------------->|------------------------------>|
| | |
| 4. SETTLE ON-CHAIN (submit preimage) |
| SHA256(preimage) == paymentHash |
| Verified by BarterCore contract |
| | |
| 5. TRUST UPDATED | 5. TRUST UPDATED |
| BTR-Trust score += delta | BTR-Trust score += delta
| BTR-Credit minted | BTR-Credit minted |
| | |
Trade Lifecycle States:
[ Proposed ] --> [ Accepted ] --> [ Settled ]
| |
| +--> [ Disputed ]
|
+--> [ Expired ] (after 7 days)
Step-by-step:
- Propose -- Party A calls
proposeTrade()with the counterparty address, a Lightning payment hash, the amount in satoshis, a category, and a description. - Accept -- Party B reviews the terms and calls
acceptTrade()to agree. Trades expire after 7 days if not accepted. - Pay -- The Lightning Network payment settles off-chain. The HTLC mechanism reveals the preimage to the payer upon successful payment.
- Settle -- Either party submits the preimage to
settleTrade(). The contract verifiesSHA256(preimage) == paymentHash. The preimage is marked as used to prevent replay. - Trust Updated -- Both parties' BTR-Trust soulbound scores increase (logarithmic delta based on trade amount). Both parties receive BTR-Credit ERC-20 tokens.
+---------------------------------------------+
| Frontend (React) |
| Vite + Tailwind + Recharts + Zustand |
| thebarmaeffect.github.io/barter-protocol |
+---------------------+-----------------------+
|
+--------------------------+--------------------------+
| | |
+---------v----------+ +-----------v----------+ +----------v---------+
| React SDK | | JS/TS SDK | | Python SDK |
| @thebarmaeffect/ | | @thebarmaeffect/ | | pip: barter-sdk |
| barter-react | | barter-sdk | | import btr |
| Hooks + Provider | | Client + WebLN | | Web3.py Client |
+--------+-----------+ +----------+------------+ +---------+----------+
| | |
+--------------------------+--------------------------+
|
+---------------v----------------+
| REST API |
| Express + Zod + Rate Limit |
| Port 3001 |
+---------------+----------------+
|
v
+--------------------------------------------------------------------+
| Ethereum (Sepolia) |
| |
| +-----------------+ +------------------+ +------------------+ |
| | BarterCore | | BTR-Trust | | BTR-Credit | |
| | Trade Engine | | Soulbound SBT | | ERC-20 Token | |
| | SHA256 HTLC |<->| ERC-721/5192 | | Trade Reward | |
| | Pair Caps | | Non-Transferable | | Mintable/Burn | |
| | ReentrancyGrd | | Log2 Scoring | | Core-Only Mint | |
| +-----------------+ +------------------+ +------------------+ |
| |
| +------------------+ |
| | BarterFactory | One-click deploy + wire all contracts |
| +------------------+ |
+--------------------------------------------------------------------+
|
+---------------v----------------+
| Bitcoin Lightning |
| Network |
| (Payment Settlement) |
+---------------------------------+
All contracts are written in Solidity 0.8.28 with OpenZeppelin v5, compiled with optimizer (200 runs), targeting the Cancun EVM.
| Contract | Description | Key Features | Sepolia Address |
|---|---|---|---|
| BarterCore | Trade lifecycle engine. Manages propose, accept, settle, dispute, and expire flows. | SHA256 preimage verification, ReentrancyGuard, pair cap enforcement, 7-day expiry, min 1000 sats | 0x81B1bC47Adb530968922a50B6EF8A76c22c580C7 |
| BTRTrust | Soulbound reputation token (ERC-721 + ERC-5192). Stores trust scores, trade counts, and counterparty diversity. | Non-transferable, logarithmic scoring (log2), pair cap (5 per pair), auto-mint on first trade |
0xC1f38C789117BE52e1E00c8bfBf2c72dae6b5e1b |
| BTRCredit | Utility reward token (ERC-20). Minted to both parties on trade settlement. | BarterCore-only minting, holder burn, amount = sats/1000 (min 1, max 10,000) |
0x2EEbD391Fe1FbadCc6B56C464c4090E68FC4b077 |
| BarterFactory | One-click deployment. Deploys all three contracts and wires them together. | Atomic deploy + wire, ownership transfer to caller | Deployed via individual contracts above |
| Package | Type | Install | Description |
|---|---|---|---|
| Smart Contracts | Solidity | cd contracts && npm install |
Hardhat project with 4 contracts, deploy scripts, 52 tests |
| Python SDK | Python | pip install barter-sdk |
Full client: import btr. Trust, Trade, Credit, Compliance sub-clients. Web3.py. |
| JS/TS SDK | TypeScript | npm install @thebarmaeffect/barter-sdk |
Full client with ethers.js v6. Trust, Trade, Credit, Compliance, WebLN settler. |
| React SDK | React | npm install @thebarmaeffect/barter-react |
Provider + hooks: useBarterScore, useBarterProfile, useBarterTrade, useBarterTrades |
| CLI | Node.js | npm install -g @thebarmaeffect/barter-cli |
btr command-line tool. Score, profile, trade, flags, graph, config, wallet commands. |
| REST API | Express | cd api && npm install |
RESTful API with Zod validation, rate limiting, OpenAPI spec. Port 3001. |
| Frontend | React | cd frontend && npm install |
Dashboard app. Vite + Tailwind + Recharts + Framer Motion + Zustand. |
import btr
# Initialize client (connects to Sepolia by default)
client = btr.BarterClient(network="sepolia")
# Read 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"Unique Counterparties: {profile.unique_counterparties}")
print(f"Trade Count: {profile.trade_count}")
print(f"Completion Rate: {profile.completion_rate}%")
# Get pair trust count between two addresses
pair_count = client.trust.get_pair_count(
"0x742d35Cc6634C0532925a3b844Bc9e7595f3F9a0",
"0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
)
print(f"Pair Trust Trades: {pair_count}/5")
# Propose a trade (requires private key)
client = btr.BarterClient(
network="sepolia",
private_key="0xYOUR_PRIVATE_KEY"
)
trade_id = client.trade.propose(
counterparty="0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
payment_hash="0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890",
amount_sats=50000,
category="electronics",
description="Laptop trade"
)
print(f"Trade proposed: {trade_id}")
# Settle a trade with Lightning preimage
receipt = client.trade.settle(
trade_id=trade_id,
preimage="0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"
)
# Run compliance checks
report = client.compliance.full_report("0x742d35Cc6634C0532925a3b844Bc9e7595f3F9a0")
print(f"Risk Level: {report.risk_level}")
print(f"Flags: {len(report.flags)}")import { BarterClient } from '@thebarmaeffect/barter-sdk';
import { ethers } from 'ethers';
// Read-only client
const client = new BarterClient({ network: 'sepolia' });
// Get trust score
const score = await client.trust.getScore('0x742d35Cc6634C0532925a3b844Bc9e7595f3F9a0');
console.log('Trust Score:', score);
// Get full profile
const profile = await client.trust.getProfile('0x742d35Cc6634C0532925a3b844Bc9e7595f3F9a0');
console.log('Profile:', profile);
// With signer (for write operations)
const provider = new ethers.BrowserProvider(window.ethereum);
const signer = await provider.getSigner();
const writeClient = new BarterClient({
network: 'sepolia',
signer,
});
// Propose a trade
const tradeId = await writeClient.trade.propose({
counterparty: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045',
paymentHash: '0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890',
amountSats: 50000,
category: 'electronics',
description: 'Laptop trade',
});
console.log('Trade ID:', tradeId);
// Settle with WebLN (in-browser Lightning)
await writeClient.webln.settle(tradeId);
// Check compliance
const flags = await client.compliance.getFlags('0x742d35Cc6634C0532925a3b844Bc9e7595f3F9a0');
console.log('Anomaly flags:', flags);import { BarterProvider, useBarterScore, useBarterProfile } from '@thebarmaeffect/barter-react';
// 1. Wrap your app with the provider
function App() {
return (
<BarterProvider config={{ network: 'sepolia' }}>
<TrustDashboard />
</BarterProvider>
);
}
// 2. Use hooks in any component
function TrustDashboard() {
const address = '0x742d35Cc6634C0532925a3b844Bc9e7595f3F9a0';
const { data: score, loading: scoreLoading } = useBarterScore(address);
const { data: profile, loading: profileLoading } = useBarterProfile(address);
if (scoreLoading || profileLoading) return <div>Loading...</div>;
return (
<div>
<h1>BTR-Trust Score: {score}</h1>
<p>Trades Completed: {profile?.tradeCount}</p>
<p>Unique Counterparties: {profile?.uniqueCounterparties}</p>
<p>Completion Rate: {profile?.completionRate}%</p>
</div>
);
}Available hooks:
| Hook | Returns | Description |
|---|---|---|
useBarterScore(address) |
{ data, loading, error, refetch } |
Fetch BTR-Trust score for an address |
useBarterProfile(address) |
{ data, loading, error, refetch } |
Fetch full trust profile |
useBarterTrade(tradeId) |
{ data, loading, error, propose, accept, settle } |
Single trade operations |
useBarterTrades(address) |
{ data, loading, error, refetch } |
List all trades for an address |
# Install globally
npm install -g @thebarmaeffect/barter-cli
# Check trust score
btr score 0x742d35Cc6634C0532925a3b844Bc9e7595f3F9a0
# Get full profile
btr profile 0x742d35Cc6634C0532925a3b844Bc9e7595f3F9a0
# Trade operations
btr trade propose # Interactive trade proposal
btr trade accept # Accept a pending trade
btr trade settle # Settle with preimage
btr trade list # List your trades
# Compliance
btr flags 0x742d35Cc6634C0532925a3b844Bc9e7595f3F9a0
# Trust graph
btr graph 0x742d35Cc6634C0532925a3b844Bc9e7595f3F9a0
# Configuration
btr config set rpc-url https://eth-sepolia.g.alchemy.com/v2/YOUR_KEY
btr config set network sepolia
# Wallet management
btr wallet import # Import private key
btr wallet balance # Check ETH + BTR-C balance# Health check
curl http://localhost:3001/health
# Get trust score
curl http://localhost:3001/v1/score/0x742d35Cc6634C0532925a3b844Bc9e7595f3F9a0
# Get full profile
curl http://localhost:3001/v1/profile/0x742d35Cc6634C0532925a3b844Bc9e7595f3F9a0
# Propose a trade
curl -X POST http://localhost:3001/v1/trade/propose \
-H "Content-Type: application/json" \
-d '{
"counterparty": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"paymentHash": "0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890",
"amountSats": 50000,
"category": "electronics",
"description": "Laptop trade"
}'
# Settle a trade
curl -X POST http://localhost:3001/v1/trade/settle \
-H "Content-Type: application/json" \
-d '{
"tradeId": "trade-001",
"preimage": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"
}'See the full API documentation for all endpoints, request/response schemas, and error codes.
The Barter frontend is a production React app that connects directly to deployed Sepolia contracts via MetaMask. All trade proposals, acceptances, and settlements are real on-chain transactions.
Tech stack: React 19 + Vite + Tailwind CSS v4 + Recharts + Framer Motion + Zustand + ethers.js v6 + React Router
How to run:
cd frontend && npm install && npm run dev
# Opens at http://localhost:5173Connect MetaMask on Sepolia, and you're interacting with real contracts. No mock data, no demo mode (unless MetaMask is absent).
The BTR-Trust score is a non-transferable, non-delegatable reputation metric bound to your wallet address. It is implemented as an ERC-721 token with ERC-5192 permanent lock (soulbound).
Scoring formula: Each successful trade yields a score delta calculated as:
delta = floor(log2(amountSats / 1000 + 1)) + 1
This logarithmic function means that a 1,000-sat trade yields +1 point, a 10,000-sat trade yields +4 points, and a 1,000,000-sat trade yields +11 points. Larger trades are rewarded, but with diminishing returns -- preventing whales from dominating scores purely through volume.
Key properties:
- Non-transferable: All transfer functions (
transferFrom,safeTransferFrom,approve,setApprovalForAll) revert unconditionally - Auto-minted: A soulbound token is minted to the wallet on its first trade
- Permanently locked:
locked(tokenId)always returnstrueper ERC-5192
BTR-Credit (BTR-C) is a standard ERC-20 utility token minted as a reward for completing trades. Both parties in a settled trade receive BTR-C tokens.
Minting formula:
creditAmount = clamp(amountSats / 1000, 1, 10000) * 1e18
- 1,000 sats = 1 BTR-C
- 50,000 sats = 50 BTR-C
- 10,000,000+ sats = 10,000 BTR-C (cap)
Key properties:
- Only BarterCore can mint (enforced by
onlyBarterCoremodifier) - Any holder can burn their own tokens via
burn(amount) - Standard ERC-20 transfers are allowed (BTR-C is tradeable, unlike BTR-Trust)
The core cryptographic primitive linking Lightning payments to on-chain trust. When a Lightning invoice is created, it contains a payment_hash = SHA256(preimage). When the payment settles, the preimage is revealed to the payer. Submitting this preimage to settleTrade() proves the Lightning payment occurred.
The contract verifies: sha256(abi.encode(paymentPreimage)) == trade.paymentHash
Used preimages are stored in usedPreimages mapping to prevent replay attacks.
To prevent wash trading (two wallets trading back and forth to inflate scores), Barter enforces a pair cap of 5 trust-counted trades per unique counterparty pair. The 6th and subsequent trades between the same two addresses will still settle and mint BTR-C, but will not increase either party's BTR-Trust score.
This encourages traders to build diverse trading relationships rather than repeatedly transacting with the same counterparty.
Every trade moves through a state machine with 5 possible states:
| State | Description | Transitions |
|---|---|---|
| Proposed | Trade created by Party A. Awaiting acceptance from Party B. | Accepted, Disputed, Expired |
| Accepted | Party B has agreed to the trade terms. Lightning payment can proceed. | Settled, Disputed |
| Settled | Preimage submitted and verified. Trust scores updated. Credits minted. | Terminal state |
| Disputed | Either party has raised a dispute. | Terminal state |
| Expired | 7 days elapsed without acceptance. Anyone can call expireTrade(). |
Terminal state |
The protocol includes behavioral analysis tools for detecting anomalous patterns:
- Velocity checks: Elevated trading frequency detection (thresholds: 20 trades/24h, 100 trades/7d)
- Isolation analysis: Graph clustering to detect isolated trading rings (Sybil resistance)
- Concentration detection: Flags addresses where >90% of trades are with a single counterparty
barter-protocol/
|
+-- contracts/ Solidity smart contracts (Hardhat)
| +-- contracts/
| | +-- BarterCore.sol Trade lifecycle engine
| | +-- BTRTrust.sol Soulbound trust score (ERC-721/5192)
| | +-- BTRCredit.sol Trade reward token (ERC-20)
| | +-- BarterFactory.sol One-click deployment factory
| +-- scripts/
| | +-- deploy.ts Deployment script
| | +-- extract-abis.ts ABI extraction for SDKs
| +-- test/
| | +-- BarterCore.test.ts 52 tests covering all contracts
| +-- hardhat.config.ts Solidity 0.8.28, optimizer, Sepolia config
|
+-- sdk-python/ Python SDK (pip: barter-sdk)
| +-- btr/
| | +-- __init__.py Package exports
| | +-- client.py BarterClient main entry point
| | +-- trust.py TrustClient (scores, profiles, history)
| | +-- trade.py TradeClient (propose, accept, settle, dispute)
| | +-- credit.py CreditClient (balances, burns)
| | +-- compliance.py ComplianceClient (flags, velocity, clusters)
| | +-- types.py Dataclass type definitions
| | +-- exceptions.py Custom exception hierarchy
| | +-- constants.py Contract addresses and ABIs
| +-- tests/ 25 tests (pytest)
|
+-- sdk-js/ TypeScript SDK (npm: @thebarmaeffect/barter-sdk)
| +-- src/
| | +-- index.ts Package exports
| | +-- client.ts BarterClient with ethers.js v6
| | +-- trust.ts TrustClient
| | +-- trade.ts TradeClient
| | +-- credit.ts CreditClient
| | +-- compliance.ts ComplianceClient
| | +-- webln.ts WebLN in-browser Lightning settler
| | +-- types.ts TypeScript type definitions
| | +-- errors.ts Custom error classes
| | +-- constants.ts Network constants and addresses
| | +-- abis/ Contract ABI JSON files
| +-- tests/ 25 tests (Jest)
|
+-- sdk-react/ React SDK (npm: @thebarmaeffect/barter-react)
| +-- src/
| | +-- index.ts Package exports
| | +-- BarterProvider.tsx React Context provider
| | +-- useBarterClient.ts Client instance hook
| | +-- useBarterScore.ts Score fetching hook
| | +-- useBarterProfile.ts Profile fetching hook
| | +-- useBarterTrade.ts Single trade operations hook
| | +-- useBarterTrades.ts Trade list hook
|
+-- cli/ CLI (npm: @thebarmaeffect/barter-cli)
| +-- src/
| | +-- index.ts Commander.js entry point
| | +-- commands/ score, profile, trade, flags, graph, config, wallet
| | +-- utils/ Output formatting, config management
|
+-- api/ REST API (Express)
| +-- src/
| | +-- index.ts Express app setup
| | +-- config.ts Environment configuration
| | +-- routes/ health, score, profile, history, flags, graph, trade
| | +-- middleware/ errorHandler, rateLimit, validate
| | +-- schemas/ Zod validation schemas
| | +-- types.ts TypeScript interfaces
| +-- openapi.yaml OpenAPI 3.0 specification
| +-- Dockerfile Production container
|
+-- frontend/ React Dashboard
| +-- src/ Vite + React 19 + Tailwind v4 + Recharts
| +-- package.json gh-pages deployment configured
|
+-- docs/ Documentation
+-- .github/ CI/CD workflows
+-- .env.example Environment variable template
+-- test-report.md Full test results (121 passing)
- Node.js >= 18
- Python >= 3.9
- npm >= 9
git clone https://github.com/thebarmaeffect/barter-protocol.git
cd barter-protocolcp .env.example .env
# Edit .env with your values:
# ALCHEMY_RPC_URL=https://eth-sepolia.g.alchemy.com/v2/YOUR_KEY
# DEPLOYER_PRIVATE_KEY=0xYOUR_PRIVATE_KEY
# ETHERSCAN_API_KEY=YOUR_ETHERSCAN_KEYcd contracts
npm install
npx hardhat compile
npx hardhat test # Run 52 contract tests
npx hardhat test --verbose # With gas reportingcd sdk-python
pip install -e ".[dev]"
pytest # Run 25 tests
pytest -v # Verbose outputcd sdk-js
npm install
npm test # Run 25 tests
npm run build # Build for distributioncd sdk-react
npm install
npm test
npm run buildcd cli
npm install
npm run build
npm link # Makes 'btr' available globally
btr --version # Verify: 1.0.0
btr --help # See all commandscd api
npm install
npm run dev # Start with hot reload (port 3001)
npm test # Run 19 API testscd frontend
npm install
npm run dev # Start dev server (Vite, port 5173)
npm run build # Production buildThe protocol has 121 tests across all components, all passing.
| Component | Framework | Tests | Command |
|---|---|---|---|
| Smart Contracts | Hardhat + Chai | 52 | cd contracts && npx hardhat test |
| Python SDK | pytest | 25 | cd sdk-python && pytest |
| JS/TS SDK | Jest | 25 | cd sdk-js && npm test |
| REST API | Jest + Supertest | 19 | cd api && npm test |
| Frontend | Vite Build | Build check | cd frontend && npm run build |
| CLI | Build + Run | Build check | cd cli && npm run build && btr --version |
Run all tests:
# Contracts
cd contracts && npx hardhat test && cd ..
# Python SDK
cd sdk-python && pytest && cd ..
# JS SDK
cd sdk-js && npm test && cd ..
# API
cd api && npm test && cd ..
# Frontend build check
cd frontend && npm run build && cd ..
# CLI build check
cd cli && npm run build && cd ..# Deploy to local Hardhat network
cd contracts
npx hardhat run scripts/deploy.ts --network hardhat
# Deploy to Sepolia testnet
npx hardhat run scripts/deploy.ts --network sepolia
# Or use the BarterFactory for one-click deployment
# The factory deploys BTRTrust, BTRCredit, and BarterCore,
# then wires them together and transfers ownership to the caller.Verification on Etherscan:
npx hardhat verify --network sepolia <CONTRACT_ADDRESS> <CONSTRUCTOR_ARGS>cd frontend
npm run build
npm run deploy # Deploys to GitHub Pages# Python SDK
cd sdk-python
python -m build
twine upload dist/*
# JS/TS SDK
cd sdk-js
npm run build
npm publish --access public
# React SDK
cd sdk-react
npm run build
npm publish --access public
# CLI
cd cli
npm run build
npm publish --access publiccd api
npm run build
docker build -t barter-api .
docker run -p 3001:3001 \
-e NETWORK=sepolia \
-e RPC_URL=https://eth-sepolia.g.alchemy.com/v2/YOUR_KEY \
barter-apiBarterCore.settleTrade() uses OpenZeppelin's ReentrancyGuard (nonReentrant modifier). State changes (status, preimage marking) occur before external calls to BTRTrust and BTRCredit.
BTRTrust overrides all ERC-721 transfer functions (transferFrom, safeTransferFrom, approve, setApprovalForAll) with unconditional reverts. The locked() function always returns true per ERC-5192. There is no unlock mechanism.
Every preimage submitted to settleTrade() is recorded in the usedPreimages mapping. Attempting to reuse a preimage reverts with "BarterCore: preimage already used". This prevents a single Lightning payment from being used to settle multiple trades.
BTRTrust.updateScore()-- Only callable by the BarterCore contract (onlyBarterCoremodifier)BTRCredit.mint()-- Only callable by the BarterCore contract (onlyBarterCoremodifier)BTRTrust.setBarterCore()-- Only callable by the owner (onlyOwnermodifier)BTRCredit.setBarterCore()-- Only callable by the owner (onlyOwnermodifier)- Ownership is transferred to the deployer via
BarterFactory.deploy()
- Zero address checks on all address parameters
- Self-trade prevention (
partyB != msg.sender) - Minimum trade amount enforcement (1,000 sats)
- Description length cap (200 characters)
- Empty payment hash rejection
- Trade status checks on all state transitions
- 7-day expiry enforcement on
acceptTrade()
Contributions are welcome. Please follow these guidelines:
- Fork the repository and create a feature branch from
main - Write tests for any new functionality
- Run the full test suite before submitting a PR (
121 tests must pass) - Follow existing code style (TypeScript strict mode, Solidity NatSpec comments)
- One feature per PR -- keep changes focused and reviewable
git checkout -b feature/your-feature
# Make changes
# Run tests in affected packages
git commit -m "Add your feature"
git push origin feature/your-feature
# Open a Pull RequestThis project is licensed under the MIT License.
BARTER -- Trust is earned, not given. Every score backed by proof.