> ## Documentation Index
> Fetch the complete documentation index at: https://docs.stateset.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Finance API

> Trade finance, invoice factoring, and lending powered by native stablecoins and smart contracts

<Info>
  **Enterprise Access**: Contact [sales@stateset.com](mailto:sales@stateset.com) for access to advanced finance features and higher limits.
</Info>

# Finance API: Revolutionizing Trade Finance

StateSet's Finance API transforms traditional trade finance by leveraging blockchain technology and stablecoins to provide instant liquidity, automated compliance, and global accessibility. Eliminate weeks of waiting and mountains of paperwork with our programmable finance infrastructure.

## 🌟 Why StateSet Finance?

<CardGroup cols={3}>
  <Card title="Instant Liquidity" icon="bolt">
    Factor invoices and access capital in minutes, not months
  </Card>

  <Card title="Global Reach" icon="globe">
    Finance trade in 195+ countries with built-in compliance
  </Card>

  <Card title="Smart Automation" icon="robot">
    AI-powered risk assessment and automated payment flows
  </Card>
</CardGroup>

## 📊 Impact Metrics

<div className="grid grid-cols-2 md:grid-cols-4 gap-4 my-8">
  <div className="bg-gradient-to-br from-blue-50 to-blue-100 dark:from-blue-900/20 dark:to-blue-800/20 p-6 rounded-xl text-center transform hover:scale-105 transition-transform">
    <div className="text-3xl font-bold text-blue-600 dark:text-blue-400">\$500M+</div>
    <div className="text-sm text-gray-600 dark:text-gray-400 mt-2">Trade Financed</div>
  </div>

  <div className="bg-gradient-to-br from-green-50 to-green-100 dark:from-green-900/20 dark:to-green-800/20 p-6 rounded-xl text-center transform hover:scale-105 transition-transform">
    <div className="text-3xl font-bold text-green-600 dark:text-green-400">2 min</div>
    <div className="text-sm text-gray-600 dark:text-gray-400 mt-2">Avg. Funding Time</div>
  </div>

  <div className="bg-gradient-to-br from-purple-50 to-purple-100 dark:from-purple-900/20 dark:to-purple-800/20 p-6 rounded-xl text-center transform hover:scale-105 transition-transform">
    <div className="text-3xl font-bold text-purple-600 dark:text-purple-400">2.5%</div>
    <div className="text-sm text-gray-600 dark:text-gray-400 mt-2">Avg. Discount Rate</div>
  </div>

  <div className="bg-gradient-to-br from-orange-50 to-orange-100 dark:from-orange-900/20 dark:to-orange-800/20 p-6 rounded-xl text-center transform hover:scale-105 transition-transform">
    <div className="text-3xl font-bold text-orange-600 dark:text-orange-400">99.8%</div>
    <div className="text-sm text-gray-600 dark:text-gray-400 mt-2">Repayment Rate</div>
  </div>
</div>

## 🚀 Quick Start

<Tabs>
  <Tab title="Invoice Factoring">
    ```javascript theme={null}
    import { StateSet } from '@stateset/sdk';

    const stateset = new StateSet({ apiKey: 'sk_test_...' });

    // Factor an invoice for instant liquidity
    const factoring = await stateset.finance.factorInvoice({
      invoice_id: 'inv_12345',
      amount: '50000.00',
      discount_rate: 0.025, // 2.5% discount
      buyer_id: 'buyer_abc123',
      recourse: false // Non-recourse factoring
    });

    console.log(`Received ${factoring.advance_amount} USDC instantly`);
    // Output: Received 48750.00 USDC instantly
    ```
  </Tab>

  <Tab title="Purchase Order Finance">
    ```javascript theme={null}
    // Finance a purchase order before fulfillment
    const poFinancing = await stateset.finance.financePurchaseOrder({
      po_id: 'po_67890',
      amount: '100000.00',
      supplier_id: 'supplier_xyz789',
      delivery_date: '2024-08-15',
      collateral_type: 'buyer_guarantee'
    });

    console.log(`PO financed: ${poFinancing.funded_amount} USDC`);
    // Funds released to supplier for production
    ```
  </Tab>

  <Tab title="Asset-Based Lending">
    ```javascript theme={null}
    // Borrow against tokenized assets
    const loan = await stateset.finance.createLoan({
      collateral: {
        type: 'tokenized_inventory',
        value: '150000.00',
        token_ids: ['inv_token_123', 'inv_token_456']
      },
      loan_amount: '100000.00',
      term_days: 90,
      interest_rate: 0.08 // 8% APR
    });

    console.log(`Loan approved: ${loan.id}`);
    // Instant USDC disbursement
    ```
  </Tab>
