bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 54쪽 중 38쪽
('3. Manually revoke old key in provider dashboard\n');
}, NINETY_DAYS);
};
// Usage example:
// rotateApiKey('https://rpc.ankr.com/somnia_testnet/your-new-private-key');
// setupRotationReminder();
```
</details>
#### Secrets Management for Production
For production environments, use a dedicated secrets management platform.
```javascript
// AWS Secrets Manager example
const AWS = require('aws-sdk');
const secretsManager = new AWS.SecretsManager();
const getRpcKey = async () => {
const secret = await secretsManager.getSecretValue({
SecretId: 'somnia-rpc-key'
}).promise();
return JSON.parse(secret.SecretString).rpcUrl;
};
```
## Private Key Security
Private keys authorize all transactions on a blockchain and should be protected with the utmost vigilance.
#### Secure Key Generation
Use reputable tools that follow industry standards for cryptographically random key generation.
```javascript
// Example: Secure key generation with ethers.js
const { Wallet } = require('ethers');
const { randomBytes } = require('crypto');
// Generate cryptographically secure random wallet
const generateSecureWallet = () => {
const randomWallet = Wallet.createRandom();
return {
address: randomWallet.address,
privateKey: randomWallet.privateKey,
mnemonic: randomWallet.mnemonic.phrase
};
};
```
#### Access Control
Private keys should never be shared. For team access, use multisig wallets or role-based access control.
```javascript
// Example: Role-based access pattern
class SecureWalletManager {
constructor() {
this.roles = new Map();
this.permissions = {
'admin': ['deploy', 'transfer', 'read'],
'developer': ['deploy', 'read'],
'viewer': ['read']
};
}
assignRole(address, role) {
this.roles.set(address, role);
}
canExecute(address, action) {
const role = this.roles.get(address);
return this.permissions[role]?.includes(action) || false;
}
}
```
## Error Handling and Logging
Proper error handling and logging are crucial for maintaining security and debugging issues in production environments. When implementing logging for blockchain applications, it's essential to balance transparency with security, ensuring that sensitive information like private keys and API secrets are never exposed in logs.
#### Secure Logging Practices
<details>
<summary>Secure logging implementation</summary>
```javascript
// Secure logging implementation
const winston = require('winston');
// Create logger with security considerations
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.errors({ stack: true }),
winston.format.json(),
// Custom format to redact sensitive information
winston.format.printf(({ timestamp, level, message, ...meta }) => {
// Redact sensitive data
const sanitized = JSON.stringify(meta).replace(
/(private_key|api_key|secret)":\s*"[^"]+"/gi,
'$1": "[REDACTED]"'
);
return `${timestamp} [${level}]: ${message} ${sanitized}`;
})
),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
// Error handling for RPC calls
const safeRpcCall = async (provider, method, params) => {
try {
const result = await provider.send(method, params);
logger.info('RPC call successful', { method, success: true });
return result;
} catch (error) {
// Log error without exposing sensitive information
logger.error('RPC call failed', {
method,
error: error.message,
code: error.code
});
throw new Error(`RPC call failed: ${error.message}`);
}
};
```
</details>
#### Error Recovery Strategies
```javascript
// Implement retry logic with exponential backoff
const retryRpcCall = async (provider, method, params, maxRetries = 3) => {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await safeRpcCall(provider, method, params);
} catch (error) {
if (attempt === maxRetries) {
logger.error('Max retries exceeded', { method, attempts: attempt });
throw error;
}
const delay = Math.pow(2, attempt) * 1000; // Exponential backoff
logger.warn('Retrying RPC call', { method, attempt, delay });
await new Promise(resolve => setTimeout(resolve, delay));
}
}
};
```
## Security Checklist
* [ ] Store all sensitive keys in environment variables
* [ ] Use private RPC endpoints for better performance and reliability
* [ ] Implement IP whitelisting where supported
* [ ] Set up regular key rotation schedules
* [ ] Use hardware wallets for high-value operations
* [ ] Implement proper error handling and logging
* [ ] Never commit secrets to version control
* [ ] Use role-based access control for team environments
* [ ] Monitor and audit key usage regularly
* [ ] Test environment variable loading in application context
## Conclusion
By following these security practices, you'll significantly reduce the risk of key compromise and ensure your Somnia blockchain applications operate securely and reliably. Security is an ongoing process, and you should regularly review and update your practices as new threats emerge and best practices evolve.
# Responsible Disclosure Policy
This page serves as the unified communication hub for **Somnia developers, contributors, and security researchers**. It combines two essential areas:
* **Developer Contact and Support:** How to reach the Somnia DevRel and technical teams.
* **Responsible Disclosure:** How to report security vulnerabilities, contribute improvements, and participate in the future bounty ecosystem.
***
## Developer Contact and Support
The Somnia developer community operates across several communication channels to provide quick technical assistance, feedback exchange, and support for integrations or bug reports.
#### Active Support Channels
* **Telegram (DevRel Team):**
* [@emreyeth](https://t.me/emreyeth)
* [@PromiseGameFi](https://t.me/PromiseGameFi)
* [@emmaodia](https://t.me/emmaodia)
* **Discord:**
* Join the official [Somnia ](https://discord.gg/somnia)server.
* For technical questions, use the `#dev-support` or `#dev-chat` channel.
* To report issues privately, open a **support ticket** under “Bug Reports”
* **Email:**\
Send an email to [**developers@somnia.network**](mailto:developers@somnia.network) for official inquiries, integration help, or collaboration requests.
{% hint style="info" %}
Response time varies based on the request type, but DevRel aims to reply within **24 hours**.
{% endhint %}
#### Types of Support Requests
| Category | Description | Preferred Channel |
| ----------------------- | --------------------------------------------- | ---------------------- |
| **Integration Help** | RPC, SDK, and Smart Contract setup assistance | Discord / Email |
| **Docs Contribution** | Reporting outdated or missing developer docs | GitHub PR / Email |
| **Bug Report** | Contract, SDK, or explorer bugs | Discord Ticket / Email |
| **Partnership Inquiry** | Technical collaborations or integration ideas | Email |
***
## Responsible Disclosure
Somnia encourages ethical researchers and contributors to responsibly disclose vulnerabilities or security risks found in the ecosystem. Even though a formal bounty system is not yet live, this framework ensures findings are handled safely and recognized appropriately.
***
## Technical Disclosure Guidelines
All vulnerability reports should follow a clear, reproducible structure for fast triage and validation.
#### **Required Report Template**
{% code title="Vulnerability Report Template" %}
```markdown
# Vulnerability Report — Somnia Network
## Summary
Brief description of the issue.
## Impact
Potential risks if exploited.
## Steps to Reproduce
1. Step-by-step actions.
2. Include RPC endpoint, contract address, and network (Mainnet or Shannon Testnet).
## Expected vs Actual Behavior
Explain the difference in observed vs intended behavior.
## Proof of Concept (PoC)
Include transaction hash, minimal code snippet, or call trace.
## Suggested Fix (Optional)
Provide insights or improvement recommendations.
## Contact
Telegram / Discord handle / Email.
```
{% endcode %}
<details>
<summary>Example</summary>
{% code title="Example Vulnerability Report" %}
```markdown
# Vulnerability Report — Somnia Bridge Contract
## Summary
Bridge contract mishandles token decimals in cross-chain conversion.
## Impact
Potential underflow on tokens with decimals < 18.
## Steps to Reproduce
1. Deploy ERC20 with 6 decimals.
2. Execute `bridgeToSomnia(token, 1000000)`.
3. Observe incorrect amount on destination.
## Expected vs Actual
Expected: normalized 1 token.
Actual: 0.000001 tokens received.
## Suggested Fix
Add decimal normalization logic.
## Proof of Concept
Testnet Tx: `0x92b...4fe1`
## Contact
@emreyeth (Telegram)
```
{% endcode %}
</details>
***
## Contribution Pathways for Developers
Somnia invites developers to contribute beyond bug reporting. Follow these pathways to get involved.
{% stepper %}
{% step %}
**Documentation Contributions**
* Suggest edits or add missing examples in tutorials.
* Create new pages under categories like *Debugging*, *Testing*, or *Security*.
{% endstep %}
{% step %}
**Testing Best Practices**
* Always test exploits or stress scenarios on **Shannon Testnet**, not on Mainnet.
* Use local forks with Hardhat or Foundry for reproducibility.
{% endstep %}
{% endstepper %}
***
## Somnia Report Lifecycle
{% stepper %}
{% step %}
**Submission**
Researcher submits a report via email, Discord, or Telegram.
{% endstep %}
{% step %}
**Verification**
Somnia DevRel reproduces the issue and collects context.
{% endstep %}
{% step %}
**Escalation**
Valid issues are passed to Somnia Core Security.
{% endstep %}
{% step %}
**Patch Deployment**
Fix rolled out to Shannon Testnet, then Mainnet. (Based on where is it.)
{% endstep %}
{% step %}
**Acknowledgment**
Researcher credited publicly in Somnia Docs and Discord.
{% endstep %}
{% endstepper %}
For multi-party vulnerabilities (e.g., involving validators or external oracles), coordinated disclosure will be handled privately.
***
## Ethical Rules
{% hint style="warning" %}
* Do **not** exploit vulnerabilities on Mainnet.
* Do **not** disrupt network services or RPC endpoints.
* Do **not** engage in social engineering or phishing.
* Always disclose vulnerabilities privately and responsibly.
Researchers acting in good faith will **not face any penalties** and will be publicly recognized for their ethical contributions.
{% endhint %}
***
## Summary
* Use **Telegram, Discord, or Email** to reach Somnia’s DevRel and security teams.
* Follow the **Responsible Disclosure template** for structured vulnerability reports.
* Contribute improvements via **Pull Requests** or documentation updates.
* Future bounty and recognition programs will expand as Somnia Mainnet evolves.
# Deployment and Production
# Go-Live Checklist
This page provides a **checklist for deploying Somnia applications to production (Mainnet)**. It ensures that all necessary environment variables, contract addresses, allowlists, and rollback strategies are correctly configured before launch.
{% hint style="warning" %}
Never commit secrets to git. Use encrypted secret storage or CI secret managers for production deployments.
{% endhint %}
***
### Environment Variables
* [ ] Store RPC URLs, private keys, and API keys in `.env` files (never commit to git).
* [ ] Define `SOMNIA_RPC_MAINNET` and `SOMNIA_RPC_TESTNET` for switching between environments.
* [ ] Configure block explorer API keys (for contract verification).
* [ ] Separate `.env.production` vs `.env.development`.
* [ ] Double-check secrets with `printenv | grep SOMNIA`.
Example `.env.production`:
{% code title=".env.production" %}
```bash
SOMNIA_RPC_MAINNET=https://api.infra.mainnet.somnia.network/
PRIVATE_KEY=0xabc123...
EXPLORER_API_KEY=...
ALLOWED_ORIGIN=https://yourapp.com
```
{% endcode %}
***
### Contract Addresses
* [ ] Verify all **core Somnia system contracts** (e.g., wrapped SOMI, multicall, registry).
* [ ] Update deployed contract addresses in `.env` or config files.
* [ ] Confirm that addresses match **Mainnet deployments** (not testnet).
* [ ] Cross-check with block explorer for correct bytecode & verification.
Example `config/addresses.json`:
{% code title="config/addresses.json" %}
```json
{
"network": "mainnet",
"dao": "0x1234...",
"token": "0xabcd...",
"subgraph": "https://subgraph.somnia.network/dashboard/subgraph/..."
}
```
{% endcode %}
***
### Allowlists
* [ ] Maintain allowlists for admin roles, multisigs, and privileged addresses.
* [ ] Use multisig wallets ([Safe](https://safe.somnia.network/welcome)) for critical roles (owner, pauser, upgrader).
* [ ] Double-check allowlist in contracts (no dev/test keys).
* [ ] Store allowlist in version control (JSON/YAML).
Example `allowlist.json`:
{% code title="allowlist.json" %}
```json
{
"admins": ["0xAdmin1...", "0xAdmin2..."],
"oracles": ["0xOracle1..."],
"relayers": ["0xRelayer1..."]
}
```
{% endcode %}
***
### Rollback Plan
Having a clear rollback strategy is essential if something goes wrong during or after deployment. This should include both **technical measures** and **operational procedures**.
#### Technical Rollback Steps
* [ ] **Pause contracts** – ensure critical contracts implement a `pause()` function for emergencies.
* [ ] **Feature flags** – enable/disable risky features without redeployment.
* [ ] **Upgradable contracts** – if using proxies, keep previous implementation verified and ready.
* [ ] **Role revocation** – remove compromised keys or revoke admin privileges quickly.
* [ ] **Migration scripts** – maintain scripts to redeploy or roll forward to a safe version.
#### Operational Rollback Steps
* [ ] **Communication plan** – inform users immediately via Discord, Twitter, or status page.
* [ ] **Validator coordination** – notify Somnia infra providers/validators in case of critical incidents.
* [ ] **Emergency access** – keep a secure list of multisig signers available for urgent transactions.
* [ ] **Data backups** – keep copies of config files, [subgraph](https://subgraph.somnia.network/) schemas, and off-chain DBs.
* [ ] **Post-mortem process** – document the issue, resolution, and future prevention steps.
***
### Best Practices
* Always test on **Shannon Testnet** before mainnet deployment.
* Pin dependencies & compiler versions for reproducibility.
* Run **audit checklist** (see Smart Contract Security 101).
* Monitor deployed contracts with logging & health checks.
* Communicate launch windows to your community in advance.
# Explorer API Health and Monitoring
A comprehensive guide for integrating Somnia Network explorer APIs with production-ready logging and health monitoring systems.
This guide demonstrates how to build robust applications on Somnia Network using Blockscout's explorer APIs, implement enterprise-grade logging, and set up comprehensive health monitoring for your dApps.
**What You'll Learn**
* Somnia Network explorer API integration
* Production logging with Winston
* Health monitoring systems
* Error handling and debugging
* Performance optimization
## **Prerequisites**
* Node.js 20+
* TypeScript/JavaScript knowledge
* Blockchain/EVM concepts
* Funded Somnia wallet
* REST API experience
## **Explorer Endpoints**
Somnia Network uses Blockscout as its blockchain explorer infrastructure:
| Network | Explorer URL | API Endpoint |
| ----------- | ----------------------------------------- | ------------ |
| **Testnet** | <https://shannon-explorer.somnia.network> | `/api` |
| **Mainnet** | <https://explorer.somnia.network> | `/api` |
### **Available APIs**
Blockscout provides multiple API interfaces:
* **REST API** - Primary interface for UI operations
* **RPC API** - Etherscan-compatible endpoints
* **ETH RPC API** - Standard [JSON-RPC methods](/developer/json-rpc-api)
* **GraphQL** - Advanced querying capabilities
## Quick Start
Initialize your Somnia integration project:
```bash
mkdir somnia-explorer-integration
cd somnia-explorer-integration
npm init -y
```
### **Dependencies**
Install required packages:
```bash
# Core dependencies
npm install axios winston express helmet cors dotenv ethers
# Development dependencies
npm install --save-dev @types/node typescript ts-node nodemon @types/express @types/cors
```
### **Core Dependencies:**
* `axios` - Promise-based HTTP client used for making API requests to Somnia Network's Blockscout explorer APIs with automatic request/response logging and error handling
* `winston` - Comprehensive logging library used for creating structured JSON logs with timestamps, component-specific loggers (API, explorer, health), and automatic log rotation
* `express` - Minimal web framework used for creating health monitoring endpoints and serving the application
* `helmet` - Security middleware used for setting HTTP security headers to protect against XSS, clickjacking, and other common web vulnerabilities
* `cors` - Cross-Origin Resource Sharing middleware used for enabling secure cross-origin requests from frontend applications
* `dotenv` - Environment variable loader used for managing configuration settings and sensitive information like API keys and network settings
* `ethers` - Ethereum library used for blockchain interactions, RPC connections, and retrieving network information
### **Project Structure**
```bash
mkdir src/{config,services,utils} logs
```
### **Package Configuration**
Update `package.json` with build scripts:
```json
{
"name": "somnia-explorer-integration",
"version": "1.0.0",
"description": "Somnia Network explorer integration with logging and health checks",
"main": "dist/app.js",
"scripts": {
"build": "tsc",
"start": "node dist/app.js",
"dev": "nodemon --exec ts-node src/app.ts",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": ["somnia", "blockchain", "explorer", "blockscout"],
"author": "Your Name",
"license": "MIT"
}
```
### Configuration
**Network Settings**
Create a configuration file for Somnia Network settings to:
* Consolidate all Somnia Network endpoints (testnet/mainnet) in one location
* Enable automatic environment-based network switching
* Provide TypeScript interfaces for type safety
* Make it easy to update endpoints without changing multiple files
```typescript
// src/config/network.ts
export const SOMNIA_CONFIG = {
testnet: {
name: 'Somnia Testnet',
rpcUrl: 'https://dream-rpc.somnia.network',
chainId: 50312,
explorerUrl: 'https://shannon-explorer.somnia.network',
explorerApiUrl: 'https://shannon-explorer.somnia.network/api'
},
mainnet: {
name: 'Somnia Mainnet',
rpcUrl: 'https://somnia-json-rpc.stakely.io',
chainId: 5031,
explorerUrl: 'https://explorer.somnia.network',
explorerApiUrl: 'https://explorer.somnia.network/api'
}
};
export const getCurrentNetwork = () => {
return process.env.NODE_ENV === 'production'
? SOMNIA_CONFIG.mainnet
: SOMNIA_CONFIG.testnet;
};
```
### **Environment Variables**
Why create a .env file:
* Keeps sensitive information out of source code
* Useful when using third-party RPC API Keys
* Enables different configurations for development/production environments
* Controls which Somnia network to use (testnet/mainnet) via `NODE_ENV`
* Allows easy modification of settings without code changes
```bash
# .env
NODE_ENV=development
PORT=3000
LOG_LEVEL=info
```
####
## API Integration
### **Explorer Service**
This service provides comprehensive logging for all API interactions and follows Blockscout's REST API patterns.
<details>
<summary>src/services/somniaExplorerService.ts</summary>
```javascript
// src/services/somniaExplorerService.ts
import axios, { AxiosInstance } from 'axios';
import { getCurrentNetwork } from '../config/network';
import { logger } from '../utils/logger';
export interface TransactionData {
hash: string;
blockNumber: number;
from: string;
to: string;프로젝트로 돌아가기