# Developers

## Overview

Libre Chain provides a robust platform for building decentralized applications, with particular focus on Bitcoin-native financial services. This section covers smart contract development, API integration, and technical resources.

## Quick Start

### Network Information

* **Chain ID**: 1
* **RPC Endpoint**: `https://lb.libre.org`
* **Explorer**: `https://librebloks.io`
* **Testnet RPC**: `https://testnet.libre.org`

### Core Contracts

* **Lending Pools**: `loan`
* **DEX**: `dex.libre`
* **USDT Token**: `usdt.libre`
* **Fast BTC**: `btc.libre`

## Smart Contract Development

### Development Environment

Libre Chain uses the Antelope (formerly EOSIO) smart contract platform:

* **Language**: C++
* **Framework**: Antelope CDT
* **Testing**: Local testnet with cleos
* **Deployment**: Multi-sig governance process

### Getting Started

```bash
# Install Antelope CDT
wget https://github.com/AntelopeIO/cdt/releases/download/v3.0.1/cdt_3.0.1_amd64.deb
sudo apt install ./cdt_3.0.1_amd64.deb

# Set up local development environment
# See https://gitlab.com/libre-chain/libre-chain-nodes for testnet setup

# Build contract
mkdir build && cd build
cmake .. && make
```

### Example: Simple Lending Integration

```cpp
#include <eosio/eosio.hpp>
#include <eosio/asset.hpp>

class [[eosio::contract]] mylender : public eosio::contract {
public:
    using contract::contract;

    // Deposit USDT to lending pool
    [[eosio::action]]
    void deposit(name user, asset quantity, uint32_t pool_id) {
        require_auth(user);
        
        // Transfer USDT to lending contract
        action(
            permission_level{get_self(), "active"_n},
            "usdt.libre"_n,
            "transfer"_n,
            std::make_tuple(get_self(), "loan"_n, quantity, std::string("deposit"))
        ).send();

        // Call lending contract deposit action
        action(
            permission_level{get_self(), "active"_n},
            "loan"_n,
            "deposit"_n,
            std::make_tuple(user, quantity, pool_id)
        ).send();
    }
};
```

## API Integration

### REST API Endpoints

#### Loan Information

```bash
# Get active loans
curl https://lb.libre.org/v1/chain/get_table_rows \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{
    "code": "loan",
    "table": "loan",
    "scope": "loan",
    "limit": 1000,
    "json": true
  }'

# Get pool configurations
curl https://lb.libre.org/v1/chain/get_table_rows \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{
    "code": "loan",
    "table": "poolconfig",
    "scope": "loan",
    "json": true
  }'

# Get pool statistics
curl https://lb.libre.org/v1/chain/get_table_rows \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{
    "code": "loan",
    "table": "poolstats",
    "scope": "loan",
    "json": true
  }'
```

#### Vault Information

```bash
# Get user vault information
curl https://lb.libre.org/v1/chain/get_table_rows \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{
    "code": "loan",
    "table": "vault",
    "scope": "loan",
    "json": true
  }'
```

#### Pool Statistics

```bash
# Get global lending statistics
curl https://lb.libre.org/v1/chain/get_table_rows \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{
    "code": "loan",
    "table": "globalstats",
    "scope": "loan",
    "json": true
  }'
```

#### Token Balances

```bash
# Get USDT balance for loan contract
curl https://lb.libre.org/v1/chain/get_currency_balance \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{
    "code": "usdt.libre",
    "account": "loan",
    "symbol": "USDT"
  }'

# Deposit to specific pool using memo
curl https://lb.libre.org/v1/chain/push_transaction \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{
    "actions": [{
      "account": "usdt.libre",
      "name": "transfer",
      "authorization": [{
        "actor": "myaccount",
        "permission": "active"
      }],
      "data": {
        "from": "myaccount",
        "to": "loan",
        "quantity": "1000.000000 USDT",
        "memo": "pool:1"
      }
    }]
  }'
```

### Real-world Integration Example