</Tabs>

## 💼 Product Suite

### Invoice Factoring

Transform outstanding invoices into immediate working capital with our AI-powered factoring platform.

<AccordionGroup>
  <Accordion title="How It Works" icon="gear">
    1. **Submit Invoice**: Upload or connect your invoice via API
    2. **Instant Assessment**: AI evaluates buyer creditworthiness in seconds
    3. **Get Offer**: Receive competitive factoring rate (typically 2-5%)
    4. **Instant Payment**: Accept offer and receive USDC immediately
    5. **We Collect**: We handle collection from your buyer at maturity
  </Accordion>

  <Accordion title="Benefits" icon="star">
    * ⚡ **Instant Liquidity**: Access 95-98% of invoice value immediately
    * 💰 **Better Rates**: 2-5% vs traditional 10-30%
    * 🌍 **Global Coverage**: Factor invoices from buyers worldwide
    * 🔒 **Non-Recourse Options**: Transfer credit risk to us
    * 🤖 **Automated Process**: No paperwork or manual approvals
  </Accordion>

  <Accordion title="Eligibility" icon="check-circle">
    * Invoice amount: $1,000 - $10,000,000
    * Buyer must be a registered business
    * Invoice must be for completed goods/services
    * Maximum term: 120 days
    * No previous factoring on same invoice
  </Accordion>
</AccordionGroup>

### Purchase Order Financing

Fund production and fulfill large orders without depleting working capital.

<AccordionGroup>
  <Accordion title="Use Cases" icon="briefcase">
    * **Manufacturing**: Fund raw materials and production costs
    * **Wholesale**: Purchase inventory for large orders
    * **Import/Export**: Finance international trade transactions
    * **Seasonal Business**: Handle demand spikes without cash strain
  </Accordion>

  <Accordion title="Smart Contract Protection" icon="shield">
    * Funds held in escrow until milestones met
    * Automatic release based on IoT/delivery confirmation
    * Multi-party signatures for large transactions
    * Dispute resolution via on-chain arbitration
  </Accordion>
</AccordionGroup>

### Dynamic Discounting

Optimize payment timing between buyers and suppliers with win-win early payment discounts.

<CardGroup cols={2}>
  <Card title="For Buyers" icon="shopping-cart">
    * Earn 15-30% APR equivalent returns
    * Strengthen supplier relationships
    * Improve supply chain resilience
  </Card>

  <Card title="For Suppliers" icon="truck">
    * Access early payment on demand
    * Predictable cash flow
    * Lower financing costs
  </Card>
</CardGroup>

## 💵 Invoice Factoring API

### Factor Invoice

```http theme={null}
POST /v1/finance/invoices/factor
```

**Request Body:**

```json theme={null}
{
  "invoice_id": "inv_12345",
  "amount": "50000.00",
  "currency": "USDC",
  "discount_rate": 0.025,
  "buyer": {
    "id": "did:stateset:buyer:abc123",
    "credit_rating": "AAA",
    "payment_history": "excellent"
  },
  "terms": {
    "net_days": 30,
    "due_date": "2024-07-25"
  },
  "recourse": false
}
```

**Response:**

