Skip to content
This repository was archived by the owner on Dec 2, 2025. It is now read-only.
Merged

main #200

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
b4f5090
Update FUNDING.yml
JosueBrenes Jun 28, 2025
7e7c8a3
Merge pull request #195 from trustbridgecr/main
JosueBrenes Jun 28, 2025
3b29941
feat: implement TrustBridge marketplace with Blend SDK integration
Jun 28, 2025
73dc655
feat: Remove sidebar and move marketplace to header navigation
Jun 29, 2025
92e2d09
refactor: Clean up MarketplacePage component formatting and remove un…
JosueBrenes Jun 29, 2025
c4f5706
refactor: Remove unused FlaskConical icon import from MarketplacePage
JosueBrenes Jun 29, 2025
d0f329f
feat: Add marketplace integration with Blend Protocol - modals, pool …
Jul 3, 2025
3a41373
fix: Add comprehensive error handling for Blend Protocol Error #1206
Jul 3, 2025
654a6a6
feat: Add comprehensive Error #1206 diagnostics and fix tools
Jul 3, 2025
7722fb4
fix: Correct contract addresses and diagnostic script for Error #1206
Jul 3, 2025
9404ee7
fix: Add SDK compatibility detection for min_collateral parsing error
Jul 3, 2025
5436c48
Merge pull request #196 from big14way/feature/marketplace-blend-integ…
JosueBrenes Jul 3, 2025
c437d4a
feat: implement Provide Liquidity modal and deposit flow (#175)
Jul 4, 2025
9b418c1
fix: use correct RequestType.Supply for deposit transactions
Jul 4, 2025
aab77ad
Merge pull request #198 from big14way/feature/provide-liquidity-modal…
JosueBrenes Jul 4, 2025
5754528
Implement Blend SDK integration for marketplace operations
Jul 4, 2025
d86a92d
Resolve merge conflict in MarketplacePage.tsx
Jul 4, 2025
e6096f0
Merge branch 'develop' into feature/marketplace-blend-integration-176
big14way Jul 4, 2025
b8392b8
fix: use PoolContractV2 and correct signTransaction usage in ProvideL…
big14way Jul 4, 2025
1822917
Merge pull request #199 from big14way/feature/marketplace-blend-integ…
JosueBrenes Jul 5, 2025
f8e73c8
refactor: change ui
JosueBrenes Jul 5, 2025
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
203 changes: 192 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,53 @@

# TrustBridge

Integration prototype between **TrustBridge** and **Blend.Capital** enabling **cross-chain lending** on the Stellar blockchain using bridged assets and Blends permissionless lending infrastructure.
Integration prototype between **TrustBridge** and **Blend.Capital** enabling **cross-chain lending** on the Stellar blockchain using bridged assets and Blend's permissionless lending infrastructure.

🔗 Built on Stellar + Soroban
🧪 MVP running on testnet
💱 Use case: Interoperable Lending with bridged assets (e.g., USDC, BLND)
💱 Use case: Interoperable Lending with bridged assets (e.g., USDC, BLND)
🏪 **NEW**: Complete marketplace interface with pool deployment and borrowing functionality

## Features

### 🏦 TrustBridge-MicroLoans Pool
- **Multi-asset support**: USDC, XLM, and TBRG token reserves
- **Oracle integration**: Real-time price feeds for accurate collateral valuation
- **Risk management**: Configurable collateral factors and liquidation thresholds
- **Pool deployment**: One-click deployment of lending pools via Blend Protocol

### 💰 Marketplace Interface
- **Dashboard**: Comprehensive overview of pool statistics and user positions
- **Borrow Flow**: Intuitive USDC borrowing with real-time health factor calculation
- **Wallet Integration**: Seamless Freighter wallet connection and transaction signing
- **Health Monitoring**: Live collateral ratio and liquidation risk tracking

### 🔧 Technical Implementation
- **Blend SDK v2.2.0**: Complete integration with Blend Protocol's lending infrastructure
- **Pool Factory**: Automated deployment using Blend's PoolFactoryContract
- **Smart Contracts**: Proper Stellar testnet contract addresses and configurations
- **TypeScript**: Type-safe implementation with comprehensive error handling

## Getting Started

1. Install dependencies, including the Blend SDK:
### Prerequisites
- Node.js 18+ and npm
- Freighter wallet extension installed
- Stellar testnet account with funded XLM

### Installation

1. Clone the repository and install dependencies:

```bash
git clone https://github.com/yourusername/dApp-TrustBridge.git
cd dApp-TrustBridge/frontend
npm install
```

2. Copy the `.env.example` file to `.env` and configure the following variables:
- Blend contract addresses
- Wallet address
- Wallet address
- RPC or Soroban network details (testnet or mainnet)

3. Launch the development server:
Expand All @@ -27,18 +57,169 @@ npm install
npm run dev
```

4. Navigate to the marketplace:
- Open `http://localhost:3000`
- Go to Dashboard → Marketplace
- Connect your Freighter wallet

### Pool Deployment

1. **Connect Wallet**: Click "Connect Wallet" and approve Freighter connection
2. **Deploy Pool**: Click "Deploy Pool" to create the TrustBridge-MicroLoans pool
3. **Wait for Confirmation**: Transaction will be signed and submitted to Stellar testnet
4. **Start Borrowing**: Once deployed, use "Borrow USDC" to access lending functionality

## Architecture Overview

- **TrustBridge** handles asset bridging and cross-chain messaging.
- **Blend** manages lending, borrowing, and liquidations in a permissionless environment.
- Integration is implemented using Soroban smart contracts and TypeScript interfaces.
### Smart Contract Integration
- **TrustBridge Contracts**: Handle asset bridging and cross-chain messaging
- **Blend Protocol**: Manages lending, borrowing, and liquidations in a permissionless environment
- **Oracle Contract**: Provides real-time price feeds for collateral valuation
- **Pool Factory**: Deploys and configures lending pools with custom parameters

### Frontend Architecture
```
frontend/src/
├── config/contracts.ts # Contract addresses & network configuration
├── helpers/pool-deployment.helper.ts # Pool deployment workflow
├── app/dashboard/ # Dashboard pages and layouts
│ ├── layout.tsx # Dashboard sidebar navigation
│ ├── page.tsx # Dashboard overview
│ └── marketplace/ # Marketplace functionality
├── components/modules/marketplace/ # Marketplace UI components
│ └── ui/
│ ├── pages/MarketplacePage.tsx # Main marketplace interface
│ └── components/BorrowModal.tsx # Borrow transaction flow
└── providers/ # Context providers for wallet and state
```

### Key Contracts (Stellar Testnet)
- **Oracle**: `CBCIZHUC42CKOZHKKEYMSXVVY24ZK2EKEUU6NFGQS5YFG7GAMEU5L32M`
- **USDC Token**: `CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA`
- **XLM Token**: `CDLZFC3SYJYDZT7K67VZ75HPJVIEUVNIXF47ZG2FB2RMQQAOBKYCWXVB`
- **TBRG Token**: `CAAUAE53WKWR4X2BRCHXNUTDJGXTOBMHMK3KFTAPEUBA7MJEQBPWVWQU`
- **Pool Factory**: `CCDEMRRGV4XHXR6PVHA6OXQ5NV3NWUGWFWRR5H3CEPSNKVPQRYVCTPPU`

## Usage Examples

### Deploy a Lending Pool
```typescript
import { deployCompletePool } from '@/helpers/pool-deployment.helper';

// Deploy TrustBridge-MicroLoans pool
const poolId = await deployCompletePool(walletAddress);
console.log('Pool deployed:', poolId);
```

### Borrow USDC
```typescript
import { PoolContract, RequestType } from '@blend-capital/blend-sdk';

// Create borrow transaction
const pool = new PoolContract(TRUSTBRIDGE_POOL_ID);
const borrowOpXdr = pool.submit({
from: walletAddress,
spender: walletAddress,
to: walletAddress,
requests: [{
request_type: RequestType.Borrow,
address: TOKENS.USDC,
amount: BigInt(amount * 1e7), // USDC has 7 decimals
}],
});

// Sign with Freighter
const signedTx = await signTransaction({
unsignedTransaction: borrowOpXdr,
address: walletAddress
});
```

## Pool Configuration

### TrustBridge-MicroLoans Parameters
- **Backstop Rate**: 15% - Fee charged for backstop provider protection
- **Max Positions**: 4 - Maximum number of concurrent user positions
- **Reserves**: USDC (primary), XLM (collateral), TBRG (governance)

### Reserve Configurations
| Asset | Collateral Factor | Liability Factor | Target Utilization |
|-------|------------------|------------------|-------------------|
| USDC | 85% | 95% | 80% |
| XLM | 75% | 90% | 75% |
| TBRG | 60% | 85% | 70% |

## Development

### Running Tests
```bash
cd frontend
npm run test
```

### Linting and Formatting
```bash
npm run lint # Check for linting errors
npm run lint:fix # Auto-fix linting issues
npm run format # Format code with Prettier
```

### Building for Production
```bash
npm run build # Build optimized production bundle
npm run start # Serve production build locally
```

## Troubleshooting

### Common Issues

1. **Wallet Connection Failed**
- Ensure Freighter extension is installed and unlocked
- Check that you're on Stellar testnet
- Verify wallet has sufficient XLM for transaction fees

2. **Pool Deployment Failed**
- Confirm Pool Factory contract address is correct
- Check network connectivity to Stellar testnet
- Ensure wallet has sufficient XLM balance (minimum 1 XLM recommended)

3. **Borrow Transaction Failed**
- Verify pool is deployed and active
- Check sufficient collateral is deposited
- Ensure borrow amount doesn't exceed health factor limits

### Getting Help
- Check the [Issues](https://github.com/yourusername/dApp-TrustBridge/issues) for known problems
- Join our [Discord](https://discord.gg/trustbridge) for community support
- Review [Blend Protocol Documentation](https://docs.blend.capital/) for advanced usage

## Status

- Functional MVP live on Stellar testnet
- Supports USDC and BLND lending pools
- Oracle integration via custom `oracle-mock` Soroban contract
- ✅ Functional MVP live on Stellar testnet
- ✅ Complete marketplace interface with pool deployment
- ✅ USDC borrowing with real-time health factor calculation
- ✅ Multi-asset support (USDC, XLM, TBRG)
- ✅ Oracle integration for accurate price feeds
- ✅ Wallet integration with Freighter
- 🚧 Supply/lending functionality (coming next)
- 🚧 Liquidation interface
- 🚧 Cross-chain asset bridging integration

## Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## License

MIT
MIT - see [LICENSE](LICENSE) file for details.

---

**TrustBridge** - Bridging the gap between chains, one loan at a time. 🌉
3 changes: 3 additions & 0 deletions frontend/.github/FUNDING.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
github: false
custom:
- https://app.onlydust.com/projects/trustbridge
152 changes: 152 additions & 0 deletions frontend/dist/activate-pool.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
#!/usr/bin/env ts-node
"use strict";
/**
* TrustBridge Pool Activation Script
*
* This script helps activate the TrustBridge pool to resolve Error #1206
* Usage: npx ts-node src/scripts/activate-pool.ts
*/
Object.defineProperty(exports, "__esModule", { value: true });
const stellar_sdk_1 = require("@stellar/stellar-sdk");
// Configuration
const POOL_ID = "CB7BGBKLC4UNO2Q6V7O52622I44PVMDFDAMAJ6NT64GB3UQZX3FU7LA5";
const NETWORK_CONFIG = {
networkPassphrase: "Test SDF Network ; September 2015",
rpcUrl: "https://soroban-testnet.stellar.org:443"
};
// Pool admin secret key - REPLACE WITH YOUR ACTUAL ADMIN SECRET KEY
const ADMIN_SECRET_KEY = process.env.ADMIN_SECRET_KEY || "";
/**
* Pool Status Enum
*/
var PoolStatus;
(function (PoolStatus) {
PoolStatus[PoolStatus["ADMIN_ACTIVE"] = 0] = "ADMIN_ACTIVE";
PoolStatus[PoolStatus["ACTIVE"] = 1] = "ACTIVE";
PoolStatus[PoolStatus["ADMIN_ON_ICE"] = 2] = "ADMIN_ON_ICE";
PoolStatus[PoolStatus["ON_ICE"] = 3] = "ON_ICE";
PoolStatus[PoolStatus["ADMIN_FROZEN"] = 4] = "ADMIN_FROZEN";
PoolStatus[PoolStatus["FROZEN"] = 5] = "FROZEN";
PoolStatus[PoolStatus["SETUP"] = 6] = "SETUP"; // This status blocks all transactions
})(PoolStatus || (PoolStatus = {}));
/**
* Activate the pool by setting status to Admin Active
*/
async function activatePool() {
if (!ADMIN_SECRET_KEY) {
console.error("❌ Error: ADMIN_SECRET_KEY environment variable not set");
console.log("💡 Set it using: export ADMIN_SECRET_KEY=YOUR_SECRET_KEY");
process.exit(1);
}
try {
console.log("🚀 Starting TrustBridge Pool Activation...");
console.log("📍 Pool ID:", POOL_ID);
console.log("");
// Initialize RPC server and admin keypair
const server = new stellar_sdk_1.rpc.Server(NETWORK_CONFIG.rpcUrl);
const adminKeypair = stellar_sdk_1.Keypair.fromSecret(ADMIN_SECRET_KEY);
console.log("👤 Admin Account:", adminKeypair.publicKey());
// Get admin account
const account = await server.getAccount(adminKeypair.publicKey());
console.log("💰 Admin Account:", adminKeypair.publicKey());
// Create pool contract instance
const poolContract = new stellar_sdk_1.Contract(POOL_ID);
console.log("⚙️ Building pool activation transaction...");
// Build transaction to set pool status to Admin Active
const transaction = new stellar_sdk_1.TransactionBuilder(account, {
fee: '1000000', // 1 XLM fee for safety
networkPassphrase: NETWORK_CONFIG.networkPassphrase
})
.addOperation(poolContract.call('set_status', (0, stellar_sdk_1.nativeToScVal)(PoolStatus.ADMIN_ACTIVE, { type: 'u32' })))
.setTimeout(30)
.build();
console.log("🧪 Simulating transaction...");
// Simulate transaction first
const simulation = await server.simulateTransaction(transaction);
if (stellar_sdk_1.rpc.Api.isSimulationError(simulation)) {
console.error("❌ Simulation failed:", simulation.error);
console.log("");
console.log("🔍 Common issues:");
console.log(" - Pool admin permissions (make sure you're the pool admin)");
console.log(" - Pool already active");
console.log(" - Network connectivity issues");
process.exit(1);
}
console.log("✅ Simulation successful!");
// Assemble transaction with simulation results
const assembledTx = stellar_sdk_1.rpc.assembleTransaction(transaction, simulation).build();
console.log("✍️ Signing transaction...");
// Sign transaction
assembledTx.sign(adminKeypair);
console.log("📤 Submitting transaction...");
// Submit transaction
const result = await server.sendTransaction(assembledTx);
if (result.status === "PENDING") {
console.log("⏳ Transaction submitted! Hash:", result.hash);
console.log("🔄 Waiting for confirmation...");
// Wait for confirmation
let attempts = 0;
const maxAttempts = 30;
while (attempts < maxAttempts) {
await new Promise(resolve => setTimeout(resolve, 2000));
try {
const txResult = await server.getTransaction(result.hash);
if (txResult.status === "SUCCESS") {
console.log("");
console.log("🎉 Pool activation successful!");
console.log("✅ Pool status set to Admin Active");
console.log("🔗 Transaction hash:", result.hash);
console.log("");
console.log("📋 Next steps:");
console.log(" 1. Your pool is now activated");
console.log(" 2. Users can now supply and borrow");
console.log(" 3. Test transactions should work (no more Error #1206)");
console.log(" 4. Consider adding backstop funding for enhanced security");
return;
}
else if (txResult.status === "FAILED") {
console.error("❌ Transaction failed:", txResult.resultXdr);
process.exit(1);
}
}
catch {
console.log("⏳ Still waiting for confirmation...");
}
attempts++;
}
console.error("❌ Transaction confirmation timeout");
console.log("🔗 Check status manually: https://stellar.expert/explorer/testnet/tx/" + result.hash);
process.exit(1);
}
else {
console.error("❌ Transaction submission failed:", result.errorResult);
process.exit(1);
}
}
catch (error) {
console.error("❌ Pool activation failed:", error);
console.log("");
console.log("🔍 Troubleshooting:");
console.log(" - Verify ADMIN_SECRET_KEY is correct");
console.log(" - Ensure admin account has XLM for fees");
console.log(" - Check network connectivity");
console.log(" - Verify you're the pool admin");
process.exit(1);
}
}
/**
* Main function
*/
async function main() {
console.log("🏗️ TrustBridge Pool Activation Tool");
console.log("=====================================");
console.log("");
await activatePool();
}
// Run the script
if (require.main === module) {
main().catch(error => {
console.error("❌ Script failed:", error);
process.exit(1);
});
}
Loading