diff --git a/.gitignore b/.gitignore index b572d2b4..ecf1421a 100644 --- a/.gitignore +++ b/.gitignore @@ -18,5 +18,5 @@ deployed/local deployments gasReporterOutput.json .vscode/ -docs -package-lock.json \ No newline at end of file + +package-lock.json diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md new file mode 100644 index 00000000..b2b61b0e --- /dev/null +++ b/docs/CHANGELOG.md @@ -0,0 +1,59 @@ +## [1.0.1](https://github.com/razor-network/contracts/compare/v1.0.0...v1.0.1) (2022-04-04) + + +### Bug Fixes + +* **release:** explicitly export abis before publish ([1931444](https://github.com/razor-network/contracts/commit/1931444e8ea05491c38685a81e826330748105db)) + +# [1.0.0](https://github.com/razor-network/contracts/compare/v0.3.0...v1.0.0) (2022-04-04) + + +### Bug Fixes + +* increase footer max line length ([26d09e7](https://github.com/razor-network/contracts/commit/26d09e79170515e5efe51282e5c4bf6ad273c1e7)) + + +### chore + +* **release:** dummy commit to trigger release ([2ecb956](https://github.com/razor-network/contracts/commit/2ecb95696b99ff09dbda7f4fbf9832dd6ea06a8a)) + + +* Merge pull request #783 from razor-network/next ([b789199](https://github.com/razor-network/contracts/commit/b789199b162f3a763b04329a593bd2b109f81ea5)), closes [#783](https://github.com/razor-network/contracts/issues/783) + + +### BREAKING CHANGES + +* Release +* **release:** Release + +# [0.3.0](https://github.com/razor-network/contracts/compare/v0.2.1...v0.3.0) (2022-04-04) + + +### Bug Fixes + +* clean up docgen ([#743](https://github.com/razor-network/contracts/issues/743)) ([2bba861](https://github.com/razor-network/contracts/commit/2bba86197e01a1f8873b8cc9cffdc93829fce359)) +* dispute 'disputeCollectionIdShouldBePresent()' is successful if empty array is passed ([#763](https://github.com/razor-network/contracts/issues/763)) ([d029654](https://github.com/razor-network/contracts/commit/d02965414e5931a28fa4b6aa56404d33f9b84f59)) +* fixed delegator migration ([#775](https://github.com/razor-network/contracts/issues/775)) ([ca349e4](https://github.com/razor-network/contracts/commit/ca349e4ce6be76d63e644414d4f13e58ee46c815)) +* fixed scenarios ([#761](https://github.com/razor-network/contracts/issues/761)) ([2ec3d73](https://github.com/razor-network/contracts/commit/2ec3d73bf4792e5af1744e63cca390cdb59fb2f1)) +* only propose revealed assets of epoch ([#726](https://github.com/razor-network/contracts/issues/726)) ([2c14622](https://github.com/razor-network/contracts/commit/2c1462220fcb1d9cbf9143da6e82f4ef4d242b27)) +* optmized for calls in loop : slither warning ([#745](https://github.com/razor-network/contracts/issues/745)) ([b1f4236](https://github.com/razor-network/contracts/commit/b1f423648b7e3366cdb3377bcfee30f752e555f9)) +* removed require statement from BlockManager ([#740](https://github.com/razor-network/contracts/issues/740)) ([af10f62](https://github.com/razor-network/contracts/commit/af10f6219662c03440d353b22106c13c19e13bec)) +* stakerReward being updated properly ([#770](https://github.com/razor-network/contracts/issues/770)) ([1e19b51](https://github.com/razor-network/contracts/commit/1e19b51fe13ff9642d2970ff3e4b3ef9283209ea)) + + +### Features + +* add docgen to the project from natspec ([#731](https://github.com/razor-network/contracts/issues/731)) ([4fd81ca](https://github.com/razor-network/contracts/commit/4fd81ca7233de0f231177e42c046d5b47b7bee9c)) +* added require length check in propose ([#765](https://github.com/razor-network/contracts/issues/765)) ([2535e59](https://github.com/razor-network/contracts/commit/2535e5961d34f4cbd98c9b831f0fd9d6e2de2d97)) +* removed redundant roles ([#754](https://github.com/razor-network/contracts/issues/754)) ([cb79103](https://github.com/razor-network/contracts/commit/cb79103b8df851f4958b9aa467b9252f31a73f19)) +* removed uncessary slither warnigns for timestamp ([#755](https://github.com/razor-network/contracts/issues/755)) ([c43731d](https://github.com/razor-network/contracts/commit/c43731d60a252a47393af070ae7687a2f4cfe5d4)) +* staker can now claim commission ([#758](https://github.com/razor-network/contracts/issues/758)) ([6469129](https://github.com/razor-network/contracts/commit/64691296e5f3420cd6309e26fa17c26c31300647)) + +## [0.2.1](https://github.com/razor-network/contracts/compare/v0.2.0...v0.2.1) (2022-02-23) + + +### Bug Fixes + +* disable body check on commits ([b351303](https://github.com/razor-network/contracts/commit/b35130307a7a5a6b90518d0a8ced0171ade58c1a)) +* disable commit body length ([78ca858](https://github.com/razor-network/contracts/commit/78ca85807514ca904102adff743b394609c0979f)) +* Fix readme ([69c008d](https://github.com/razor-network/contracts/commit/69c008de5dac294135942f5fe11352e59d14fc99)) diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md new file mode 100644 index 00000000..d17db19d --- /dev/null +++ b/docs/CONTRIBUTING.md @@ -0,0 +1,260 @@ +# Contributing to Oracle Contracts + +This guide explains how to contribute to the Oracle Contracts project, covering everything from setting up your development environment to submitting pull requests. + +## Development Setup + +### Prerequisites +- Node.js >= 16 +- Git +- npm or yarn +- Hardhat development environment + +### Initial Setup + +1. Fork the repository on GitHub: + - Visit [razor-network/contracts](https://github.com/razor-network/contracts) + - Click the 'Fork' button + - Clone your fork locally: + ```bash + git clone git@github.com:YourLogin/contracts.git + cd contracts + ``` + +2. Install dependencies: + ```bash + npm install + # or + yarn install + ``` + +3. Add upstream remote: + ```bash + git remote add upstream git@github.com:razor-network/contracts.git + ``` + +## Development Workflow + +### 1. Branch Management + +Always create a feature branch for your work: +```bash +# Sync with upstream +git checkout master +git pull upstream master + +# Create feature branch +git checkout -b feature/your-feature-name +``` + +### 2. Development Process + +1. Make your changes in the feature branch +2. Follow the code style guidelines +3. Add tests for new functionality +4. Ensure all tests pass +5. Update documentation as needed + +### 3. Testing Requirements + +Run the full test suite before submitting: +```bash +# Run all tests +npm test + +# Run specific test scenarios +npm run scenarios + +# Check test coverage +npm run coverage +``` + +Coverage requirements: +- Statements: 90% +- Branches: 60% +- Functions: 85% +- Lines: 86% + +### 4. Code Quality + +Maintain code quality by running: +```bash +# Run all linters +npm run lint + +# Fix linting issues +npm run lint:fix + +# Run specific linters +npm run lint:sol # Solidity files +npm run lint:js # JavaScript files +``` + +## Code Style Guidelines + +### Solidity Style Guide + +1. **Contract Structure** + ```solidity + // SPDX-License-Identifier: UNLICENSED + pragma solidity ^0.8.0; + + contract MyContract { + // State variables + // Events + // Modifiers + // Constructor + // External functions + // Public functions + // Internal functions + // Private functions + } + ``` + +2. **Naming Conventions** + - Contracts: PascalCase + - Functions: camelCase + - Variables: camelCase + - Events: PascalCase + - Modifiers: camelCase + +3. **Documentation** + - Use NatSpec format for all public interfaces + - Document parameters and return values + - Explain complex logic + ```solidity + /// @notice Brief description + /// @dev Detailed description + /// @param name Description of parameter + /// @return Description of return value + ``` + +### JavaScript Style Guide + +1. **File Structure** + - Use ES modules (import/export) + - One class/component per file + - Clear file naming + +2. **Code Formatting** + - Use prettier for consistent formatting + - 2 space indentation + - Semicolons required + - Single quotes for strings + +## Pull Request Process + +1. **Before Submitting** + - Sync with upstream master + - Run all tests + - Check code coverage + - Run linters + - Update documentation + +2. **Creating the PR** + ```bash + git add . + git commit -m "feat: description of your changes" + git push origin feature/your-feature-name + ``` + +3. **PR Guidelines** + - Use conventional commit messages + - Include tests for new features + - Update relevant documentation + - Link related issues + - Provide clear description of changes + +4. **PR Template** + ```markdown + ## Description + Brief description of changes + + ## Type of change + - [ ] Bug fix + - [ ] New feature + - [ ] Breaking change + - [ ] Documentation update + + ## Checklist + - [ ] Tests added/updated + - [ ] Documentation updated + - [ ] Code follows style guidelines + - [ ] All tests passing + ``` + +## Smart Contract Development + +### 1. Contract Modifications + +When modifying contracts: +1. Update interfaces if needed +2. Add new tests +3. Update deployment scripts +4. Document changes in NatSpec + +### 2. Testing Guidelines + +1. **Test Structure** + ```javascript + describe("Contract", () => { + before(() => { + // Setup + }); + + it("should do something", async () => { + // Test + }); + }); + ``` + +2. **Test Coverage** + - Happy path scenarios + - Edge cases + - Error conditions + - Access control + - State transitions + +### 3. Gas Optimization + +1. Run gas analysis: + ```bash + npm run gas + ``` + +2. Compare gas usage: + ```bash + npm run gasCompare + ``` + +## Documentation + +### 1. Code Documentation +- Use NatSpec comments for all public interfaces +- Document complex algorithms +- Explain security considerations +- Update API documentation + +### 2. Technical Documentation +- Update relevant .md files +- Keep diagrams current +- Document breaking changes +- Update examples + +## Getting Help + +1. **Resources** + - [Project Documentation](docs/README.md) + - [Core Concepts](docs/core-concepts.md) + - [API Reference](docs/api-reference.md) + +2. **Community** + - GitHub Issues + - Development chat + - Technical discussions + +## Related Documentation +- [Architecture Overview](architecture.md) +- [Setup Guide](setup-and-installation.md) +- [API Reference](api-reference.md) +- [Core Concepts](core-concepts.md) diff --git a/docs/DEPLOY.md b/docs/DEPLOY.md new file mode 100644 index 00000000..168f83fd --- /dev/null +++ b/docs/DEPLOY.md @@ -0,0 +1,73 @@ +## hardhat-deploy in a nutshell + +**hardhat-deploy** allows you to write `deploy scripts` in the `deploy` folder. Each of these files that look as follows will be executed in turn when you execute the following task: `hardhat --network deploy` + +Note: `hre.deployments.deploy` function will by default only deploy a contract if the contract code has changed, making it easier to write idempotent scripts. + +### An example of a deploy script : + +``` +module.exports = async ({ + getNamedAccounts, + deployments, + getChainId, + getUnnamedAccounts, +}) => { + const {deploy} = deployments; + const {deployer} = await getNamedAccounts(); + + // the following will only deploy "GenericMetaTxProcessor" if the contract was never deployed or if the code changed since last deployment + await deploy('GenericMetaTxProcessor', { + from: deployer, + gasLimit: 4000000, + args: [], + }); +}; + +``` + +As you can see the HRE passed in has 4 new fields : + +- `getNamedAccounts` is a function that returns a promise to an object whose keys are names and values are addresses. It is parsed from the `namedAccounts` configuration. +- `getUnnamedAccounts` is a function that return a promise to an array of accounts which were not named (see `namedAccounts` ). It is useful for tests where you want to be sure that the account has no speicifc role in the system (no token given, no admin access, etc...). +- `getChainId` is a function which return a promise for the chainId, as convenience +- `deployments` is an object which contains functions to access past deployments or to save new ones, as well as helpers functions. + +`deployments` contains for example the `deploy` function that allows you to deploy contract and save them. + +### **1. namedAccounts (ability to name addresses)** + +--- + +This plugin extends the `HardhatConfig`'s object with an optional `namedAccounts` field. + +`namedAccounts` allows you to associate names to addresses and have them configured per chain. +This allows you to have meaningful names in your tests. + +``` +{ + namedAccounts: { + deployer: { + default: 0, // here this will by default take the first account as deployer + 1: 0, // similarly on mainnet it will take the first account as deployer. Note though that depending on how hardhat network are configured, the account 0 on one network can be different than on another + 4: '0xA296a3d5F026953e17F472B497eC29a5631FB51B', // but for rinkeby it will be a specific address + "goerli": '0x84b9514E013710b9dD0811c9Fe46b837a4A0d8E0', //it can also specify a specific netwotk name (specified in hardhat.config.js) + }, + feeCollector:{ + default: 1, // here this will by default take the second account as feeCollector (so in the test this will be a different account than the deployer) + 1: '0xa5610E1f289DbDe94F3428A9df22E8B518f65751', // on the mainnet the feeCollector could be a multi sig + 4: '0xa250ac77360d4e837a13628bC828a2aDf7BabfB3', // on rinkeby it could be another account + } + } +} + +``` + +--- + +Furthermore you can also ensure these scripts are executed in test’s too by calling `await deployments.fixture(['MyContract'])` in your test. +This is optimised, so if multiple tests use the same contract, the deployment will be executed once and each test will start with the exact same state. + +This is a huge benefit for testing since you are not required to replicate the deployment procedure in your tests. + +You can even group deploy scripts in different sub folder and ensure they are executed in their logical order. diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 00000000..9d720a79 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,36 @@ +# Oracle Contracts Documentation + +Welcome to the Oracle Contracts documentation. This documentation provides comprehensive information about the Oracle Contracts system, its architecture, and how to work with it. + +## Documentation Structure + +- [Architecture Overview](architecture.md) - System design and component interactions +- [Setup & Installation](setup-and-installation.md) - Environment setup and deployment steps +- [API Reference](api-reference.md) - Contract interfaces and endpoints +- [Data Models](data-models.md) - Data structures and schemas +- [Core Concepts](core-concepts.md) - Fundamental concepts and terminology +- [Contributing](contributing.md) - Development workflow and guidelines + +### Detailed Guides +- [Staking Guide](guides/staking.md) +- [Voting Guide](guides/voting.md) +- [Bonds Guide](guides/bonds.md) +- [Delegation Guide](guides/delegation.md) + +## Quick Links + +- [Documentation Plan](documentation-plan.md) +- [GitHub Repository](https://github.com/razor-network/oracle-contracts) +- [Change Log](../CHANGELOG.md) + +## Getting Help + +If you need help or have questions: +1. Check the [Core Concepts](core-concepts.md) guide +2. Review the [API Reference](api-reference.md) +3. See the [Contributing](contributing.md) guide for development questions +4. Open an issue on GitHub for bugs or feature requests + +## Contributing to Documentation + +See our [Contributing Guide](contributing.md) for information about improving this documentation. diff --git a/docs/api-reference.md b/docs/api-reference.md new file mode 100644 index 00000000..468dabeb --- /dev/null +++ b/docs/api-reference.md @@ -0,0 +1,277 @@ +# API Reference + +This document provides detailed information about the smart contract interfaces and functions in the Oracle Contracts system. + +## Core Contracts + +### StakeManager + +The StakeManager contract handles staking operations, delegation, and reward distribution. + +#### Staking Functions + +```solidity +function stake(uint32 epoch, uint256 amount) external +``` +Stake RAZOR tokens in the network. +- `epoch`: The epoch for staking +- `amount`: Amount of RAZOR to stake +- Returns: None +- Emits: `Staked` event + +```solidity +function delegate(uint32 stakerId, uint256 amount) external +``` +Delegate RAZOR tokens to an existing staker. +- `stakerId`: ID of the staker to delegate to +- `amount`: Amount of RAZOR to delegate +- Returns: None +- Emits: `Delegated` event + +```solidity +function unstake(uint32 stakerId, uint256 sAmount) external +``` +Lock sRZR tokens for withdrawal. +- `stakerId`: ID of the staker +- `sAmount`: Amount of sRZR to unstake +- Returns: None +- Emits: `Unstaked` event + +#### Query Functions + +```solidity +function getStakerId(address _address) external view returns (uint32) +``` +Get the staker ID for an address. +- `_address`: Staker's address +- Returns: Staker ID + +```solidity +function getStaker(uint32 _id) external view returns (Structs.Staker memory) +``` +Get detailed information about a staker. +- `_id`: Staker ID +- Returns: Staker struct with all details + +```solidity +function getInfluence(uint32 stakerId) external view returns (uint256) +``` +Calculate a staker's influence (maturity × stake). +- `stakerId`: Staker ID +- Returns: Influence value + +### CollectionManager + +The CollectionManager contract manages data collections and jobs. + +#### Collection Management + +```solidity +function createCollection( + uint32 tolerance, + int8 power, + uint16 occurrence, + uint32 aggregationMethod, + uint16[] memory jobIDs, + string calldata name +) external returns (uint16) +``` +Create a new data collection. +- `tolerance`: Allowed deviation percentage +- `power`: Decimal shift for results +- `occurrence`: Reporting frequency +- `aggregationMethod`: Method to aggregate results +- `jobIDs`: Array of job IDs in collection +- `name`: Collection name +- Returns: Collection ID + +```solidity +function createMulJob(Structs.Job[] memory mulJobs) external returns (uint16[] memory) +``` +Create multiple data source jobs. +- `mulJobs`: Array of job structures +- Returns: Array of created job IDs + +```solidity +function updateCollection( + uint16 collectionID, + uint32 tolerance, + uint32 aggregationMethod, + int8 power, + uint16[] memory jobIDs +) external +``` +Update an existing collection's parameters. +- `collectionID`: Collection to update +- `tolerance`: New tolerance value +- `aggregationMethod`: New aggregation method +- `power`: New decimal shift value +- `jobIDs`: New array of job IDs + +#### Query Functions + +```solidity +function getResult(bytes32 _name) external view returns (uint256, int8) +``` +Get a collection's latest result. +- `_name`: Collection name +- Returns: (result value, decimal power) + +```solidity +function getActiveCollections() external view returns (uint16[] memory) +``` +Get all active collection IDs. +- Returns: Array of active collection IDs + +### BlockManager + +The BlockManager handles epoch progression and block confirmation. + +```solidity +function confirmPreviousEpochBlock(uint32 stakerId) external +``` +Confirm a block from the previous epoch. +- `stakerId`: ID of confirming staker +- Returns: None + +```solidity +function getBlock(uint32 epoch) external view returns (Structs.Block memory) +``` +Get block information for an epoch. +- `epoch`: Target epoch +- Returns: Block structure + +```solidity +function isBlockConfirmed(uint32 epoch) external view returns (bool) +``` +Check if a block is confirmed. +- `epoch`: Target epoch +- Returns: Confirmation status + +## Events + +### StakeManager Events + +```solidity +event Staked( + address indexed staker, + address sToken, + uint32 indexed epoch, + uint32 indexed stakerId, + uint256 amount, + uint256 newStake, + uint256 totalSupply, + uint256 timestamp +) +``` +Emitted when tokens are staked. + +```solidity +event Delegated( + address indexed delegator, + uint32 indexed epoch, + uint32 indexed stakerId, + uint256 amount, + uint256 newStake, + uint256 totalSupply, + uint256 timestamp +) +``` +Emitted when tokens are delegated. + +### CollectionManager Events + +```solidity +event CollectionCreated( + uint16 indexed collectionId, + string name, + uint32 tolerance, + uint32 aggregationMethod, + uint16[] jobIds +) +``` +Emitted when a new collection is created. + +## Data Structures + +### Staker Structure +```solidity +struct Staker { + bool acceptDelegation; + bool isSlashed; + uint8 commission; + uint32 id; + uint32 age; + address _address; + address tokenAddress; + uint32 epochFirstStakedOrLastPenalized; + uint256 stakerReward; + uint256 stake; + uint32 epochCommissionLastUpdated; +} +``` + +### Collection Structure +```solidity +struct Collection { + uint32 tolerance; + int8 power; + uint16 occurrence; + uint32 aggregationMethod; + uint16[] jobIds; + string name; + bool active; +} +``` + +## Error Codes + +Common error messages and their meanings: + +| Error Message | Description | +|--------------|-------------| +| "less than minimum safe Razor" | Stake amount below minimum | +| "staker is slashed" | Staker has been penalized | +| "Delegation not accepted" | Staker doesn't accept delegation | +| "Invalid Amount" | Amount exceeds balance or invalid | +| "Withdraw epoch not reached" | Lock period not complete | + +## Integration Examples + +### Staking Example +```solidity +// Approve RAZOR tokens first +IERC20(razorAddress).approve(stakeManager, amount); + +// Stake tokens +stakeManager.stake(currentEpoch, amount); +``` + +### Collection Creation Example +```solidity +// Create jobs first +Structs.Job[] memory jobs = new Structs.Job[](1); +jobs[0] = Structs.Job({ + weight: 1, + power: 8, + selectorType: Constants.JobSelectorType.JSON, + selector: "$.price", + url: "https://api.example.com/price" +}); +uint16[] memory jobIds = collectionManager.createMulJob(jobs); + +// Create collection +collectionManager.createCollection( + 1000, // 1% tolerance + 8, // 8 decimal places + 1, // Report every epoch + 0, // Mean aggregation + jobIds, + "ETH/USD" +); +``` + +## Related Documentation +- [Core Concepts](core-concepts.md) +- [Architecture Overview](architecture.md) +- [Setup Guide](setup-and-installation.md) \ No newline at end of file diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 00000000..3f5a299d --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,225 @@ +# System Architecture + +## Overview + +The Oracle Contracts system is a decentralized oracle network that enables reliable off-chain data reporting and aggregation on blockchain networks. The system uses a sophisticated architecture of smart contracts to manage data collection, stake-based validation, and reward distribution. + +```mermaid +graph TD + A[Client Applications] --> B[Oracle Network] + B --> C[Core Contracts] + C --> D[Data Sources] + + subgraph Core Contracts + E[Block Manager] + F[Collection Manager] + G[Stake Manager] + H[Vote Manager] + I[Bond Manager] + J[Reward Manager] + end + + subgraph Data Flow + K[Jobs] + L[Collections] + M[Results] + end +``` + +## Core Components + +### 1. Collection Management System +The Collection Manager is the primary interface for data management: +- **Jobs**: Individual data sources with specific URLs and parsing instructions +- **Collections**: Groups of related jobs with defined aggregation methods +- **Results**: Aggregated and validated data points + +```mermaid +graph LR + A[Jobs] -->|Grouped into| B[Collections] + B -->|Reported by| C[Stakers] + C -->|Validated through| D[Consensus] + D -->|Produces| E[Final Results] +``` + +### 2. Stake Management System +Manages staker participation and security: +- Stake allocation and tracking +- Slashing conditions +- Delegation mechanisms + +### 3. Block Management System +Handles the epoch-based progression of the oracle: +- Block confirmation process +- Epoch transitions +- Result finalization + +```mermaid +stateDiagram-v2 + [*] --> Commit + Commit --> Reveal + Reveal --> Propose + Propose --> Confirm + Confirm --> [*] +``` + +### 4. Vote Management System +Coordinates the consensus process: +- Vote collection and tracking +- Dispute resolution +- Result finalization + +### 5. Bond Management System +Handles data bond management: +- Collection assignments +- Bond calculations +- Occurrence tracking + +### 6. Reward Management System +Manages incentive distribution: +- Block rewards +- Staking rewards +- Penalty management + +## Data Flow + +```mermaid +sequenceDiagram + participant Client + participant Oracle + participant Staker + participant DataSource + + Client->>Oracle: Request Data + Oracle->>Staker: Assign Collection + Staker->>DataSource: Query Jobs + DataSource->>Staker: Return Data + Staker->>Oracle: Submit Results + Oracle->>Oracle: Consensus Process + Oracle->>Client: Return Validated Data +``` + +## Security Model + +The system employs multiple security mechanisms: + +1. **Staking**: Participants must stake tokens to participate +2. **Consensus**: Multi-stage validation process +3. **Slashing**: Penalties for malicious behavior +4. **Bonding**: Collection-specific security deposits + +## Network States + +The oracle network operates in distinct states: + +```mermaid +stateDiagram-v2 + [*] --> Active + Active --> Paused: Emergency + Paused --> Active: Resolution + Active --> Upgraded: Protocol Update + Upgraded --> Active: Migration Complete +``` + +## Smart Contract Architecture + +```mermaid +classDiagram + class IBlockManager { + +confirmPreviousEpochBlock() + +getBlock() + +isBlockConfirmed() + } + class ICollectionManager { + +createCollection() + +updateCollection() + +setResult() + +getResult() + } + class IStakeManager { + +stake() + +unstake() + +delegate() + } + class IBondManager { + +occurrenceRecalculation() + +getDatabondCollections() + } + class IVoteManager { + +vote() + +reveal() + +dispute() + } + class IRewardManager { + +distributeRewards() + +calculateRewards() + } +``` + +## Deployment Architecture + +The system supports deployment across multiple networks: + +```mermaid +graph TD + A[Deployment Manager] -->|Deploy| B[Network 1] + A -->|Deploy| C[Network 2] + A -->|Deploy| D[Network N] + + subgraph Network 1 + B1[Core Contracts] + B2[Governance] + B3[Token Contracts] + end +``` + +## Integration Points + +### External Interfaces +1. **Client Integration** + - Direct contract calls + - Event monitoring + - Result verification + +2. **Data Source Integration** + - URL-based data fetching + - Multiple selector types (JSON/XHTML) + - Custom aggregation methods + +### Internal Communication +1. **Inter-Contract Communication** + - Strict access control + - State synchronization + - Event-based updates + +## Scalability Considerations + +The system is designed with several scalability features: + +1. **Horizontal Scaling** + - Multiple collections can be processed in parallel + - Independent staker operations + - Distributed data sourcing + +2. **Vertical Scaling** + - Configurable epoch lengths + - Adjustable collection parameters + - Flexible aggregation methods + +## Future Architecture Considerations + +1. **Planned Improvements** + - Layer 2 integration + - Cross-chain communication + - Enhanced data verification methods + +2. **Expansion Areas** + - Additional data source types + - New consensus mechanisms + - Advanced reward systems + +## Related Documentation +- [Setup and Installation](setup-and-installation.md) +- [API Reference](api-reference.md) +- [Data Models](data-models.md) +- [Core Concepts](core-concepts.md) \ No newline at end of file diff --git a/docs/core-concepts.md b/docs/core-concepts.md new file mode 100644 index 00000000..8d425306 --- /dev/null +++ b/docs/core-concepts.md @@ -0,0 +1,195 @@ +# Core Concepts + +This document explains the fundamental concepts and terminology used in the Oracle Contracts system. + +## Staking System + +### Staking and Delegation +The system uses a Proof of Stake (PoS) consensus mechanism where participants can: + +1. **Direct Staking** + - Participants can stake RAZOR tokens directly + - Minimum safe amount required for staking + - Stakers receive sRZR (Staked RAZOR) tokens representing their stake + - Stakers can run nodes and participate in oracle operations + +2. **Delegation** + - Users can delegate their RAZOR tokens to existing stakers + - Delegators receive sRZR tokens proportional to their delegation + - Stakers can set commission rates for delegation + - Helps achieve decentralization without requiring everyone to run nodes + +```mermaid +graph TD + A[RAZOR Tokens] -->|Stake| B[Direct Staking] + A -->|Delegate| C[Delegation] + B -->|Receive| D[sRZR Tokens] + C -->|Receive| D + D -->|Represent| E[Stake Position] +``` + +### Stake Management +The system includes sophisticated stake management features: + +1. **Staking Operations** + - Stake: Lock RAZOR tokens and receive sRZR + - Unstake: Lock sRZR tokens for withdrawal + - Withdraw: Claim unstaked RAZOR tokens + - Lock periods for security + +2. **Maturity and Influence** + - Stakers gain maturity over time + - Influence = Maturity × Stake + - Higher influence means more weight in consensus + +## Oracle Operations + +### Data Collection System + +1. **Jobs** + - Individual data sources + - Specific URLs and parsing instructions + - Power (decimal adjustment) settings + - Weight in aggregation + +2. **Collections** + - Groups of related jobs + - Aggregation methods + - Tolerance levels for deviation + - Update frequency (occurrence) + +```mermaid +graph LR + A[Jobs] -->|Group Into| B[Collections] + B -->|Assigned to| C[Stakers] + C -->|Report| D[Results] + D -->|Validate| E[Consensus] +``` + +### Consensus Mechanism + +The system operates in epochs with distinct states: + +1. **Epoch States** + ```mermaid + stateDiagram-v2 + [*] --> Commit + Commit --> Reveal + Reveal --> Propose + Propose --> Confirm + Confirm --> [*] + ``` + +2. **State Functions** + - Commit: Submit hashed values + - Reveal: Reveal actual values + - Propose: Select block proposer + - Confirm: Finalize results + +## Security Model + +### Slashing Conditions +The system enforces security through penalties: + +1. **Slashing Components** + - Bounty: Reward for identifying violations + - Burn: Tokens removed from circulation + - Keep: Tokens retained by the system + +2. **Penalty Triggers** + - Invalid data reporting + - Malicious behavior + - Inactivity + - Protocol violations + +```mermaid +graph TD + A[Violation Detected] -->|Triggers| B[Slashing] + B -->|Distributes| C[Bounty] + B -->|Removes| D[Burn] + B -->|Retains| E[Keep] +``` + +### Bond Management + +1. **Data Bonds** + - Collateral for data reporting + - Collection-specific assignments + - Occurrence tracking + - Risk management + +2. **Bond Calculations** + - Based on stake amount + - Adjusted by collection value + - Influenced by reporting history + +## Reward System + +### Reward Distribution + +1. **Types of Rewards** + - Block rewards for proposers + - Staking rewards for participation + - Commission for delegation service + - Bounties for security enforcement + +2. **Distribution Factors** + - Stake amount + - Participation rate + - Age and maturity + - Commission rates + +```mermaid +graph TD + A[Rewards] -->|Block| B[Proposers] + A -->|Stake| C[Stakers] + A -->|Commission| D[Delegators] + A -->|Bounty| E[Enforcers] +``` + +## Governance + +### Parameter Management + +1. **Configurable Parameters** + - Minimum stake amounts + - Lock periods + - Commission limits + - Slashing ratios + - Reward rates + +2. **Access Control** + - Role-based permissions + - Admin functions + - Emergency controls + - Upgrade mechanisms + +## Token Economics + +### RAZOR Token + +1. **Utility** + - Staking requirement + - Transaction fees + - Governance participation + - Value capture + +2. **sRZR Token** + - Represents staked position + - Transferable stake claims + - Delegation tracking + - Reward distribution + +```mermaid +graph LR + A[RAZOR] -->|Stake| B[sRZR] + B -->|Represents| C[Stake Position] + C -->|Earns| D[Rewards] + D -->|Claimed in| A +``` + +## Related Documentation +- [Architecture Overview](architecture.md) +- [Setup Guide](setup-and-installation.md) +- [API Reference](api-reference.md) +- [Contributing Guidelines](contributing.md) \ No newline at end of file diff --git a/docs/data-models.md b/docs/data-models.md new file mode 100644 index 00000000..745133b0 --- /dev/null +++ b/docs/data-models.md @@ -0,0 +1,242 @@ +# Data Models + +This document describes the core data structures and their relationships in the Oracle Contracts system. + +## Core Data Structures + +### Staker +Represents a participant in the oracle network who stakes RAZOR tokens. + +```solidity +struct Staker { + bool acceptDelegation; // Whether staker accepts delegation + bool isSlashed; // If staker has been slashed + uint8 commission; // Commission rate for delegators (0-100) + uint32 id; // Unique identifier + uint32 age; // Staker's age in the system + address _address; // Staker's address + address tokenAddress; // sRZR token contract address + uint32 epochFirstStakedOrLastPenalized; // Tracking epoch + uint32 epochCommissionLastUpdated; // Last commission update + uint256 stake; // Total staked amount + uint256 stakerReward; // Accumulated rewards +} +``` + +```mermaid +classDiagram + class Staker { + +bool acceptDelegation + +bool isSlashed + +uint8 commission + +uint32 id + +uint32 age + +address _address + +address tokenAddress + +uint32 epochFirstStakedOrLastPenalized + +uint32 epochCommissionLastUpdated + +uint256 stake + +uint256 stakerReward + } +``` + +### Collection +Represents a group of related data sources that need to be reported. + +```solidity +struct Collection { + bool active; // Collection status + uint16 id; // Unique identifier + uint16 occurrence; // Reporting frequency + int8 power; // Decimal adjustment + uint32 epochLastReported; // Last report epoch + uint32 tolerance; // Allowed deviation % + uint32 aggregationMethod; // How to aggregate values + uint16[] jobIDs; // Associated jobs + string name; // Collection name + uint256 result; // Latest result +} +``` + +```mermaid +classDiagram + class Collection { + +bool active + +uint16 id + +uint16 occurrence + +int8 power + +uint32 epochLastReported + +uint32 tolerance + +uint32 aggregationMethod + +uint16[] jobIDs + +string name + +uint256 result + } + Collection "1" --> "*" Job: contains +``` + +### Job +Represents a single data source that needs to be queried. + +```solidity +struct Job { + uint16 id; // Unique identifier + uint8 selectorType; // JSON/XHTML (0-1) + uint8 weight; // Weight in aggregation (1-100) + int8 power; // Decimal adjustment + string name; // Job name + string selector; // Data selector + string url; // Data source URL +} +``` + +```mermaid +classDiagram + class Job { + +uint16 id + +uint8 selectorType + +uint8 weight + +int8 power + +string name + +string selector + +string url + } +``` + +### Block +Represents a confirmed block of oracle data. + +```solidity +struct Block { + bool valid; // Block validity + uint32 proposerId; // Proposer's staker ID + uint16[] ids; // Collection IDs + uint256 iteration; // Block iteration + uint256 biggestStake; // Largest stake + uint256[] medians; // Median values +} +``` + +```mermaid +classDiagram + class Block { + +bool valid + +uint32 proposerId + +uint16[] ids + +uint256 iteration + +uint256 biggestStake + +uint256[] medians + } + Block "1" --> "1" Staker: proposed by + Block "1" --> "*" Collection: contains +``` + +### DataBond +Represents a bond for data reporting commitments. + +```solidity +struct DataBond { + bool active; // Bond status + uint16 collectionId; // Associated collection + uint16 desiredOccurrence; // Desired reporting frequency + uint32 id; // Unique identifier + uint32 epochBondLastUpdated; // Last update epoch + address bondCreator; // Creator's address + uint16[] jobIds; // Associated jobs + uint256 bond; // Bond amount +} +``` + +```mermaid +classDiagram + class DataBond { + +bool active + +uint16 collectionId + +uint16 desiredOccurrence + +uint32 id + +uint32 epochBondLastUpdated + +address bondCreator + +uint16[] jobIds + +uint256 bond + } + DataBond "1" --> "1" Collection: bonds + DataBond "1" --> "*" Job: requires +``` + +### Lock +Represents locked tokens (staking/unstaking). + +```solidity +struct Lock { + uint256 amount; // Locked amount + uint256 unlockAfter; // Unlock epoch +} +``` + +### BountyLock +Represents locked bounty rewards. + +```solidity +struct BountyLock { + uint32 redeemAfter; // Redemption epoch + address bountyHunter; // Hunter's address + uint256 amount; // Bounty amount +} +``` + +## Data Relationships + +```mermaid +graph TD + A[Staker] -->|stakes| B[RAZOR Tokens] + A -->|receives| C[sRZR Tokens] + A -->|reports| D[Collections] + D -->|contains| E[Jobs] + A -->|proposes| F[Blocks] + F -->|confirms| D + G[DataBond] -->|requires| D + G -->|posted by| A + H[Lock] -->|restricts| C + I[BountyLock] -->|rewards| A +``` + +## Storage Layout + +### Staker Storage +- Mapping of addresses to staker IDs +- Mapping of IDs to staker structs +- Total number of stakers +- Maturity levels array + +### Collection Storage +- Mapping of IDs to collection structs +- Mapping of names to collection IDs +- Active collections array +- Total number of collections + +### Block Storage +- Mapping of epochs to blocks +- Current epoch +- Block confirmation status + +### Lock Storage +- Mapping of (address, token, type) to locks +- Mapping of IDs to bounty locks +- Counter for bounty IDs + +## State Transitions + +```mermaid +stateDiagram-v2 + [*] --> Active: Create + Active --> Locked: Lock + Locked --> Unlocked: Time Pass + Unlocked --> Withdrawn: Withdraw + Active --> Slashed: Violation + Slashed --> [*] +``` + +## Related Documentation +- [Architecture Overview](architecture.md) +- [API Reference](api-reference.md) +- [Core Concepts](core-concepts.md) \ No newline at end of file diff --git a/docs/documentation-plan.md b/docs/documentation-plan.md new file mode 100644 index 00000000..b3adf495 --- /dev/null +++ b/docs/documentation-plan.md @@ -0,0 +1,75 @@ +# Documentation Plan for Oracle Contracts + +## Completed Tasks + +### Phase 1: Project Setup & Structure ✓ +1. Create documentation directory structure + - Created all core documentation files + - Set up guides folder + - Established consistent formatting + +2. Create initial README and navigation ✓ + - Main README with project overview + - Documentation index for easy navigation + - Cross-referencing strategy + +### Phase 2: Core Architecture Documentation ✓ +1. Document System Architecture + - High-level system overview + - Component relationships + - Core contract interactions + - Mermaid diagrams for system visualization + +2. Document Core Components + - Block management system + - Bond management system + - Collection management system + - Reward distribution + - Stake management + - Vote management + - Random number generation + +### Phase 3: Technical Documentation ✓ +1. API Reference Documentation + - Interface documentation + - Function signatures + - Events documentation + - Error codes + +2. Data Models Documentation + - Contract storage structures + - State variables + - Struct definitions + - Relationship diagrams + +### Phase 4: Process & Workflow Documentation ✓ +1. Setup & Installation Guide + - Development environment setup + - Dependencies and prerequisites + - Build and deployment steps + - Configuration options + +2. Contributing Guidelines + - Development workflow + - Code style guidelines + - Testing requirements + - Pull request process + +### Phase 5: Conceptual Documentation ✓ +1. Core Concepts Guide + - Oracle system fundamentals + - Consensus mechanism + - Tokenomics + - Governance model + +2. User Guides + - Staking guide + - Voting procedures + - Bond management + - Delegation process + +## Related Documentation +- [Architecture Overview](architecture.md) +- [Setup Guide](setup-and-installation.md) +- [API Reference](api-reference.md) +- [Core Concepts](core-concepts.md) \ No newline at end of file diff --git a/docs/guides/bonds.md b/docs/guides/bonds.md new file mode 100644 index 00000000..5ffd3367 --- /dev/null +++ b/docs/guides/bonds.md @@ -0,0 +1,271 @@ +# Data Bonds Guide + +This guide explains how to create and manage data bonds in the Oracle Network. + +## Overview + +Data bonds are a mechanism for ensuring reliable data reporting by requiring bond creators to lock RAZOR tokens as collateral. Bonds are associated with collections of data sources (jobs) and their reporting frequency. + +## Bond Creation Process + +### 1. Prerequisites + +Before creating a data bond: +- Have sufficient RAZOR tokens +- Plan your data sources +- Understand reporting requirements +- Calculate minimum bond + +### 2. Creating a Bond + +```solidity +function createBond( + uint32 epoch, + Structs.Job[] memory mulJobs, + uint256 bond, + uint16 occurrence, + int8 collectionPower, + uint32 collectionTolerance, + uint32 collectionAggregation, + string calldata collectionName +) +``` + +Key parameters: +- `mulJobs`: Array of data source jobs +- `bond`: Amount of RAZOR to lock +- `occurrence`: Reporting frequency +- `collectionPower`: Decimal adjustment +- `collectionTolerance`: Allowed deviation +- `collectionAggregation`: Aggregation method + +```mermaid +sequenceDiagram + participant User + participant BondManager + participant CollectionManager + participant RAZOR + + User->>BondManager: Create Bond + BondManager->>CollectionManager: Create Jobs + BondManager->>CollectionManager: Create Collection + User->>RAZOR: Approve Tokens + RAZOR->>BondManager: Transfer Bond +``` + +## Bond Management + +### 1. Updating Jobs + +```solidity +function updateDataBondJob( + uint32 bondId, + uint8 jobIndex, + uint8 weight, + int8 power, + JobSelectorType selectorType, + string calldata selector, + string calldata url +) +``` + +When to update: +- Data source changes +- Weight adjustments +- Selector modifications +- URL updates + +### 2. Updating Collections + +```solidity +function updateDataBondCollection( + uint32 bondId, + uint16 collectionId, + uint16 desiredOccurrence, + uint32 tolerance, + uint32 aggregationMethod, + int8 power, + uint16[] memory jobIds +) +``` + +Collection updates for: +- Frequency changes +- Tolerance adjustments +- Aggregation modifications +- Job reorganization + +### 3. Adding Jobs + +```solidity +function addJobsToCollection( + uint32 bondId, + Structs.Job[] memory jobs, + uint16 desiredOccurrence, + int8 collectionPower, + uint32 collectionTolerance, + uint32 collectionAggregation +) +``` + +Considerations: +- Maximum job limit +- Bond requirements +- Reporting frequency +- Collection parameters + +## Bond Economics + +### 1. Bond Requirements + +```mermaid +graph TD + A[Bond Amount] --> B{Requirements} + B --> C[Minimum Bond] + B --> D[Per Job Deposit] + B --> E[Occurrence Rate] + E --> F[Reporting Frequency] +``` + +Calculations: +- Minimum bond amount +- Deposit per job +- Occurrence limitations +- Total requirements + +### 2. Adding More Bond + +```solidity +function addBond( + uint32 bondId, + uint256 bond, + uint16 desiredOccurrence +) +``` + +When to add: +- Increase frequency +- Add more jobs +- Enhance security +- Meet requirements + +### 3. Unstaking Bond + +```solidity +function unstakeBond(uint32 bondId, uint256 bond) +``` + +Process: +1. Initiate unstake +2. Wait lock period +3. Withdraw funds +4. Maintain minimums + +## Bond Status Management + +### 1. Setting Status + +```solidity +function setDatabondStatus(bool databondStatus, uint16 bondId) +``` + +Status options: +- Active: Collection reporting +- Inactive: Reporting paused +- Requirements: Minimum bond + +### 2. Monitoring + +Track: +- Collection status +- Reporting frequency +- Bond amounts +- Job performance + +## Advanced Topics + +### 1. Bond Optimization + +Strategies for: +- Efficient job selection +- Frequency optimization +- Bond amount balancing +- Cost management + +### 2. Security Considerations + +Protection against: +- Data manipulation +- Economic attacks +- Technical failures +- Market conditions + +### 3. Performance Monitoring + +Monitor: +- Reporting accuracy +- Collection health +- Bond efficiency +- Economic metrics + +## Troubleshooting + +### Common Issues + +1. **Creation Problems** + - Insufficient bond + - Invalid jobs + - Wrong parameters + - Gas issues + +2. **Update Failures** + - Timing restrictions + - Invalid changes + - Permission issues + - Bond requirements + +3. **Withdrawal Issues** + - Lock period + - Minimum requirements + - Status conflicts + - Technical errors + +## Best Practices + +### 1. Bond Creation +- Start with test amounts +- Verify data sources +- Check requirements +- Monitor performance + +### 2. Management +- Regular updates +- Proactive monitoring +- Economic optimization +- Risk management + +### 3. Withdrawal Strategy +- Plan ahead +- Maintain minimums +- Consider timing +- Monitor locks + +## Tools and Resources + +### 1. Calculation Tools +- Bond requirements +- Occurrence rates +- Economic projections +- Gas estimates + +### 2. Monitoring Tools +- Collection status +- Reporting metrics +- Bond efficiency +- Performance analytics + +## Related Documentation +- [Core Concepts](../core-concepts.md) +- [API Reference](../api-reference.md) +- [Architecture](../architecture.md) +- [Staking Guide](staking.md) \ No newline at end of file diff --git a/docs/guides/delegation.md b/docs/guides/delegation.md new file mode 100644 index 00000000..cab9ae06 --- /dev/null +++ b/docs/guides/delegation.md @@ -0,0 +1,231 @@ +# Delegation Guide + +This guide explains how to participate in the Oracle Network through delegation. + +## Overview + +Delegation allows users to participate in the network without running a node by delegating their RAZOR tokens to active stakers. Delegators earn rewards while stakers manage the operational aspects. + +## Delegation Process + +### 1. Prerequisites + +Before delegating: +- Have RAZOR tokens +- Research stakers +- Understand commission rates +- Consider lock periods + +### 2. Choosing a Staker + +Factors to consider: +- Performance history +- Commission rate +- Total stake +- Age/maturity +- Uptime record + +```mermaid +graph TD + A[Choose Staker] --> B{Evaluation} + B --> C[Performance] + B --> D[Commission] + B --> E[Stake Size] + B --> F[Maturity] + B --> G[Uptime] +``` + +### 3. Delegating Tokens + +```solidity +function delegate(uint32 stakerId, uint256 amount) +``` + +Process: +1. Approve RAZOR tokens +2. Select staker +3. Specify amount +4. Execute delegation + +```mermaid +sequenceDiagram + participant Delegator + participant StakeManager + participant Staker + participant RAZOR + + Delegator->>RAZOR: Approve Tokens + Delegator->>StakeManager: Delegate + StakeManager->>Staker: Increase Stake + StakeManager->>Delegator: Issue sRZR +``` + +## Reward System + +### 1. Reward Distribution + +How rewards work: +- Staker earns rewards +- Commission deducted +- Remainder distributed +- Based on delegation share + +### 2. Commission Structure + +Understanding fees: +- Base commission rate +- Maximum limits +- Update frequency +- Calculation method + +```mermaid +graph LR + A[Total Rewards] -->|Minus Commission| B[Net Rewards] + B -->|Proportional| C[Delegator Share] + A -->|Commission %| D[Staker Share] +``` + +## Managing Delegation + +### 1. Monitoring Performance + +Track: +- Reward earnings +- Staker performance +- Network participation +- Commission changes + +### 2. Unstaking Process + +```solidity +function unstake(uint32 stakerId, uint256 sAmount) +``` + +Steps: +1. Initiate unstake +2. Wait lock period +3. Initiate withdrawal +4. Complete withdrawal + +```mermaid +stateDiagram-v2 + [*] --> Delegated + Delegated --> Unstaking: Unstake + Unstaking --> Withdrawing: Lock Period + Withdrawing --> Withdrawn: Claim + Withdrawn --> [*] +``` + +## Risk Management + +### 1. Staker Risks + +Potential issues: +- Poor performance +- Commission changes +- Slashing events +- Inactivity + +### 2. Network Risks + +Consider: +- Market conditions +- Protocol changes +- Technical issues +- Economic factors + +### 3. Mitigation Strategies + +Best practices: +- Diversify delegations +- Monitor actively +- Plan exit strategy +- Stay informed + +## Advanced Topics + +### 1. Delegation Strategy + +Optimization: +- Timing entries +- Size management +- Staker selection +- Exit planning + +### 2. Reward Optimization + +Maximizing returns: +- Commission comparison +- Performance tracking +- Compound strategy +- Tax efficiency + +### 3. Portfolio Management + +Balancing: +- Risk levels +- Return targets +- Lock periods +- Liquidity needs + +## Troubleshooting + +### Common Issues + +1. **Delegation Problems** + - Insufficient balance + - Staker not accepting + - Wrong parameters + - Technical issues + +2. **Reward Issues** + - Distribution delays + - Calculation errors + - Commission changes + - Network issues + +3. **Withdrawal Problems** + - Lock periods + - Gas costs + - Timing issues + - Technical errors + +## Best Practices + +### 1. Due Diligence +- Research stakers +- Check history +- Verify commission +- Monitor performance + +### 2. Risk Management +- Start small +- Diversify +- Monitor regularly +- Plan exits + +### 3. Record Keeping +- Track delegations +- Monitor rewards +- Document changes +- Tax implications + +## Tools and Resources + +### 1. Analysis Tools +- Staker metrics +- Performance tracking +- Reward calculator +- Risk assessment + +### 2. Monitoring Tools +- Network status +- Staker performance +- Reward tracking +- Commission changes + +## Related Documentation +- [Core Concepts](../core-concepts.md) +- [API Reference](../api-reference.md) +- [Architecture](../architecture.md) +- [Staking Guide](staking.md) \ No newline at end of file diff --git a/docs/guides/staking.md b/docs/guides/staking.md new file mode 100644 index 00000000..742c4146 --- /dev/null +++ b/docs/guides/staking.md @@ -0,0 +1,197 @@ +# Staking Guide + +This guide explains how to participate in the Oracle Network through staking RAZOR tokens. + +## Overview + +Staking is the primary mechanism for participating in the Oracle Network. By staking RAZOR tokens, participants: +- Secure the network +- Earn rewards +- Participate in data reporting +- Gain voting rights + +## Staking Process + +### 1. Prerequisites + +Before staking, ensure you have: +- RAZOR tokens in your wallet +- Minimum required stake amount +- ETH for transaction fees + +### 2. Direct Staking + +```solidity +// 1. Approve RAZOR tokens +IERC20(razorAddress).approve(stakeManager, amount); + +// 2. Stake tokens +stakeManager.stake(currentEpoch, amount); +``` + +When you stake: +1. Your RAZOR tokens are locked in the contract +2. You receive sRZR tokens representing your stake +3. Your staker ID is assigned +4. You can start participating in oracle operations + +### 3. Stake Management + +#### Adding More Stake +```solidity +stakeManager.stake(currentEpoch, additionalAmount); +``` + +#### Checking Your Stake +```solidity +uint256 stake = stakeManager.getStake(stakerId); +uint256 influence = stakeManager.getInfluence(stakerId); +``` + +#### Understanding Maturity +- Stake maturity increases over time +- Higher maturity = more influence +- Influence = Stake × Maturity +- Maturity resets on penalties + +## Unstaking Process + +### 1. Initiate Unstake +```solidity +stakeManager.unstake(stakerId, sRZRAmount); +``` + +### 2. Wait Lock Period +- Must wait `unstakeLockPeriod` epochs +- Lock prevents quick withdrawals +- Ensures network security + +### 3. Initiate Withdrawal +```solidity +stakeManager.initiateWithdraw(stakerId); +``` + +### 4. Complete Withdrawal +```solidity +stakeManager.unlockWithdraw(stakerId); +``` + +## Rewards + +### Types of Rewards +1. Block Rewards + - For proposing valid blocks + - Based on stake size + +2. Reporting Rewards + - For accurate data reporting + - Based on participation + +3. Age Rewards + - For long-term staking + - Based on maturity + +### Claiming Rewards +```solidity +stakeManager.claimStakerReward(); +``` + +## Security Considerations + +### 1. Slashing Conditions +- Invalid data reporting +- Malicious behavior +- Inactivity +- Protocol violations + +### 2. Slashing Penalties +- Loss of stake +- Reset of maturity +- Temporary exclusion + +### 3. Best Practices +- Monitor your node +- Maintain uptime +- Report accurately +- Stay informed + +## Node Operation + +### 1. Setup Requirements +- Reliable hardware +- Stable internet +- Regular maintenance +- Security measures + +### 2. Monitoring +- Watch performance +- Check rewards +- Monitor slashing +- Track influence + +## Advanced Topics + +### 1. Commission Management +```solidity +// Set delegation acceptance +stakeManager.setDelegationAcceptance(true); + +// Update commission rate +stakeManager.updateCommission(newRate); +``` + +### 2. Lock Extensions +```solidity +// Reset unstake lock if needed +stakeManager.resetUnstakeLock(stakerId); +``` + +### 3. Influence Optimization +- Balance stake size +- Maintain uptime +- Avoid penalties +- Build maturity + +## Troubleshooting + +### Common Issues + +1. **Failed Stake** + - Insufficient balance + - Not approved + - Below minimum + +2. **Failed Unstake** + - Existing locks + - Wrong timing + - Invalid amount + +3. **Failed Withdrawal** + - Lock period active + - Wrong timing + - System paused + +## Best Practices + +1. **Risk Management** + - Start small + - Increase gradually + - Monitor performance + - Maintain reserves + +2. **Operational Excellence** + - Regular monitoring + - Quick response + - Stay updated + - Community engagement + +3. **Long-term Strategy** + - Build maturity + - Optimize influence + - Plan upgrades + - Network participation + +## Related Documentation +- [Core Concepts](../core-concepts.md) +- [API Reference](../api-reference.md) +- [Architecture](../architecture.md) \ No newline at end of file diff --git a/docs/guides/voting.md b/docs/guides/voting.md new file mode 100644 index 00000000..020c9503 --- /dev/null +++ b/docs/guides/voting.md @@ -0,0 +1,217 @@ +# Voting Guide + +This guide explains how to participate in the Oracle Network's consensus process through voting. + +## Overview + +The Oracle Network uses a commit-reveal voting scheme to ensure fair and tamper-resistant data reporting. Stakers participate in multiple phases: +1. Commit Phase - Submit encrypted votes +2. Reveal Phase - Reveal actual values +3. Dispute Phase - Challenge incorrect values +4. Resolution Phase - Finalize results + +## Voting Process + +### 1. Commit Phase + +During the commit phase, stakers: +1. Query assigned data sources +2. Aggregate results +3. Create a Merkle tree of values +4. Submit the Merkle root as commitment + +```mermaid +sequenceDiagram + participant Staker + participant DataSource + participant Network + + Staker->>DataSource: Query Data + DataSource->>Staker: Return Values + Staker->>Staker: Aggregate Results + Staker->>Staker: Build Merkle Tree + Staker->>Network: Submit Commitment +``` + +#### Creating a Commitment +```solidity +struct Commitment { + uint32 epoch; + bytes32 commitmentHash; +} +``` + +Key considerations: +- Use secure random salt +- Include all assigned collections +- Meet depth requirements +- Submit within timeframe + +### 2. Reveal Phase + +During the reveal phase, stakers: +1. Reveal original values +2. Provide Merkle proofs +3. Validate other reveals +4. Build consensus + +```mermaid +sequenceDiagram + participant Staker + participant Network + participant Validators + + Staker->>Network: Reveal Values + Staker->>Network: Submit Proofs + Network->>Validators: Validate Reveals + Validators->>Network: Confirm Valid +``` + +#### Vote Weight Calculation +Vote weight depends on: +- Staker's influence (stake × maturity) +- Accuracy history +- Participation rate +- Value deviation + +### 3. Dispute Phase + +Disputes can be raised when: +- Values deviate significantly +- Proofs are invalid +- Rules are violated + +```mermaid +stateDiagram-v2 + [*] --> ValidReveal + ValidReveal --> Disputed: Challenge + Disputed --> Resolution + Resolution --> Slashed: Invalid + Resolution --> Confirmed: Valid +``` + +#### Dispute Resolution +1. Challenge submission +2. Evidence verification +3. Stake implications +4. Result adjustment + +### 4. Finalization + +Results are finalized when: +1. Sufficient votes received +2. Consensus achieved +3. Dispute period passed +4. Block confirmed + +## Best Practices + +### 1. Data Collection +- Use reliable data sources +- Implement proper error handling +- Validate input data +- Handle edge cases + +### 2. Vote Submission +- Meet timing requirements +- Verify commitments +- Double-check values +- Monitor gas costs + +### 3. Security +- Secure salt generation +- Safe key management +- Network monitoring +- Backup procedures + +## Advanced Topics + +### 1. Influence Optimization +- Maintain high uptime +- Build maturity +- Avoid slashing +- Strategic staking + +### 2. Merkle Tree Management +```solidity +struct MerkleTree { + AssignedAsset[] values; + bytes32[][] proofs; + bytes32 root; +} +``` + +Key aspects: +- Proper construction +- Proof verification +- Tree balancing +- Depth requirements + +### 3. Dispute Strategies +When to dispute: +- Clear violations +- Significant deviations +- Provable cases +- Economic viability + +## Error Handling + +### Common Issues + +1. **Failed Commits** + - Invalid format + - Wrong timing + - Gas issues + - Tree depth mismatch + +2. **Failed Reveals** + - Invalid proofs + - Wrong values + - Timing issues + - Gas limitations + +3. **Dispute Problems** + - Insufficient evidence + - Wrong procedure + - Timing constraints + - Economic factors + +## Monitoring and Analytics + +### 1. Performance Metrics +- Vote success rate +- Dispute involvement +- Consensus participation +- Reward efficiency + +### 2. Network Statistics +- Total influence +- Vote distribution +- Value convergence +- Dispute frequency + +### 3. Economic Analysis +- Reward projections +- Slashing risk +- Gas optimization +- ROI calculations + +## Tools and Resources + +### 1. Development Tools +- Test networks +- Simulation tools +- Monitoring systems +- Analytics platforms + +### 2. Reference Materials +- Technical specifications +- API documentation +- Example implementations +- Best practices + +## Related Documentation +- [Core Concepts](../core-concepts.md) +- [API Reference](../api-reference.md) +- [Architecture](../architecture.md) +- [Staking Guide](staking.md) \ No newline at end of file diff --git a/docs/setup-and-installation.md b/docs/setup-and-installation.md new file mode 100644 index 00000000..519bae1b --- /dev/null +++ b/docs/setup-and-installation.md @@ -0,0 +1,203 @@ +# Setup and Installation Guide + +This guide will walk you through the process of setting up the Oracle Contracts development environment and deploying the contracts to various networks. + +## Prerequisites + +- Node.js >= 16 +- Git +- Yarn or npm +- Access to an Ethereum node (local or remote) + +## Environment Setup + +1. Clone the repository: +```bash +git clone https://github.com/razor-network/contracts.git +cd contracts +``` + +2. Install dependencies: +```bash +yarn install +# or +npm install +``` + +3. Set up environment variables: +```bash +cp .env.tpl .env +``` + +Edit `.env` with your configuration: +``` +MNEMONIC=your mnemonic phrase +INFURA_PROJECT_ID=your infura project id +ETHERSCAN_API_KEY=your etherscan api key +``` + +## Development Environment + +### Local Development + +1. Start a local Hardhat node: +```bash +npm run start:local +``` + +2. In a new terminal, deploy contracts to local network: +```bash +npm run deploy +``` + +### Running Tests + +1. Run the full test suite: +```bash +npm test +``` + +2. Run specific test scenarios: +```bash +npm run scenarios +``` + +3. Generate coverage report: +```bash +npm run coverage +``` + +Coverage requirements: +- Statements: 90% +- Branches: 60% +- Functions: 85% +- Lines: 86% + +### Code Quality + +1. Run linting: +```bash +# Run all linters +npm run lint + +# Fix linting issues +npm run lint:fix + +# Run specific linters +npm run lint:sol # Solidity files +npm run lint:js # JavaScript files +``` + +## Deployment + +### Network Configuration + +The system supports deployment to multiple networks. Configure network settings in `hardhat.config.js`: + +```javascript +networks: { + mainnet: { + url: `https://mainnet.infura.io/v3/${process.env.INFURA_PROJECT_ID}`, + accounts: { + mnemonic: process.env.MNEMONIC + } + }, + rinkeby: { + url: `https://rinkeby.infura.io/v3/${process.env.INFURA_PROJECT_ID}`, + accounts: { + mnemonic: process.env.MNEMONIC + } + } +} +``` + +### Named Accounts + +Configure named accounts in `hardhat.config.js` for different networks: + +```javascript +namedAccounts: { + deployer: { + default: 0, + 1: 0, // mainnet + 4: '0xA296a3d5F026953e17F472B497eC29a5631FB51B', // rinkeby + }, + feeCollector: { + default: 1, + 1: '0xa5610E1f289DbDe94F3428A9df22E8B518f65751', // mainnet + 4: '0xa250ac77360d4e837a13628bC828a2aDf7BabfB3', // rinkeby + } +} +``` + +### Deployment Process + +1. Deploy to a specific network: +```bash +npx hardhat --network deploy +``` + +2. Verify contracts on Etherscan: +```bash +npx hardhat --network etherscan-verify +``` + +### Deployment Scripts + +Deployment scripts in the `deploy/` folder are executed in sequence: + +1. `001_deploy_governance.js` - Deploys governance contract +2. `002_deploy_block_manager.js` - Deploys block manager +3. `003_deploy_collection_manager.js` - Deploys collection manager +4. `004_deploy_stake_manager.js` - Deploys stake manager +5. `005_deploy_reward_manager.js` - Deploys reward manager +6. `006_deploy_vote_manager.js` - Deploys vote manager +7. `007_deploy_delegator.js` - Deploys delegator +8. `008_deploy_razor.js` - Deploys RAZOR token +9. `009_deploy_staked_token_factory.js` - Deploys staked token factory +10. `010_deploy_random_no_manager.js` - Deploys random number manager +11. `011_deploy_bond_manager.js` - Deploys bond manager + +## Gas Analysis + +1. Generate gas usage report: +```bash +npm run gas +``` + +2. Compare gas usage between versions: +```bash +npm run gasCompare +``` + +## Troubleshooting + +### Common Issues + +1. **Compilation Errors** + - Ensure Node.js version >= 16 + - Clear hardhat cache: `npx hardhat clean` + - Rebuild: `npm run compile` + +2. **Deployment Failures** + - Check network configuration + - Verify account has sufficient funds + - Ensure correct environment variables + +3. **Test Failures** + - Run with `--verbose` flag for detailed output + - Check test coverage for specific components + +### Support + +For additional support: +1. Check [GitHub Issues](https://github.com/razor-network/contracts/issues) +2. Review [Core Concepts](core-concepts.md) +3. Consult [API Reference](api-reference.md) + +## Next Steps + +- Review [Architecture Documentation](architecture.md) +- Understand [Core Concepts](core-concepts.md) +- Explore [API Reference](api-reference.md) +- Learn about [Contributing](contributing.md) \ No newline at end of file