```json theme={null}
{
  "factoring_id": "fact_8y4mQr5oP2",
  "invoice_id": "inv_12345",
  "status": "FUNDED",
  "advance_amount": "48750.00",
  "discount_amount": "1250.00",
  "discount_rate": 0.025,
  "funded_at": "2024-06-25T12:05:00Z",
  "maturity_date": "2024-07-25T23:59:59Z",
  "transaction_hash": "0x742d35Cc6634C0532925a3b8D097C00D4dfece08"
}
```

### Get Factoring Options

```http theme={null}
GET /v1/finance/invoices/{invoice_id}/factoring-options
```

**Response:**

```json theme={null}
{
  "invoice_id": "inv_12345",
  "amount": "50000.00",
  "options": [
    {
      "provider": "StateSet Pool Alpha",
      "discount_rate": 0.02,
      "advance_amount": "49000.00",
      "funding_time": "instant",
      "recourse": false,
      "rating": "AAA"
    },
    {
      "provider": "Institutional Lender",
      "discount_rate": 0.015,
      "advance_amount": "49250.00",
      "funding_time": "1_hour",
      "recourse": false,
      "rating": "AA+"
    }
  ],
  "risk_assessment": {
    "buyer_score": 95,
    "payment_probability": 0.99,
    "recommended_rate": 0.02
  }
}
```

### Track Factored Invoice

```http theme={null}
GET /v1/finance/factoring/{factoring_id}
```

**Response:**

```json theme={null}
{
  "id": "fact_8y4mQr5oP2",
  "invoice_id": "inv_12345",
  "status": "ACTIVE",
  "amount": "50000.00",
  "advance_paid": "48750.00",
  "discount": "1250.00",
  "days_remaining": 15,
  "payment_tracking": {
    "buyer_notified": true,
    "payment_link_sent": true,
    "reminder_sent": false
  },
  "timeline": [
    {
      "event": "FACTORED",
      "timestamp": "2024-06-25T12:05:00Z",
      "amount": "48750.00"
    },
    {
      "event": "BUYER_NOTIFIED",
      "timestamp": "2024-06-25T12:06:00Z"
    }
  ]
}
```

## 📦 Purchase Order Financing API

### Finance Purchase Order

```http theme={null}
POST /v1/finance/purchase-orders/finance
```

**Request Body:**

```json theme={null}
{
  "purchase_order_id": "po_67890",
  "supplier_id": "did:stateset:supplier:xyz789",
  "buyer_id": "did:stateset:buyer:abc123", 
  "amount": "100000.00",
  "currency": "USDC",
  "financing_terms": {
    "advance_percentage": 0.8,
    "fee_percentage": 0.03,
    "payment_terms": "net_60"
  },
  "delivery_terms": {
    "incoterm": "FOB",
    "expected_delivery": "2024-08-15",
    "delivery_address": "123 Main St, San Francisco, CA"
  },
  "collateral": {
    "type": "purchase_order",
    "insurance_required": true
  }
}
```

**Response:**

```json theme={null}
{
  "financing_id": "pof_9x3kLm8nR5",
  "purchase_order_id": "po_67890",
  "status": "APPROVED",
  "advance_amount": "80000.00",
  "total_fees": "3000.00",
  "funding_schedule": [
    {
      "milestone": "ORDER_CONFIRMED",
      "amount": "40000.00",
      "funded_at": "2024-06-25T12:10:00Z"
    },
    {
      "milestone": "PRODUCTION_COMPLETE",
      "amount": "40000.00",
      "estimated_date": "2024-08-01"
    }
  ],
  "repayment_due": "2024-10-15",
  "contract_address": "stateset1contract456..."
}
```

### Get Financing Options

```http theme={null}
GET /v1/finance/purchase-orders/{po_id}/financing-options
```

**Response:**

