monoracle-sdk
v2.0.1
Published
Official SDK for Monoracle - Transform APIs into blockchain oracles
Maintainers
Readme
Monoracle SDK
Transform APIs into Blockchain Oracles
📖 About
Monoracle SDK is the official JavaScript/TypeScript library for reading data from Monoracle smart contracts. It provides a simple interface to fetch real-world data from your deployed oracles directly from the blockchain.
✨ Features
- 🔗 Multi-chain Support - Works with Ethereum, Polygon, Arbitrum, Optimism, Base, BSC, and Avalanche
- 📦 TypeScript First - Built with TypeScript for excellent type safety and developer experience
- 🚀 Easy to Use - Simple API with minimal configuration
- ⚡ Lightweight - Powered by ethers.js
- 🛡️ Error Handling - Comprehensive error handling with custom error types
- 🔄 Promise-based - Modern async/await support
- 🌐 Built-in RPC URLs - Default public RPC endpoints for all supported networks
📦 Installation
npm install monoracle-sdkyarn add monoracle-sdkpnpm add monoracle-sdk🚀 Quick Start
import { MonoracleSDK } from 'monoracle-sdk';
// Initialize the SDK with your API key
const monoracle = new MonoracleSDK({
apiKey: 'MObf356801_4ec798f2ae76bfe129025a54e4b4355078b9927ecd3c089c'
});
// Fetch data from your oracle
const data = await monoracle.getData({
contractAddress: '0x491F5fF8548CDd861b4c71e1097C73D7354E3919',
network: 'sepolia'
});
console.log('Oracle Data:', data.data);
console.log('Updated At:', new Date(data.updatedAt * 1000));📚 Documentation
Configuration
MonoracleConfig
interface MonoracleConfig {
apiKey: string; // Your Monoracle API key (required)
rpcUrls?: Partial<Record<Network, string>>; // Optional custom RPC URLs
}Basic Configuration:
const monoracle = new MonoracleSDK({
apiKey: 'MObf356801_4ec798f2ae76bfe129025a54e4b4355078b9927ecd3c089c'
});With Custom RPC URLs:
The SDK comes with built-in public RPC URLs for all supported networks. You can optionally override them:
const monoracle = new MonoracleSDK({
apiKey: 'MObf356801_4ec798f2ae76bfe129025a54e4b4355078b9927ecd3c089c',
rpcUrls: {
sepolia: 'https://your-custom-sepolia-rpc.com',
polygon: 'https://your-custom-polygon-rpc.com'
}
});Supported Networks
The SDK supports the following blockchain networks:
Ethereum:
mainnet- Ethereum Mainnetsepolia- Ethereum Sepolia Testnetgoerli- Ethereum Goerli Testnet
Polygon:
polygon- Polygon Mainnetpolygon-mumbai- Polygon Mumbai Testnet
Arbitrum:
arbitrum- Arbitrum Onearbitrum-sepolia- Arbitrum Sepolia
Optimism:
optimism- Optimism Mainnetoptimism-sepolia- Optimism Sepolia
Base:
base- Base Mainnetbase-sepolia- Base Sepolia
BSC:
bsc- BNB Smart Chainbsc-testnet- BNB Smart Chain Testnet
Avalanche:
avalanche- Avalanche C-Chainavalanche-fuji- Avalanche Fuji Testnet
Methods
getData(params: GetDataParams): Promise<OracleData>
Fetch complete data from a Monoracle smart contract.
Parameters:
interface GetDataParams {
contractAddress: string; // Smart contract address
network: Network; // Blockchain network
}Returns:
interface OracleData {
contractAddress: string; // The contract address
network: Network; // The network
data: string; // The oracle data (from API)
createdAt: number; // Contract creation timestamp (Unix)
updatedAt: number; // Last update timestamp (Unix)
creatorWallet: string; // Creator's wallet address
blockNumber: number; // Current block number
}Example:
const data = await monoracle.getData({
contractAddress: '0x491F5fF8548CDd861b4c71e1097C73D7354E3919',
network: 'sepolia'
});
console.log('Data:', data.data);
console.log('Last Updated:', new Date(data.updatedAt * 1000).toLocaleString());
console.log('Creator:', data.creatorWallet);getDataOnly(contractAddress: string, network: Network): Promise<string>
Get only the data field from the oracle (simplified method).
Example:
const data = await monoracle.getDataOnly(
'0x491F5fF8548CDd861b4c71e1097C73D7354E3919',
'sepolia'
);
console.log('Oracle Data:', data);isContractDeployed(contractAddress: string, network: Network): Promise<boolean>
Check if a contract exists at the given address.
Example:
const isDeployed = await monoracle.isContractDeployed(
'0x491F5fF8548CDd861b4c71e1097C73D7354E3919',
'sepolia'
);
console.log('Contract deployed:', isDeployed);setRpcUrl(network: Network, rpcUrl: string): void
Set a custom RPC URL for a specific network.
Example:
monoracle.setRpcUrl('sepolia', 'https://my-custom-rpc.com');getRpcUrl(network: Network): string
Get the current RPC URL for a network.
Example:
const rpcUrl = monoracle.getRpcUrl('sepolia');
console.log('Sepolia RPC:', rpcUrl);Error Handling
The SDK provides a custom MonoracleError class for error handling:
import { MonoracleSDK, MonoracleError } from 'monoracle-sdk';
try {
const data = await monoracle.getData({
contractAddress: '0x...',
network: 'sepolia'
});
} catch (error) {
if (error instanceof MonoracleError) {
console.error('Error:', error.message);
console.error('Error Code:', error.code);
}
}Error Codes:
INVALID_NETWORK- Network not supported or no RPC URL configuredNETWORK_ERROR- Network connectivity issueCONTRACT_ERROR- Smart contract errorFETCH_ERROR- Failed to fetch data
💡 Usage Examples
Basic Usage
import { MonoracleSDK } from 'monoracle-sdk';
const monoracle = new MonoracleSDK({
apiKey: process.env.MONORACLE_API_KEY!
});
async function fetchPriceData() {
const data = await monoracle.getData({
contractAddress: '0x491F5fF8548CDd861b4c71e1097C73D7354E3919',
network: 'sepolia'
});
// Assuming the oracle returns JSON data
const priceData = JSON.parse(data.data);
console.log('Current Price:', priceData.price);
console.log('Last Updated:', new Date(data.updatedAt * 1000));
}With Custom RPC URLs
const monoracle = new MonoracleSDK({
apiKey: process.env.MONORACLE_API_KEY!,
rpcUrls: {
sepolia: process.env.SEPOLIA_RPC_URL!,
polygon: process.env.POLYGON_RPC_URL!
}
});Error Handling
import { MonoracleSDK, MonoracleError } from 'monoracle-sdk';
const monoracle = new MonoracleSDK({
apiKey: process.env.MONORACLE_API_KEY!
});
async function safeFetchData() {
try {
const data = await monoracle.getData({
contractAddress: '0x491F5fF8548CDd861b4c71e1097C73D7354E3919',
network: 'sepolia'
});
return data;
} catch (error) {
if (error instanceof MonoracleError) {
switch (error.code) {
case 'INVALID_NETWORK':
console.error('Invalid network or RPC not configured');
break;
case 'NETWORK_ERROR':
console.error('Network error occurred');
break;
case 'CONTRACT_ERROR':
console.error('Smart contract error');
break;
default:
console.error('An error occurred:', error.message);
}
}
throw error;
}
}Multiple Networks
const networks = ['sepolia', 'polygon-mumbai', 'base-sepolia'];
const contractAddress = '0x491F5fF8548CDd861b4c71e1097C73D7354E3919';
for (const network of networks) {
try {
const data = await monoracle.getData({
contractAddress,
network: network as Network
});
console.log(`${network}:`, data.data);
} catch (error) {
console.error(`Failed to fetch from ${network}:`, error);
}
}Check Contract Before Fetching
async function safeGetData(contractAddress: string, network: Network) {
// First check if contract is deployed
const isDeployed = await monoracle.isContractDeployed(contractAddress, network);
if (!isDeployed) {
console.log('Contract not found at this address');
return null;
}
// Fetch data
return await monoracle.getData({ contractAddress, network });
}React Hook Example
import { useEffect, useState } from 'react';
import { MonoracleSDK, OracleData } from 'monoracle-sdk';
function useOracleData(contractAddress: string, network: Network) {
const [data, setData] = useState<OracleData | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
const monoracle = new MonoracleSDK({
apiKey: process.env.NEXT_PUBLIC_MONORACLE_API_KEY!
});
monoracle.getData({ contractAddress, network })
.then(setData)
.catch(setError)
.finally(() => setLoading(false));
}, [contractAddress, network]);
return { data, loading, error };
}
// Usage
function PriceDisplay() {
const { data, loading, error } = useOracleData(
'0x491F5fF8548CDd861b4c71e1097C73D7354E3919',
'sepolia'
);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<h2>Oracle Data</h2>
<p>{data?.data}</p>
<small>Updated: {new Date(data!.updatedAt * 1000).toLocaleString()}</small>
</div>
);
}🔧 Advanced Usage
Using with ethers.js
The SDK uses ethers.js internally. You can access the ABI and RPC URLs:
import { MONORACLE_ABI, RPC_URLS } from 'monoracle-sdk';
console.log('Sepolia RPC:', RPC_URLS.sepolia);
console.log('Contract ABI:', MONORACLE_ABI);🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🔗 Links
API Key Guide
Getting Your API Key
- Visit Monoracle Dashboard
- Navigate to API Keys section
- Click Create New API Key
- Give your key a name (e.g., "Production App")
- Copy the generated key - it starts with
MO - Store it securely (you won't be able to see it again!)
Using Your API Key
Basic Usage
import { MonoracleSDK } from 'monoracle-sdk';
const monoracle = new MonoracleSDK({
apiKey: 'MObf356801_4ec798f2ae76bfe129025a54e4b4355078b9927ecd3c089c'
});Using Environment Variables (Recommended)
Create a .env file:
MONORACLE_API_KEY=MObf356801_4ec798f2ae76bfe129025a54e4b4355078b9927ecd3c089cThen use it in your code:
import { MonoracleSDK } from 'monoracle-sdk';
const monoracle = new MonoracleSDK({
apiKey: process.env.MONORACLE_API_KEY!
});Next.js / React
For client-side usage in Next.js:
# .env.local
NEXT_PUBLIC_MONORACLE_API_KEY=MObf356801_...const monoracle = new MonoracleSDK({
apiKey: process.env.NEXT_PUBLIC_MONORACLE_API_KEY!
});Security Best Practices
✅ DO:
- Store API keys in environment variables
- Use different keys for development and production
- Add
.envto your.gitignore - Rotate keys periodically
❌ DON'T:
- Commit API keys to version control
- Share API keys in public repositories
- Hardcode API keys in your source code
- Use production keys in development
API Key Validation
The SDK validates your API key:
// ✅ Valid - starts with "MO"
apiKey: 'MObf356801_4ec798f2ae76bfe129025a54e4b4355078b9927ecd3c089c'
// ❌ Invalid - doesn't start with "MO"
apiKey: 'invalid-key' // Throws MonoracleError
// ❌ Invalid - missing
// No apiKey provided // Throws MonoracleErrorChecking Your API Key
You can verify your API key (masked for security):
const monoracle = new MonoracleSDK({
apiKey: 'MObf356801_4ec798f2ae76bfe129025a54e4b4355078b9927ecd3c089c'
});
console.log(monoracle.getApiKey());
// Output: "MObf356801..."Error Handling
import { MonoracleSDK, MonoracleError } from 'monoracle-sdk';
try {
const monoracle = new MonoracleSDK({
apiKey: process.env.MONORACLE_API_KEY!
});
} catch (error) {
if (error instanceof MonoracleError) {
console.error('API Key Error:', error.message);
// "API key is required" or
// "Invalid API key format. API key must start with 'MO'"
}
}Regenerating API Keys
If your key is compromised:
- Go to API Keys Dashboard
- Click "Revoke" on the compromised key
- Create a new API key
- Update your environment variables
- Redeploy your application
Support
Having issues with API keys?
- 📧 X: Support
- 📝 GitHub Issues: github.com/monoracle/monoracle-sdk/issues