Based on the tools.libre.org loan tracker implementation and actual loan contract source code. For complete implementation details, see the [libre-tools.com source code](https://github.com/bensig/libre-tools.com):

```javascript
// Fetch loan data using standard fetch API
const fetchLoans = async (scope) => {
  const response = await fetch('https://lb.libre.org/v1/chain/get_table_rows', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      code: 'loan',
      table: 'loan',
      scope, // 'loan' for active, 'completed' for finished loans
      limit: 1000,
      json: true
    })
  });

  const data = await response.json();
  return data.rows || [];
};

// Pool-specific deposit function
const depositToPool = async (account, amount, poolId) => {
  return await api.transact({
    actions: [{
      account: 'usdt.libre',
      name: 'transfer',
      authorization: [{
        actor: account,
        permission: 'active'
      }],
      data: {
        from: account,
        to: 'loan',
        quantity: amount,
        memo: `pool:${poolId}` // Pool-specific deposit
      }
    }]
  });
};

// Loan repayment function
const repayLoan = async (account, amount) => {
  return await api.transact({
    actions: [{
      account: 'usdt.libre',
      name: 'transfer',
      authorization: [{
        actor: account,
        permission: 'active'
      }],
      data: {
        from: account,
        to: 'loan',
        quantity: amount,
        memo: 'payback' // Required memo for loan repayment
      }
    }]
  });
};

// Get vault balances for collateral tracking
const fetchVaultBalance = async (vaultAccount) => {
  const [cbtcResponse, btcResponse] = await Promise.all([
    fetch('https://lb.libre.org/v1/chain/get_currency_balance', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        code: 'cbtc.libre',
        account: vaultAccount,
        symbol: 'CBTC'
      })
    }),
    fetch('https://lb.libre.org/v1/chain/get_currency_balance', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        code: 'btc.libre',
        account: vaultAccount,
        symbol: 'BTC'
      })
    })
  ]);

  const [cbtcBalances, btcBalances] = await Promise.all([
    cbtcResponse.json(),
    btcResponse.json()
  ]);

  return {
    cbtc: cbtcBalances[0] || '0.00000000 CBTC',
    btc: btcBalances[0] || '0.00000000 BTC'
  };
};

// Pool configuration data
const fetchPoolConfigs = async () => {
  const response = await fetch('https://lb.libre.org/v1/chain/get_table_rows', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      code: 'loan',
      table: 'poolconfig',
      scope: 'loan',
      json: true
    })
  });
  return (await response.json()).rows || [];
};

// Pool statistics (pool-specific)
const fetchPoolStats = async () => {
  const response = await fetch('https://lb.libre.org/v1/chain/get_table_rows', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      code: 'loan',
      table: 'poolstats',
      scope: 'loan',
      json: true
    })
  });
  return (await response.json()).rows || [];
};
```

## Direct Chain Integration

Libre Chain does not currently have JavaScript or Python SDKs. Integration is done directly using Antelope/EOSIO APIs and libraries.

### JavaScript Integration Example

```javascript
// Using eosjs for direct chain interaction
import { Api, JsonRpc } from 'eosjs';
import { JsSignatureProvider } from 'eosjs/dist/eosjs-jssig';

const rpc = new JsonRpc('https://lb.libre.org');
const api = new Api({
    rpc,
    signatureProvider: new JsSignatureProvider(['YOUR_PRIVATE_KEY'])
});

// Get active loans from loan contract
const loans = await rpc.get_table_rows({
    code: 'loan',
    table: 'loan',
    scope: 'loan',
    limit: 1000,
    json: true
});

// Get global statistics
const stats = await rpc.get_table_rows({
    code: 'loan',
    table: 'globalstats',
    scope: 'loan',
    json: true
});

// Borrow USDT from the loan contract
const borrowResult = await api.transact({
    actions: [{
        account: 'loan',
        name: 'borrow',
        authorization: [{
            actor: 'myaccount',
            permission: 'active'
        }],
        data: {
            account: 'myaccount',
            amount: '1000.000000 USDT',
            pool_id: 1
        }
    }]
});

// Repay loan by transferring USDT back to loan contract
// The memo must contain the payback keyword for loan repayment
const repayResult = await api.transact({
    actions: [{
        account: 'usdt.libre',
        name: 'transfer',
        authorization: [{
            actor: 'myaccount',
            permission: 'active'
        }],
        data: {
            from: 'myaccount',
            to: 'loan',
            quantity: '1050.000000 USDT', // principal + interest
            memo: 'payback' // exact memo required for loan repayment
        }
    }]
});

// Cancel a loan (before it's processed)
const cancelResult = await api.transact({
    actions: [{
        account: 'loan',
        name: 'cancelloan',
        authorization: [{
            actor: 'myaccount',
            permission: 'active'
        }],
        data: {
            account: 'myaccount'
        }
    }]
});

// Extend a loan (if pool allows it)
const extendResult = await api.transact({
    actions: [{
        account: 'loan',
        name: 'extendloan',
        authorization: [{
            actor: 'myaccount',
            permission: 'active'
        }],
        data: {
            loan_id: 123
        }
    }]
});
```

## Bitcoin Integration

Libre Chain provides native Bitcoin integration through the Fast BTC system:

### Bitcoin Collateral Integration

```javascript
// Fast BTC and CBTC are used as collateral in the loan system
// Multiple token contracts: btc.libre, cbtc.libre

// Create a vault for holding Bitcoin collateral
const createVaultResult = await api.transact({
    actions: [{
        account: 'loan',
        name: 'createvault',
        authorization: [{
            actor: 'myaccount',
            permission: 'active'
        }],
        data: {
            owner: 'myaccount',
            vault: 'myvault1234'
        }
    }]
});

// Generate Bitcoin address for the vault
const generateAddressResult = await api.transact({
    actions: [{
        account: 'loan',
        name: 'genaddr',
        authorization: [{
            actor: 'myaccount',
            permission: 'active'
        }],
        data: {
            owner: 'myaccount'
        }
    }]
});

// Check vault addresses for Bitcoin tracking
const vaultAddresses = await rpc.get_table_rows({
    code: 'v.libre',
    table: 'accounts',
    scope: 'v.libre',
    limit: 10000,
    json: true
});

// Get BTC price from oracle
const priceFeeds = await rpc.get_table_rows({
    code: 'chainlink', // or 'oracletest' for testnet
    table: 'feed',
    scope: 'chainlink',
    json: true
});

const btcPrice = priceFeeds.rows.find(row => row.pair === 'btcusd')?.price;

// Withdraw Bitcoin from vault (to external Bitcoin address)
const withdrawResult = await api.transact({
    actions: [{
        account: 'loan',
        name: 'withdraw',
        authorization: [{
            actor: 'myaccount',
            permission: 'active'
        }],
        data: {
            account: 'myaccount',
            cbtc_amount: '0.05000000 CBTC',
            btc_address: 'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh'
        }
    }]
});
```

### Liquidation Monitoring

```javascript
// Monitor liquidations
const liquidations = await rpc.get_table_rows({
    code: 'loan',
    table: 'liquidation',
    scope: 'liquidating', // or 'finished'
    limit: 1000,
    json: true
});

// Loan status values from contract:
// 0=In Progress, 1=Warning, 2=At Risk, 3=Liquidating, 4=Liquidated, 5=Repaid, 6=Canceled
const atRiskLoans = loans.rows.filter(loan => loan.status === 2);

// Pool-specific token examples:
// TP (pool 0), TPA (pool 1), TPB (pool 2), TPC (pool 3), TPD (pool 4), TPE (pool 5), TPF (pool 6)
// Each pool has its own TP token for tracking deposits

// Management flags check
const managementFlags = await rpc.get_table_rows({
  code: 'loan',
  table: 'management',
  scope: 'loan',
  json: true
});

// Check if operations are enabled
const isDepositsEnabled = !managementFlags.rows[0]?.disable_deposits;
const isLoansEnabled = !managementFlags.rows[0]?.disable_loans;
const isLiquidationsEnabled = !managementFlags.rows[0]?.disable_liquidations;
```

## Testing & Development

### Local Testnet Setup

```bash
# Start local Libre node
git clone https://gitlab.com/libre-chain/libre-chain-nodes
cd libre-chain-nodes
docker-compose up -d

# Create test accounts
cleos create account eosio alice ALICE_PUBLIC_KEY
cleos create account eosio bob BOB_PUBLIC_KEY

# Deploy contracts
cleos set contract loan ./contracts/loan
```

### Test Data

```bash
# Create test USDT
cleos push action usdt.libre create '["usdt.libre", "1000000.000000 USDT"]' -p usdt.libre

# Issue test tokens
cleos push action usdt.libre issue '["alice", "10000.000000 USDT", "test funds"]' -p usdt.libre

# Create test pool
cleos push action loan createpool '[1, "30 days", 900, "alice"]' -p alice
```

## Security Considerations

### Smart Contract Security

* **Reentrancy protection**: Use proper state management
* **Authorization checks**: Validate all user permissions
* **Overflow protection**: Use safe math libraries
* **Input validation**: Sanitize all external inputs

### API Security

* **Rate limiting**: Implement request throttling
* **Authentication**: Use signed transactions for state changes
* **Input validation**: Validate all API parameters
* **HTTPS only**: Always use encrypted connections

## Resources

### Documentation

* [Antelope Developer Docs](https://docs.antelope.io)
* [Local Testnet Setup](https://gitlab.com/libre-chain/libre-chain-nodes)
* [Libre Blockchain Tools](https://tools.libre.org) - Loan monitoring, contract explorer, account history, Bitcoin bridge tracker
* [Real Implementation Examples](https://github.com/bensig/libre-tools.com) - Source code for tools.libre.org showing actual API usage patterns

### Tools

* **Block Explorer**: [librebloks.io](https://librebloks.io)
* **Libre Blockchain Tools**: [tools.libre.org](https://tools.libre.org)
  * Loan Overview: Monitor USDT loans and BTC collateral
  * Contract Explorer: Browse smart contract data
  * Account History Viewer: Download account history to CSV
  * Bitcoin Bridge Tracker: Track cross-chain transactions
  * Vault Inspector: Check vault information and balances
  * Multisig Proposal Viewer: Browse multisig proposals
* **Tools Source Code**: [GitHub](https://github.com/bensig/libre-tools.com)
* **Wallet**: [Anchor Wallet](https://greymass.com/anchor)
* **CLI Tools**: [cleos documentation](https://docs.antelope.io/cleos)

### Support

* **Developer Discord**: [Join community](https://discord.gg/libre)
* **GitHub Issues**: [Report bugs](https://github.com/libre-chain/libre-chain/issues)
* **Documentation**: [Technical guides](https://gitlab.com/libre-chain/libre-chain-gitbook/-/blob/main/developers/legacy-docs/the-libre-platform/building-on-libre/README.md)

### Legacy Developer Resources

For comprehensive technical documentation, see:

* [Building Smart Contracts](https://gitlab.com/libre-chain/libre-chain-gitbook/-/blob/main/developers/legacy-docs/the-libre-platform/building-on-libre/building-smart-contracts-on-libre.md)
* [API Documentation](https://gitlab.com/libre-chain/libre-chain-gitbook/-/blob/main/developers/legacy-docs/the-libre-platform/building-on-libre/api-docs.md)
* [Testnet Setup](https://gitlab.com/libre-chain/libre-chain-gitbook/-/blob/main/developers/legacy-docs/the-libre-platform/building-on-libre/libre-testnet.md)
* [Developer Tools](https://gitlab.com/libre-chain/libre-chain-gitbook/-/blob/main/developers/legacy-docs/the-libre-platform/building-on-libre/libre-developer-tools.md)

## Contributing

Libre Chain is open source. Contributions welcome:

1. Fork the repository
2. Create feature branch
3. Submit pull request
4. Follow coding standards
5. Include tests for new features

The platform is designed to be **developer-friendly** while maintaining the security and transparency that Bitcoin users expect.