```json theme={null}
{
  "purchase_order_id": "po_67890",
  "amount": "100000.00",
  "supplier_rating": "A+",
  "buyer_rating": "AAA",
  "financing_options": [
    {
      "provider": "StateSet Capital",
      "advance_percentage": 0.85,
      "fee_rate": 0.025,
      "approval_time": "instant",
      "requirements": ["insurance", "shipping_docs"]
    },
    {
      "provider": "Trade Finance Pool", 
      "advance_percentage": 0.8,
      "fee_rate": 0.02,
      "approval_time": "2_hours",
      "requirements": ["credit_check", "collateral"]
    }
  ],
  "risk_factors": {
    "supplier_history": "excellent",
    "product_category": "low_risk",
    "shipping_route": "established",
    "insurance_available": true
  }
}
```

## 🏦 Collateralized Lending API

### Create Loan Request

```http theme={null}
POST /v1/finance/loans/request
```

**Request Body:**

```json theme={null}
{
  "borrower_id": "did:stateset:borrower:def456",
  "loan_amount": "25000.00",
  "currency": "USDC",
  "loan_purpose": "working_capital",
  "term_months": 12,
  "collateral": [
    {
      "type": "cryptocurrency",
      "asset": "STATE",
      "amount": "50000.00",
      "current_value": "50000.00",
      "ltv_ratio": 0.5
    },
    {
      "type": "invoice",
      "asset_id": "inv_78901",
      "face_value": "15000.00",
      "ltv_ratio": 0.8
    }
  ],
  "requested_rate": 0.08
}
```

**Response:**

```json theme={null}
{
  "loan_id": "loan_5z8nPq3oW7",
  "status": "PENDING_APPROVAL",
  "requested_amount": "25000.00",
  "approved_amount": "25000.00",
  "interest_rate": 0.075,
  "term_months": 12,
  "monthly_payment": "2256.50",
  "total_collateral_value": "65000.00",
  "ltv_ratio": 0.38,
  "approval_time": "instant",
  "funds_available": "2024-06-25T12:15:00Z"
}
```

### Loan Management

```http theme={null}
POST /v1/finance/loans/{loan_id}/drawdown
```

**Request Body:**

```json theme={null}
{
  "amount": "25000.00",
  "destination_wallet": "stateset1borrower123...",
  "purpose": "Inventory purchase for Q3 orders"
}
```

**Response:**

```json theme={null}
{
  "drawdown_id": "draw_4k7mLx9nQ2",
  "loan_id": "loan_5z8nPq3oW7",
  "amount": "25000.00",
  "funded_at": "2024-06-25T12:20:00Z",
  "transaction_hash": "0x9f2e45Bb8734C1523456a7b9E087F00E4dfebe19",
  "repayment_schedule": [
    {
      "payment_number": 1,
      "due_date": "2024-07-25",
      "principal": "1923.17",
      "interest": "333.33",
      "total": "2256.50"
    }
  ]
}
```

## 🎯 Automated Risk Management

### Credit Scoring

```typescript theme={null}
// Real-time credit assessment
const creditScore = await client.finance.assessCredit({
  entity_id: 'did:stateset:company:abc123',
  factors: [
    'payment_history',
    'financial_statements', 
    'industry_trends',
    'blockchain_activity'
  ]
});

// Response
{
  "entity_id": "did:stateset:company:abc123",
  "credit_score": 785,
  "rating": "A+",
  "factors": {
    "payment_history": {
      "score": 95,
      "on_time_percentage": 0.98,
      "avg_days_early": 2.3
    },
    "financial_health": {
      "score": 88,
      "debt_to_equity": 0.35,
      "current_ratio": 2.1
    },
    "blockchain_activity": {
      "score": 92,
      "transaction_volume": "500000.00",
      "network_reputation": "excellent"
    }
  },
  "recommended_limits": {
    "factoring": "100000.00",
    "lending": "50000.00",
    "trade_finance": "250000.00"
  }
}
```

### Dynamic Pricing

