Integration Guide for Developers
This guide will help you integrate your application with the Osito Protocol. Whether you're building a DApp that needs to interact with Osito or a project looking to leverage Osito's lending features, this document provides the necessary steps and best practices.
Prerequisites
Before integrating with Osito Protocol, ensure you have:
- Basic understanding of Ethereum/Berachain development
- Experience with Web3 libraries like ethers.js or web3.js
- Familiarity with smart contract interactions
- Understanding of ERC-20 token standards
Integration Options
There are three main ways to integrate with Osito Protocol:
1. Direct Smart Contract Interaction
For applications that need maximum flexibility and customization:
- Interact directly with Osito smart contracts
- Implement custom UI and business logic
- Handle all contract events and state changes yourself
2. Osito SDK
For applications that want simplified integration:
- Use our JavaScript/TypeScript SDK
- Simplified methods for all protocol interactions
- Built-in error handling and state management
- Types and documentation included
3. Subgraph Integration
For applications that need historical data and analytics:
- Query the Osito subgraph for protocol data
- Access historical transactions and protocol state
- Build custom analytics and visualizations
Setting Up the SDK
# Install the SDK
npm install @osito-protocol/sdk
# or with yarn
yarn add @osito-protocol/sdk
Basic initialization:
import { OsitoSDK } from '@osito-protocol/sdk';
import { ethers } from 'ethers';
// Initialize with ethers provider (browser)
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
// Create SDK instance
const ositoSDK = new OsitoSDK({
provider,
signer,
network: 'berachain', // or 'berachain-testnet'
});
// Check if SDK is ready
const isInitialized = await ositoSDK.isInitialized();
console.log(`SDK Initialized: ${isInitialized}`);
Common Integration Patterns
1. Check Token Eligibility
Before offering Osito Protocol functionality for a token, check if it's eligible:
const isEligible = await ositoSDK.isTokenEligible('0xTokenAddress');
if (isEligible) {
// Show Osito options in your UI
} else {
// Hide Osito options or show ineligibility message
}
2. Display Borrowing Capacity
Show users how much they can borrow against their tokens:
// Get token information
const tokenInfo = await ositoSDK.getTokenInfo('0xTokenAddress');
// Calculate borrowing capacity for user's tokens
const userTokenBalance = await ositoSDK.getTokenBalance('0xTokenAddress', userAddress);
const borrowCapacity = await ositoSDK.calculateBorrowCapacity('0xTokenAddress', userTokenBalance);
// Display in UI
console.log(`You can borrow up to ${ethers.utils.formatEther(borrowCapacity)} wBERA`);
3. Implement Borrowing Flow
Complete flow for a borrowing transaction:
// Step 1: Approve token transfer
const tokenAmount = ethers.utils.parseUnits('100', tokenDecimals);
await ositoSDK.approveToken('0xTokenAddress', tokenAmount);
// Step 2: Deposit collateral
await ositoSDK.depositCollateral('0xTokenAddress', tokenAmount);
// Step 3: Borrow wBERA
const borrowAmount = ethers.utils.parseEther('10'); // 10 wBERA
await ositoSDK.borrow('0xTokenAddress', borrowAmount);
// Step 4: Track transaction status
ositoSDK.on('TransactionStatus', (status) => {
console.log(`Transaction: ${status.type}, Status: ${status.status}`);
if (status.status === 'confirmed') {
// Update UI to show successful borrowing
}
});
4. Monitor Position Health
Keep users informed about their position health:
// Initial check
const position = await ositoSDK.getBorrowPosition(userAddress, '0xTokenAddress');
const healthFactor = position.healthFactor;
// Set up real-time monitoring
ositoSDK.on('PositionUpdate', (updatedPosition) => {
if (updatedPosition.healthFactor < 1.1) {
// Alert user about liquidation risk
}
});
5. Display Protocol Stats
Show protocol statistics in your application:
// Get global stats
const stats = await ositoSDK.getProtocolStats();
console.log(`Total Value Locked: ${stats.tvl} wBERA`);
console.log(`Total Borrowed: ${stats.totalBorrowed} wBERA`);
// Get token-specific stats
const tokenStats = await ositoSDK.getTokenStats('0xTokenAddress');
console.log(`Utilization Rate: ${tokenStats.utilizationRate}%`);
console.log(`Interest Rate: ${tokenStats.interestRate}%`);
Best Practices
- Always use async/await with try/catch blocks for handling contract interactions
- Implement proper error handling with user-friendly error messages
- Use event listeners to provide real-time updates on transaction status
- Include loading states for all blockchain interactions
- Implement confirmation steps for all transactions
- Provide estimated gas fees before transaction confirmation
- Track transaction hashes and provide links to block explorers
- Handle wallet connection states (connected, disconnected, wrong network)
Security Considerations
- Always verify contract addresses against official sources
- Implement proper input validation for all user inputs
- Never expose private keys in your client-side code
- Set reasonable slippage tolerances for transactions
- Implement rate limiting to prevent excessive API calls
- Add multisig or timelock for admin functions if building governance features
Testing Your Integration
We provide several environments for testing:
- Local Testing: Use Hardhat to deploy Osito Protocol locally
- Testnet: Interact with our Berachain testnet deployment
- Mainnet Fork: Test against a fork of the mainnet for realistic testing
Troubleshooting Common Issues
Transaction Reverted
- Check if token approvals are sufficient
- Verify the token is eligible for Osito
- Ensure borrowing capacity calculations are up-to-date
Incorrect Borrow Capacity
- Check if the token distribution has changed
- Verify the AMM pool data is current
- Ensure you're using the latest protocol parameters
SDK Initialization Issues
- Verify you're connected to the correct network
- Check if your provider has the necessary permissions
- Ensure contract addresses are correctly configured
Getting Help
If you encounter issues with integration:
- Check our SDK Reference Documentation
- Join our Developer Discord
- Open an issue on our GitHub repository
- Contact our developer relations team at dev@osito.finance
Conclusion
By following this guide, you should be able to successfully integrate your application with the Osito Protocol. Remember to test thoroughly and follow security best practices to provide a safe and reliable experience for your users.