npm package: @oramp/sdk
Description: A library to simplify interaction with Oramp Protocol
Latest version: 0.8.12

![ts](https://badgen.net/badge/-/TypeScript?icon=typescript&label&labelColor=blue&color=555555)

# Oramp SDK

A TypeScript library that simplifies interaction with the Oramp protocol by abstracting its underlying complexity. The SDK provides type-safe interfaces for all Oramp smart contracts and utilities for common operations.

## Table of Contents

  - [Installation](#installation)
- [Quick Start](#quick-start)
- [Core Concepts](#core-concepts)
  - [Provider](#provider)
  - [Wallet](#wallet)
  - [Oramp Client](#oramp-client)
- [Networks](#networks)
- [Contract Interfaces](#contract-interfaces)
  - [Static Contracts](#static-contracts)
  - [Dynamic Contracts](#dynamic-contracts)
- [Examples](#examples)
  - [Basic Usage](#basic-usage)
  - [Identity Provider Operations](#identity-provider-operations)
  - [Payment Oracle Operations](#payment-oracle-operations)
  - [Escrow Management](#escrow-management)
  - [Matching Engine](#matching-engine)
- [Error Handling](#error-handling)
- [API Reference](#api-reference)

## Installation

```sh
npm install @oramp/sdk
```

## Quick Start

```typescript
import { 
    ENVIRONMENTS, 
    TESTNET_NETWORKS, 
    SUPPORTED_PROVIDERS,
    OrampClient,
    Web3Provider,
    Web3Wallet
} from '@oramp/sdk'

// Initialize provider
const provider = new Web3Provider({
    environment: ENVIRONMENTS.TESTNET,
    network: TESTNET_NETWORKS.BASE_SEPOLIA,
    provider: SUPPORTED_PROVIDERS.JSON_RPC,
    rpcUrl: 'https://base-sepolia.g.alchemy.com/v2/YOUR_API_KEY',
})
await provider.init()

// Initialize wallet
const wallet = new Web3Wallet(provider, 'YOUR_PRIVATE_KEY')
await wallet.init()

// Initialize Oramp client
const oramp = new OrampClient({
    provider,
    verbose: true // Enable verbose logging
})

// Access contracts
const dao = oramp.Dao()
const usdc = oramp.USDC()
const stableCoinAddress = await dao.getStableCoinAddress()
```

## Core Concepts

### Provider

The `Web3Provider` class manages the connection to the blockchain network. It supports:

- **JSON_RPC**: For connecting via RPC endpoints
- **WEB**: For browser-based providers (MetaMask, WalletConnect, etc.)

```typescript
// JSON RPC Provider
const provider = new Web3Provider({
    environment: ENVIRONMENTS.TESTNET,
    network: TESTNET_NETWORKS.BASE_SEPOLIA,
    provider: SUPPORTED_PROVIDERS.JSON_RPC,
    rpcUrl: 'YOUR_RPC_URL',
})

// Web Provider (Browser)
const provider = new Web3Provider({
    environment: ENVIRONMENTS.TESTNET,
    network: TESTNET_NETWORKS.BASE_SEPOLIA,
    provider: SUPPORTED_PROVIDERS.WEB,
    webProvider: window.ethereum, // or your EIP-1193 provider
})
```

### Wallet

The `Web3Wallet` class handles transaction signing. It can be initialized with:

- **Private Key**: For programmatic signing
- **Web Provider**: For browser-based signing (MetaMask, etc.)

```typescript
// With private key
const wallet = new Web3Wallet(provider, '0x...')
await wallet.init()

// With web provider (browser)
const wallet = new Web3Wallet(provider)
await wallet.init()
```

### Oramp Client

The `OrampClient` (exported as `Oramp`) is the main entry point for interacting with Oramp contracts. It automatically initializes all static contracts and provides access to dynamic contracts.

```typescript
const oramp = new OrampClient({
    provider,
    identityProviders: ['0x...'], // Optional: pre-initialize identity providers
    paymentOracles: ['0x...'],     // Optional: pre-initialize payment oracles
    contractAddresses: {           // Optional: override contract addresses (for hardhat/local development)
        Dao: { address: '0x...' }
    },
    verbose: true                  // Optional: enable verbose logging
})
```

## Networks

The SDK supports the following networks:

### Testnet
- `TESTNET_NETWORKS.BASE_SEPOLIA` - Base Sepolia testnet (Chain ID: 84532)

### Mainnet
- `MAINNET_NETWORKS.BASE` - Base mainnet (Chain ID: 8453)

### Local
- `LOCAL_NETWORKS.HARDHAT` - Hardhat local network (Chain ID: 31337)

## Contract Interfaces

### Static Contracts

Static contracts are deployed once per network and are automatically initialized by the Oramp client.

#### OrampDao
The DAO contract manages protocol governance, identity providers, and matching engines.

```typescript
const dao = oramp.Dao()

// Get stable coin address
const usdcAddress = await dao.getStableCoinAddress()

// Get identity provider info
const ipInfo = await dao.getIdentityProviderInfo(identityProviderId)

// Propose identity provider
await dao.proposeIdentityProvider(
    'https://ip.example.com',
    'My Identity Provider',
    wallet.getWallet()
)

// Approve identity provider
await dao.approveIdentityProvider(
    identityProviderId,
    wallet.getWallet()
)

// Check if identity provider is valid
const isValid = await dao.isValidIdentityProvider(identityProviderAddress)
```

#### OrampOracleManager
Manages payment oracles and their configurations.

```typescript
const oracleManager = oramp.OracleManager()

// Get oracle address by ID
const oracleAddress = await oracleManager.getOracleAddress(oracleId)

// Check if address is valid oracle
const isValid = await oracleManager.isValidOracleAddress(address)

// Add payment oracle (requires DAO permissions)
await oracleManager.addPaymentOracle(
    countryCode,
    network,
    stakeSupply,
    minRequiredStake,
    alephHash,
    oracleUrl,
    proposal,
    wallet.getWallet()
)
```

#### OrampEscrowManager
Manages payment order escrows and matching.

```typescript
const escrow = oramp.EscrowManager()

// Post buy order
await escrow.postBuyOrder(
    messageObject,
    price,
    quantity,
    metadata,
    wallet.getWallet()
)

// Post sell order
await escrow.postSellOrder(
    messageObject,
    price,
    quantity,
    metadata,
    wallet.getWallet()
)

// Match payment orders
await escrow.matchPaymentOrder(
    sellOrderId,
    buyOrderId,
    matchedQuantity,
    wallet.getWallet()
)

// Get order details
const order = await escrow.getMyOrder(orderId)
```

#### OrampDisputeResolver
Handles dispute resolution for payment orders.

```typescript
const disputeResolver = oramp.DisputeResolver()

// Report dispute
await disputeResolver.reportDispute(
    escrowId,
    reportState,
    wallet.getWallet()
)
```

#### USDC
ERC20 token interface for USDC (or Mock_USDC on testnet).

```typescript
const usdc = oramp.USDC()

// Get balance
const balance = await usdc.balanceOf(address)

// Approve spending
await usdc.approve(
    spender,
    amount,
    wallet.getWallet()
)

// Transfer tokens
await usdc.transfer(
    to,
    amount,
    wallet.getWallet()
)

// Get free tokens (testnet only)
if (network === TESTNET_NETWORKS.BASE_SEPOLIA) {
    await usdc.getFree(
        recipient,
        amount,
        wallet.getWallet()
    )
}
```

### Dynamic Contracts

Dynamic contracts are deployed per instance and must be initialized with their addresses.

#### OrampIdentityProvider
Manages identity verification and passport issuance.

```typescript
// Initialize identity provider
oramp.initIdentityProvider(identityProviderAddress)

// Or get it directly (auto-initializes if needed)
const ip = oramp.getIdentityProvider(identityProviderAddress)

// Get passport info
const passport = await ip.getPassport(walletAddress)

// Issue passport
await ip.issuePassport(
    target,
    countryCode,
    did,
    wallet.getWallet()
)

// Renew passport
await ip.renewPassport(target, wallet.getWallet())

// Activate passport
await ip.activatePassport(target, wallet.getWallet())

// Blacklist/whitelist
await ip.blacklist(wallet, true, wallet.getWallet())
await ip.whitelist(handler, true, wallet.getWallet())
```

#### OrampPaymentOracle
Manages payment verification and staking.

```typescript
// Initialize payment oracle
oramp.initPaymentOracle(paymentOracleAddress)

// Or get it directly
const oracle = oramp.getPaymentOracle(paymentOracleAddress)

// Get oracle info
const info = await oracle.getMyInfo()

// Get stake information
const totalSupply = await oracle.getTotalStakeSupply()
const currentStakes = await oracle.getCurrentStakes(identityProvider)
const myStake = await oracle.getMyStakeSize(identityProvider, stakeHolder)

// Stake tokens
await oracle.stake(
    identityProvider,
    stakeAmount,
    wallet.getWallet()
)

// Withdraw stake
await oracle.withdraw(
    identityProvider,
    stakeAmount,
    wallet.getWallet()
)

// Add stake pool
await oracle.addStakePool(
    identityProvider,
    wallet.getWallet()
)
```

## Examples

### Basic Usage

```typescript
import { 
    ENVIRONMENTS, 
    TESTNET_NETWORKS, 
    SUPPORTED_PROVIDERS,
    OrampClient,
    Web3Provider,
    Web3Wallet,
    OrampError
} from '@oramp/sdk'

async function main() {
    // Setup
    const provider = new Web3Provider({
        environment: ENVIRONMENTS.TESTNET,
        network: TESTNET_NETWORKS.BASE_SEPOLIA,
        provider: SUPPORTED_PROVIDERS.JSON_RPC,
        rpcUrl: process.env.RPC_URL!,
    })
    await provider.init()

    const wallet = new Web3Wallet(provider, process.env.PRIVATE_KEY!)
    await wallet.init()

    const oramp = new OrampClient({ provider, verbose: true })

    // Interact with contracts
    try {
        const dao = oramp.Dao()
        const usdcAddress = await dao.getStableCoinAddress()
        console.log('USDC Address:', usdcAddress)

        const usdc = oramp.USDC()
        const balance = await usdc.balanceOf(await wallet.getCurrentSigner())
        console.log('Balance:', balance.toString())
    } catch (e) {
        if (e instanceof OrampError) {
            console.error('Oramp Error:', e.message)
        } else {
            console.error('Error:', e)
        }
    }
}
```

### Identity Provider Operations

```typescript
// Initialize identity provider
const identityProviderAddress = '0x...'
oramp.initIdentityProvider(identityProviderAddress)

const ip = oramp.getIdentityProvider(identityProviderAddress)

// Check passport status
const passport = await ip.getPassport(userAddress)
console.log('Passport State:', passport.state)
console.log('Country:', passport.country)
console.log('DID:', passport.did)

// Issue new passport
await ip.issuePassport(
    userAddress,
    'USA', // ISO3166 country code
    didBytes,
    wallet.getWallet()
)
```

### Payment Oracle Operations

```typescript
// Initialize payment oracle
const oracleAddress = '0x...'
oramp.initPaymentOracle(oracleAddress)

const oracle = oramp.getPaymentOracle(oracleAddress)

// Get oracle information
const info = await oracle.getMyInfo()
console.log('Oracle ID:', info.oracleId)
console.log('Country:', info.country)
console.log('Network:', info.network)
console.log('URL:', info.oracleUrl)

// Check stake pool
const identityProvider = '0x...'
const totalSupply = await oracle.getTotalStakeSupply()
const currentStakes = await oracle.getCurrentStakes(identityProvider)
console.log(`Stakes: ${currentStakes}/${totalSupply}`)

// Stake tokens
await oracle.stake(
    identityProvider,
    '1000000000', // 1000 USDC (6 decimals)
    wallet.getWallet()
)
```

### Escrow Management

```typescript
const escrow = oramp.EscrowManager()

// Post a sell order
const sellOrder = await escrow.postSellOrder(
    JSON.stringify({ /* message object */ }),
    '1000000', // price
    '5000000', // quantity
    {
        paymentHandler: paymentHandlerAddress,
        identityProvider: identityProviderAddress,
        isTrader: false
    },
    wallet.getWallet()
)

console.log('Sell Order ID:', sellOrder.events[0]?.orderId)

// Post a buy order
const buyOrder = await escrow.postBuyOrder(
    JSON.stringify({ /* message object */ }),
    '1000000',
    '5000000',
    {
        paymentHandler: paymentHandlerAddress,
        identityProvider: identityProviderAddress,
        isTrader: false
    },
    wallet.getWallet()
)

// Match orders
await escrow.matchPaymentOrder(
    sellOrderId,
    buyOrderId,
    matchedQuantity,
    wallet.getWallet()
)
```

### Matching Engine

```typescript
import { MatchingEngine, OrderSide } from '@oramp/sdk'

// Initialize matching engine
const matchingEngine = new MatchingEngine({
    network: TESTNET_NETWORKS.BASE_SEPOLIA,
    provider: provider.getProvider(),
    countryCode: 'USA',
    paymentNetwork: keccak256(toUtf8Bytes('Zelle'))
})
await matchingEngine.init()

// Get matching engine info
const meInfo = await matchingEngine.getInfo()
console.log('ME Name:', meInfo.name)
console.log('ME Address:', meInfo.address)

// Get available orders
const orders = await matchingEngine.getOrders()
console.log('Bids:', orders.bids)
console.log('Asks:', orders.asks)

// Get price quote
const price = await matchingEngine.getPrice(
    paymentHandlerAddress,
    identityProviderAddress,
    1000000 // quantity
)
console.log('Bid Price:', price.bidPrice)
console.log('Ask Price:', price.askPrice)

// Check if order can be matched
const matchResult = await matchingEngine.getMatchResult(
    OrderSide.buyer,
    paymentHandlerAddress,
    identityProviderAddress,
    1000000,
    1000000
)
console.log('Is Matched:', matchResult.isMatched)
console.log('Matched Quantity:', matchResult.quantity)
console.log('Matched Price:', matchResult.price)
```

## Error Handling

The SDK uses a custom `OrampError` class for error handling:

```typescript
import { OrampError } from '@oramp/sdk'

try {
    await dao.approveIdentityProvider(id, wallet.getWallet())
} catch (e) {
    if (e instanceof OrampError) {
        console.error('Error Code:', e.code)
        console.error('Error Message:', e.message)
        console.error('Error Details:', e.details)
    } else {
        console.error('Unknown error:', e)
    }
}
```

## API Reference

### Core Classes

- `OrampClient` - Main client for interacting with Oramp protocol
- `Web3Provider` - Blockchain provider abstraction
- `Web3Wallet` - Wallet for signing transactions
- `MatchingEngine` - Matching engine client

### Constants

- `ENVIRONMENTS` - Environment types (TESTNET, MAINNET)
- `TESTNET_NETWORKS` - Testnet network options
- `MAINNET_NETWORKS` - Mainnet network options
- `LOCAL_NETWORKS` - Local network options
- `SUPPORTED_PROVIDERS` - Provider types (JSON_RPC, WEB)
- `ISO3166Countries` - ISO 3166 country codes

### Types

- `OrampEvent` - Event emitted from contracts
- `OrampTransaction` - Transaction result with events
- `AddressLike` - Address type (string or Address)
- `BigNumberish` - Big number type
- `BytesLike` - Bytes type

For detailed API documentation, see the TypeScript definitions in the `build/esm` directory.