```typescript theme={null}
// Market-driven interest rates
const pricing = await client.finance.getPricing({
  product: 'invoice_factoring',
  amount: '50000.00',
  term_days: 30,
  risk_profile: {
    buyer_rating: 'AAA',
    seller_rating: 'A+',
    industry: 'technology'
  }
});

// Response
{
  "base_rate": 0.02,
  "risk_premium": 0.005,
  "final_rate": 0.025,
  "pricing_factors": {
    "market_conditions": {
      "liquidity": "high",
      "demand": "moderate",
      "adjustment": -0.002
    },
    "counterparty_risk": {
      "buyer_score": 95,
      "seller_score": 88,
      "adjustment": 0.003
    },
    "product_risk": {
      "default_rate": 0.001,
      "recovery_rate": 0.98,
      "adjustment": 0.002
    }
  },
  "expires_at": "2024-06-25T13:00:00Z"
}
```

## 🌍 Cross-Border Trade Finance

### Letters of Credit

```typescript theme={null}
// Digital letter of credit
const lc = await client.finance.createLetterOfCredit({
  importer: 'did:stateset:importer:usa123',
  exporter: 'did:stateset:exporter:chn456',
  amount: '500000.00',
  currency: 'USDC',
  goods_description: '1000 units Model X widgets',
  shipping_terms: {
    incoterm: 'CIF',
    port_of_loading: 'Shanghai',
    port_of_discharge: 'Los Angeles',
    latest_shipment: '2024-08-15'
  },
  documents_required: [
    'commercial_invoice',
    'bill_of_lading',
    'packing_list',
    'certificate_of_origin'
  ],
  expiry_date: '2024-09-30'
});

// Automated document verification via oracles
const verification = await client.finance.verifyDocuments(lc.id, {
  documents: uploadedDocs,
  verify_authenticity: true,
  check_compliance: true
});
```

### Trade Credit Insurance

```typescript theme={null}
// Parametric insurance for trade finance
const insurance = await client.finance.createTradeInsurance({
  policy_type: 'trade_credit',
  insured_amount: '500000.00',
  coverage: {
    non_payment: true,
    political_risk: true,
    currency_inconvertibility: false
  },
  buyer: 'did:stateset:buyer:xyz789',
  premium_rate: 0.015,
  coverage_period: {
    start: '2024-07-01',
    end: '2024-12-31'
  },
  payment_method: 'usdc'
});

// Smart contract automatically pays claims
if (paymentOverdue > 90 && verifiedDefault) {
  await insurance.contract.payoutClaim({
    amount: insuredAmount,
    recipient: beneficiaryWallet
  });
}
```

## 📊 Liquidity Pools & Yield

### Liquidity Provider Program

```typescript theme={null}
// Earn yield by providing liquidity
const liquidityPosition = await client.finance.addLiquidity({
  pool: 'invoice_factoring_pool',
  amount: '100000.00',
  currency: 'USDC',
  lock_period: '30_days',
  min_yield: 0.08 // 8% APR minimum
});

// Response
{
  "position_id": "lp_3k8mRx7nQ9",
  "pool": "invoice_factoring_pool",
  "amount_deposited": "100000.00",
  "shares_minted": "100000.00",
  "current_apr": 0.095,
  "projected_yield_30d": "791.67",
  "risk_level": "low",
  "withdraw_available": "2024-07-25T12:00:00Z"
}
```

### Yield Farming

```typescript theme={null}
// Stake LP tokens for additional rewards
const farming = await client.finance.stakeLPTokens({
  lp_token_id: 'lp_3k8mRx7nQ9',
  farm: 'state_rewards_farm',
  amount: '100000.00'
});

// Earn both:
// 1. Base APR from factoring fees (9.5%)
// 2. STATE token rewards (3.2% additional)
// Total APY: 12.7%
```

## 🔐 Security & Compliance

### Multi-Signature Workflows

```typescript theme={null}
// Large transactions require multiple approvals
const largeLoan = await client.finance.createLoan({
  amount: '1000000.00', // $1M loan
  requires_multisig: true,
  approvers: [
    'did:stateset:officer:cfo',
    'did:stateset:officer:risk',
    'did:stateset:board:chair'
  ],
  threshold: 2 // 2 of 3 signatures required
});

// Approval workflow
for (const approver of requiredApprovers) {
  await client.finance.signApproval(largeLoan.id, {
    signer: approver,
    decision: 'approve',
    notes: 'Reviewed financials and risk assessment'
  });
}
```

### Compliance Monitoring

```typescript theme={null}
// Real-time compliance checking
const compliance = await client.compliance.monitor({
  transaction_id: 'txn_abc123',
  checks: [
    'sanctions_screening',
    'aml_monitoring', 
    'kyc_verification',
    'regulatory_limits'
  ],
  jurisdictions: ['US', 'EU', 'UK']
});

// Automatic reporting
if (compliance.flagged) {
  await client.compliance.generateSAR({
    transaction_id: compliance.transaction_id,
    reason: compliance.flag_reason,
    submit_to: ['fincen', 'eu_authorities']
  });
}
```

## 🚀 Advanced Features

### Parametric Insurance

```typescript theme={null}
// Smart contract insurance
const insurance = await client.finance.createParametricInsurance({
  trigger_type: 'oracle_data',
  coverage_amount: '100000.00',
  parameters: {
    weather_station: 'NOAA_SF_001',
    trigger_condition: 'rainfall > 5_inches_24h',
    measurement_period: '2024-07-01 to 2024-07-31'
  },
  premium: '2500.00',
  automatic_payout: true
});

// Automatic claim payment when conditions met
if (oracleData.rainfall > triggeLevell) {
  insurance.contract.payout();
}
```

### AI-Powered Analytics

```typescript theme={null}
// Machine learning risk assessment
const riskAnalysis = await client.finance.analyzeRisk({
  entity: 'did:stateset:company:xyz',
  analysis_type: 'comprehensive',
  data_sources: [
    'financial_statements',
    'payment_history',
    'market_data',
    'social_sentiment',
    'supply_chain_data'
  ]
});

// Response includes ML-generated insights
{
  "risk_score": 78,
  "confidence": 0.94,
  "key_factors": [
    "Strong payment history (98% on-time)",
    "Growing market share in sector",
    "Diversified supplier base"
  ],
  "risk_factors": [
    "High customer concentration (top 3 = 60% revenue)",
    "Increasing raw material costs"
  ],
  "recommended_limits": {
    "factoring": "250000.00",
    "lending": "100000.00"
  }
}
```

## 📈 Performance Metrics

### By the Numbers

| Metric                | Value      | Industry Comparison |
| --------------------- | ---------- | ------------------- |
| Funding Speed         | 2 minutes  | Banks: 3-6 months   |
| Transaction Cost      | \$0.01     | Banks: \$25-100     |
| Default Rate          | 0.1%       | Industry: 2-5%      |
| Borrower Satisfaction | 98%        | Banks: 65%          |
| API Uptime            | 99.99%     | Enterprise standard |
| Processing Capacity   | 10,000 TPS | Unlimited scale     |

### Success Stories

**Manufacturing SME in Vietnam**

* Needed \$500K to fulfill large US order
* Funded in 3 minutes vs 3 months traditional
* Saved \$15K in fees (3% vs 6% bank rate)
* Scaled production 300% in 6 months

**Tech Startup in Nigeria**

* Factored invoices for immediate cash flow
* Accessed capital without US banking relationship
* Reduced payment cycles from 90 to 2 days
* Reinvested in R\&D and hiring

## 🔗 Related APIs

* [Invoices API](/stateset-commerce-api-reference/invoices) - Create and manage invoices
* [Purchase Orders API](/stateset-commerce-api-reference/purchaseorders) - PO management
* [Loans API](/stateset-commerce-api-reference/loans) - Lending operations
* [USDC Integration](/stateset-commerce-api-reference/usdc) - Native USDC support
* [Orders API](/stateset-commerce-api-reference/orders) - Order management

***

*Ready to access capital? [Start your application →](https://app.stateset.network/finance)*
