# Welcome

Learn how to deploy and run your on-chain trading vaults, or query on-chain token prices.

Learn the basics of Rigoblock

{% content-ref url="/pages/5K7qm63mlEaiKnTwuwL2" %}
[Introduction to Rigoblock](/introduction-to-rigoblock)
{% endcontent-ref %}

Jump to the technical overview of the smart contracts

{% content-ref url="/pages/U6YKG1oQWySDnOV9e5MY" %}
[Contracts](/contracts)
{% endcontent-ref %}

Find the deployed smart contracts

{% content-ref url="/pages/AtyRyGckeYgc2Ayii96c" %}
[Deployments](/deployments)
{% endcontent-ref %}

Get an on-chain price feed for any token

{% content-ref url="/pages/9rfeOSvTQx57MSHv3QVj" %}
[Oracles and Price Feeds](/oracles-and-price-feeds)
{% endcontent-ref %}


# Introduction to Rigoblock

The Rigoblock protocol is a set of smart contracts for deploying and running on-chain token management strategies with real time reconciliation of positions and value.

At its heart, it consists of a very light pool proxy contract (\~227k gas units) which delegates calls to a pool implementation contract.

The implementation address is stored in the proxy, and can only be updated upon its operator's action in a trust-minimized way, by querying the new address from a beacon contract. The new address is retrieved from the proxy factory contract, which can be modified only by the Rigoblock DAO through an on-chain governance vote. The Rigoblock DAO cannot autonomously take over control of the pool, as each pool operator must upgrade to the new implementation address the upgrade to take effect.

Since the use of a proxy and an implementation can lead to undesired storage clashing and possible overwriting, each variable (or batch of variables) is assigned a deterministic and randomly big-enough storage slot, so that accidental storage cannot happen.

Before upgrading the implementation, the Rigoblock Governance must assess that newly-introduced variables do not overlap existing storage slots. Furthermore, before whitelisting an extension to the protocol, the Rigoblock Governance must ensure that the storage slot used by the extension does not overlap to existing storage.

The pool implementation code extends the core functionalities of the pool itself. Further methods are added through adapters, which are accessible in write-mode for the pool operator only, while in read-mode for everyone else. These adapters allow interaction with external smart contracts. In order to guarantee smooth interaction with external applications, the adapters are updated by the governance, meaning each pool will use the same adapter when interacting with a certain application, regardless of the implementation. By design, only the pool operator can access the adapters in write mode, preventing a pool takeover by the governance (even in the case of a rogue attack on the governance).


# Deployments

Rigoblock has been deployed on multiple blockchains using [deterministic deployment](https://ethereum-magicians.org/t/deterministic-deployment-proxy-magic-wrapped-in-magic/3261). Currently supported mainnet chains are:

* Ethereum Mainnet
* Arbitrum
* Base
* Optimism
* Bsc
* Unichain
* Polygon

{% content-ref url="/pages/6D7QLLHGeKBEAcqfvIuK" %}
[Deployed Contracts - v4](/deployments/deployed-contracts-v4)
{% endcontent-ref %}

{% content-ref url="/pages/iz1RJXe1JLpOtpqkv8Ag" %}
[Deployed Contracts - v3](/deployments/deployed-contracts-v3)
{% endcontent-ref %}


# Deployed Contracts - v4

## Supported Networks

```
Mainnets
1: ethereum,
10: optimism,
56: bsc,
130: unichain,
137: polygon,
8453: base,
42161: arbitrum

Testnets
11155111: sepolia
```

## Protocol Addresses

### Deps

```
Authority 0xe35129A1E0BdB913CF6Fd8332E9d3533b5F41472
PoolRegistry 0x06767e8090bA5c4Eca89ED00C3A719909D503ED6
ExtensionsMapDeployer 0x39550A76814B0379C9c2981930F18b891A5BF6F7
```

### Core

```
SmartPool: [
    0xC90c7523ac52F510d21D74255740C1e972a3507E - v4.3.3 (canonical)
    0xee84f3D9095dc173a5ed1c60a7f30C3ff3064bBD - v4.3.2
    0x70fF4c1317C64B24BAb253bE6D6ac1adBf1d9869 - v4.3.1
    0xfC70DE6783D2aC32bDf9Ab4b375F8D77a8764393 - v4.3.0
    0x3D665d334E99cc6Fee0Ffc505FC7Fc1C1dD3515f - v4.2.0
    0x7f9737cBB7740C3486d7c6745f476D3aA32e59e1 - v4.1.2
    0x1DB955265B8DC18715cAb12E805F9b71Fa545420 - v4.1.1
]
RigoblockPoolProxyFactory 0x8DE8895ddD702d9a216E640966A98e08c9228f24
```

Notice: deterministic deployment requires 0xeb0c08Ad44af89BcBB5Ed6dD28caD452311B8516 as the implementation address in the constructor to obtain the same factory address on new chains.

### Extensions - v4.3.3

```
ExtensionsMap: 0x91F292b2d790C2808e1bFDD5c75Bd999ab7b9d61
EUpgrade 0x6A17ca05b112485Bd5c73215F275Baff7F980ac6
EApps: [
ethereum: 0x06B38dB78C62022647a01F85392E959F5277292A,
arbitrum: 0x62C122358F7ce8471098541F7aF88E02E015615E,
base: 0xd7C370654eF907F0979C6956F49078df4190e475,
bsc: 0x25F6cFDE3A728A20426854A0D98179690a1d9962,
optimism: 0xB30f4322B9368D3Ba74a3e94eee96820fF2d3F73,
unichain: 0xD85e2A1ce6a7770fBe685C897BDe5532eE0721D8,
polygon: 0x6f38b69C65222186Fe4c60452360e7a06CbD4B26,
sepolia: 0xdae4aAFb3ff7b3183993bFac80b2415640Dc2bc1
]
EOracle: [
ethereum: 0x3BFD6cd56e40082fA1ca9b89134EC8cFaEF7e3cc,
arbitrum: 0x62c8a84D21C7065B802D37a815CFae6982bB28d2,
base: 0x6b076dde21513db069315370f460d4a20d96e98b,
bsc: 0xF8e859EdB0827ce5B77995ca4b47aE3Dee046a38,
optimism: 0x8710AD4E33581ECEfD9174f17D81d610672870A4,
unichain: 0x01978307408599CC0ebE160ac394A739E3e5cCC8,
polygon: 0xb9E5db73e18DB4335485AA01BCEE369C78615d1F,
sepolia: 0xB536513F660bdce3b68A937f979410d72241a517
]
ECrosschain: 0xa3f20B68A7A967f5611ebd9ce7E8CB590F95BB59
ENavView: [
ethereum: 0x5B68B04cd562D3d7E02230a80b78E84FeCB69860,
arbitrum: 0xc103c8e4bD9fC698C2471Eb29FA1080a58a17E7F,
base: 0x87ac9df2cefcad9959d565b88fd91c353f04b38e,
bsc: 0xAD5d8b6fCa1A82B12e0a915Ae9528aD971D1aD0c,
optimism: 0x90a09F353161E79347D6aa097731e068A293a7cE,
unichain: 0xef05ac254D6629678627E563c16338659eb1c09C,
polygon: 0x701276b2a235De28aB7A34B2a924f07ce0C8C3C5,
sepolia: 0xAA16F560A6A96A1FfFef40B1af5d621b97Bafb02
]
EGmxCallback: 0x9e5558b99DFc2c4Bda4Cf63B60120B4D730D1278 (Arbitrum only)
```

## Adapters

<pre><code>AMulticall: 0x04EdE1591733793d2321C0393f318cF83d215bF0
[
    ethereum: 0x9cD3CB7CF9392182890d0b5Fe7d92BFD7539afFC,
    arbitrum: 0x9cD3CB7CF9392182890d0b5Fe7d92BFD7539afFC,
    base: 0x9cD3CB7CF9392182890d0b5Fe7d92BFD7539afFC,
    bsc: 0x9cD3CB7CF9392182890d0b5Fe7d92BFD7539afFC,
    optimism: 0x9cD3CB7CF9392182890d0b5Fe7d92BFD7539afFC,
    unichain: 0x1DC90d2C0d5312dcBC31be6Ccd23b03bf251fFc6,
    polygon: 0x9cD3CB7CF9392182890d0b5Fe7d92BFD7539afFC,
    sepolia: 0x1DC90d2C0d5312dcBC31be6Ccd23b03bf251fFc6
]
<strong>AStaking: [
</strong>    ethereum: 0x70A82fd79983Eb659874A16f56Df593ccE050e77,
    arbitrum: 0x4672fE808ce3dA430128ad611E251b896abe689E,
    base: 0x9E9abF328B5d1f4b4c66715cB54cA0F66225FBfa,
    bsc: 0xcfDAC3f80a99ebB4d0F951a9C2aa40138992eCD1,
    optimism: 0x21B423Ad9488CAD08E06c50a5DB0F65AAa813254,
    unichain: 0x77f4cF40adC6026B0e8C0df088E0B1459005922c,
    polygon: 0xB0B97506516B3aD835Cfa6124F446bA75C4B9653,
    sepolia: 0x7CD4d2c1e816123da38cc6e56b7f893Ff8C3a756
]
AUniswap: [
    ethereum: 0x8d7cF3D7f21350E00f46068D8905F2De1D3963E9,
    arbitrum: 0xFe9B49638523ebB3A0047e2ECE9E3b9BCA7D95A0,
    base: 0x3E3A38bb061c51Dde0725fCDA70C0D4FCDafC7D1,
    bsc: 0x1d43cDf7DA675aE777A11A4bEeb956b38bf1F3C4,
    optimism: 0x3E3A38bb061c51Dde0725fCDA70C0D4FCDafC7D1,
    unichain: 0x3E3A38bb061c51Dde0725fCDA70C0D4FCDafC7D1,
    polygon: 0x73B4Bc91aCa9Fe1312763B1138e42b02f1D54B1C,
    sepolia: 0x16434d7f981eB308Faa122154502df01125A7951
]
AUniswapRouter: [
    ethereum: 0x8d89AC596804704Fff512DAe5cAC19319F3AB560,
    arbitrum: 0x27A707296078C535b8eCabc3A5E9B5E26a9C2140,
    base: 0x2b75aD5cB2fa53fF93D20F38b5f3264Fbd1A6f82,
    bsc: 0x1dE6BA9EC7b30988af35F52A0Fce434409FB88A6,
    optimism: 0xE1db51fa21EB0D185778d8c25dF33FA356f34730,
    unichain: 0x767515c8A9d34dC66A5160bD58cd1d3EE03dAb00,
    polygon: 0xc4Eb59bf8606d96016af3664C5FDb08D67234078,
    sepolia: 0x1CF61a7384C939B876A1F30129e6E18991b9cdD4
]
AIntents: [
    ethereum: 0xc82a3Aa9985fe3BA6da13b41c4fD1635F1C816D5,
    arbitrum: 0x2d02E0986C1C9C9a3D2a7B5015d59bCE0D57F6be,
    base: 0x798F9BEB0cB39E656e9794229E75c05D20193e1a,
    bsc: 0xE2dD97d7377472a2E8A50135C63BEdd723e22912,
    optimism: 0x05E362a731Ad651b26206ABd0A59019ece210DE6,
    unichain: 0x798F9BEB0cB39E656e9794229E75c05D20193e1a,
    polygon: 0xffaa05503b230C053a929eD98c3c6F3f67AAA0f6,
    sepolia: 0x1919bB149CcCb1Dbca16BaF44996a0874E9F7Fc6
]
A0xRouter: 0xe03263BB518E780e890f93449339431e90a850A7
AGmxV2: 0xB3160c9A7D9076b6a24ddE5Bc72Bb778644d67Ad (Arbitrum only)
</code></pre>


# Deployed Contracts - v3

Notice: Deprecated - v3 pools should upgrade to v4. Funds in v3 pools can be withdrawn at any time. The v3 protocol has been deployed on the following chains:

```
1: ethereum, 10: optimism, 56: bsc, 130: unichain, 137: polygon, 8453: base, 42161: arbitrum
11155111: sepolia
```

## Protocol Addresses

### Deps

```
Authority 0xe35129A1E0BdB913CF6Fd8332E9d3533b5F41472
PoolRegistry 0x06767e8090bA5c4Eca89ED00C3A719909D503ED6
```

### Core

```
RigoblockV3Pool 0x7Df14Ba4a5f565cD56206e49Fc66b3002A91841d
RigoblockPoolProxyFactory 0x8DE8895ddD702d9a216E640966A98e08c9228f24
```

### Extensions

```
EUpgrade 0x64BcA3673c8990B11225E9f49E6da554180690fc
EWhitelist 0xB43baD2638696F8bC82247B92bD56B8DF37d89aB
AMulticall, AGovernance, AStaking - see v4 page
```


# Deployed Contracts - Staking

Staking suite

### mainnet

```
ERC20Proxy 0x8C96182c1B2FE5c49b1bc9d9e039e369f131ED37
RigoToken 0x4FbB350052Bca5417566f188eB2EBCE5b19BC964
Inflation 0x3c602D3C6140073DF26BC1f42196484311C946AB
ProofOfPerformance 0xC3736344ee0bcE9bDe5D231060f03990b798f030
GrgVault 0xfbd2588b170Ff776eBb1aBbB58C0fbE3ffFe1931
Staking 0x10bffaF04448313Dd64476072391e7f9F7f670ca
StakingProxy 0x730dDf7b602dB822043e0409d8926440395e07fE
```

### arbitrum

```
ERC20Proxy 0x28891F41eA506Ba7eA3Be9f2075AB0aa8b81dD29
RigoToken 0x7F4638A58C0615037deCc86f1daE60E55fE92874
InflationL2 0xA889E90d4F1BA125Df1B4C1f55c7fff9F4377C03
ProofOfPerformance 0xA665C2f17D0Fa2D9f1efaa587B5CF493B23751b0
GrgVault 0xE86a667F239A2531C9d398E81154ba125030497e
Staking 0x83Ed9DaF843DF15Aa33Df1a554177163B32e493d
StakingProxy 0xD495296510257DAdf0d74846a8307bf533a0fB48
```

### optimism

```
ERC20Proxy 0x28891F41eA506Ba7eA3Be9f2075AB0aa8b81dD29
RigoToken 0xEcF46257ed31c329F204Eb43E254C609dee143B3
InflationL2 0xA889E90d4F1BA125Df1B4C1f55c7fff9F4377C03
ProofOfPerformance 0x9e895962AaceE64e42b8fFFa1efF0AcD7F0B6794
GrgVault 0x5932C223186F7856e08A1D7b35ACc2Aa5fC57BfD
Staking 0x27A2b90f5245aeFE3E6F7CAc12df98Be2737D0fa
StakingProxy 0xB844bDCC64a748fDC8c9Ee74FA4812E4BC28FD70
```

### polygon

```
ERC20Proxy 0x28891F41eA506Ba7eA3Be9f2075AB0aa8b81dD29
RigoToken 0xBC0BEA8E634ec838a2a45F8A43E7E16Cd2a8BA99
InflationL2 0xA889E90d4F1BA125Df1B4C1f55c7fff9F4377C03
ProofOfPerformance 0x4170B7d618F3E5B29b3DBdCDADd626fF3746be9A
GrgVault 0xF241De983959A483F376fDC8Ed09DC580BA66109
Staking 0xa9043af31213F236AfB47D0E0FCA8d27CD79a387
StakingProxy 0xC87d1B952303ae3A9218727692BAda6723662dad
```

### bsc

```
ERC20Proxy 0x28891F41eA506Ba7eA3Be9f2075AB0aa8b81dD29
RigoToken 0x3d473C3eF4Cd4C909b020f48477a2EE2617A8e3C
InflationL2 0xA889E90d4F1BA125Df1B4C1f55c7fff9F4377C03
ProofOfPerformance 0xAe1D80A6731c44eeF098D4C6Cf979f596c7cd6F7
GrgVault 0x5494B4193961a467039B92CCfE0138Fe353240d6
Staking 0x30799CAb291C1fBef32Ed4E9531C05F2439Dfd4c
StakingProxy 0xa4a94cCACa8ccCdbCD442CF8eECa0cd98f69e99e
```

### base

```
ERC20Proxy 0x28891F41eA506Ba7eA3Be9f2075AB0aa8b81dD29
RigoToken 0x09188484e1Ab980DAeF53a9755241D759C5B7d60
InflationL2 0xA889E90d4F1BA125Df1B4C1f55c7fff9F4377C03
ProofOfPerformance 0x979Af6DDC1562b4B6D8B2Ab60A1B7221a0d6C8DB
GrgVault 0x7a7fa66B97a9e009ecAB4bCD62e87b2c0b65F21D
Staking 0xF37d731764Ad0856119c6288FE768B5407bD1007
StakingProxy 0xc758Ea84d6D978fe86Ee29c1fbD47B4F302F1992
```

### Unichain

```
ERC20Proxy 0x28891F41eA506Ba7eA3Be9f2075AB0aa8b81dD29
RigoToken 0x03C2868c6D7fD27575426f395EE081498B1120dd
InflationL2 0x3A0C479A2715cc01bC3f744F74Efd45f40f8Dad6
ProofOfPerformance 0xa094BEB834b439bA77763c5889DaBf434Bc26662
GRGVault 0x448366d7C2e0af67D3723De875b7eAf548474A37
Staking 0x87211E18cAae43a8cd865aD37442a137149BB40c
StakingProxy 0x550Ed0bFFdbE38e8Bd33446D5c165668Ea071643
```

### Sepolia

```
ERC20Proxy 0x28891F41eA506Ba7eA3Be9f2075AB0aa8b81dD29
RigoToken 0x076C619e7ebaBe40746106B66bFBed731F2c1339
InflationL2 0x65eA36e096CC23fBC58055365159d20b49A6e34B
ProofOfPerformance 0x26a1b82d6cBFb3dA5500C85C4968993cd07b0399
GRGVault 0x58b5FBe3e8F86a3f22BB9e47129a9FDE4702c221
Staking 0xC8088565d057227Ac0481bc16a5e769b2353f74E
StakingProxy 0xD40edcc947fF35637233d765CB9efCFc10fC8c22
```


# Deployed Contracts - Gov

### Governance Core

```
RigoblockGovernanceFactory 0xc1AdDa7605d2DC47Dd91A930c978Cd6a18D2D760
RigoblockGovernance
    unchain: 0xf9f0432c606359aa1Eeec6c7c2846E012cCDc959
    other: 0xE5D8204f8335e9786ea7Ce382771B865fE73a304
```

### Governance Strategy

```
RigoblockGovernanceStrategy: [
    mainnet: 0x6e1423CB6B0b72316f051fbc3B6Bc54ed5e584Dc,
    arbitrum: 0xe9141C1AA817165aa6375C8fd82A2a800dCbd9dA,
    optimism: 0xc8d95B9a7a0C7f36cb97175e806B3B96D117cFb0,
    polygon: 0x5F63E59e328F2565e71363D3d5F4c29063bB7868,
    bsc: 0x910Aaf1F6818F1044d97DAee22d1eC32647926a7,
    base: 0x1fBEf987C7d87f794548Aa9089E87B9A15dB07EA,
    unichain: 0xeBA708293C4F21131AAc2c384526c9b9b8E2D9d9
]
```

### Governance Proxy

```
RigoblockGovernanceProxy 0x5F8607739c2D2d0b57a4292868C368AB1809767a
```


# Oracles and Price Feeds

Reliable Price Feeds for Token Prices

## Overview

Oracles are essential for providing reliable price data to smart contracts in decentralized finance (DeFi). Our oracle system, built as a Uniswap V4 hook, delivers **block-manipulation resistant** price feeds for on-chain token pairs, across chains using consensus mechanisms like Proof of Stake (PoS), Proof of Authority (PoA), and sequencer-based systems (e.g., Ethereum L2s). Our oracle offers a robust, on-chain solution optimized for DeFi applications requiring secure and manipulation-resistant price data.

## Key Features

* **Proof of Stake Resistance:** Mitigates price manipulation across various consensus mechanisms by leveraging Uniswap V4 hooks and automatic backrunning.
* **On-Chain Price Feeds:** Provides pricing data for on-chain token pairs, eliminating reliance on off-chain data sources.
* **Automated Backrunning:** Executes backrunning within the hook to revert price manipulations, ensuring minimal user intervention.
* **Single Oracle per Trading Pair:** Simplifies deployment with one oracle per trading pair, reducing complexity and attack vectors.
* **Truncated Geomean Oracles:** Caps tick movement per block to limit manipulation, with safeguards for multi-block scenarios.
* **Full Range Liquidity:** Uses maximum tick spacing and full range to ensure uniform liquidity, enhancing resistance to manipulation.

## **Architecture**

The oracle system is built as a Uniswap V4 hook, capturing price observations at the start of each block and processing them to resist manipulation. Key components include:

* **Observation Storage:** Records the last block’s price observation at the first transaction, capturing a non-manipulated state.
* **Automatic Backrunning:** Protects against price manipulations within the same or subsequent blocks by executing backrunning transactions, limiting tick delta to \~2280 ticks per block.
* **Tick Spacing and Range:** Configures pools with maximum tick spacing and full range for robust liquidity and manipulation resistance.
* **Manipulation Detection:** Monitors tick deltas to detect and counteract manipulation attempts, increasing the cost of attacks.

## Block-Manipulation Resistance

The oracle is designed to resist price manipulation in various consensus environments:

* **PoS Chains:** Mitigates multi-block attacks by limiting tick movement and using backrunning to deter attackers, even when validators can predict block proposers.
* **PoA and Sequencer-Based Systems:** Ensures price feed integrity in Ethereum L2s or other chains with centralized or semi-centralized block production.
* **Economic Deterrence:** Automatic backrunning raises the financial cost of manipulation, making attacks economically unviable.

## **Integration Guide**

**Prerequisites**

* Familiarity with Uniswap V4 and its hook system.
* Access to an Ethereum development environment (e.g., Hardhat, Foundry).
* Choose an available deployment (listed at the end of this page).

## Using an Existing Price Feed

To retrieve price data from an existing Uniswap V4 pool with liquidity and an attached oracle hook, call the observe method on the hook contract.

#### **Example: Fetching Price Data (TWAP)**

```
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {OracleLibrary} from "@uniswap/v3-periphery/contracts/libraries/OracleLibrary.sol";
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";

interface IOracle {
    function observe(
        PoolKey calldata key,
        uint32[] calldata secondsAgos
    ) external view returns (int48[] memory tickCumulatives, uint144[] memory secondsPerLiquidityCumulativeX128s);
}

contract PriceFeedConsumer {
    IOracle public backGeoOracle;
    
    constructor(IOracle _backGeoOracle) {
        backGeoOracle = _backGeoOracle;
    }

    function getTwapTick(address tokenA, address tokenB) external view returns (int24 twapTick) {
        uint32[] memory secondsAgos = new uint32[](2);
        secondsAgos[0] = 0; // Latest observation
        uint32 twapWindow = 1; // 1-second TWAP
        secondsAgos[1] = twapWindow; // Previous observation
        
        PoolKey memory key = PoolKey({
            currency0: Currency.wrap(tokenA),
            currency1: Currency.wrap(tokenB),
            fee: 0,
            tickSpacing: TickMath.MAX_TICK_SPACING,
            hooks: IHooks(backGeoOracle)
        });

        (int56[] memory tickCumulatives, ) = oracleHook.observe(key, secondsAgos);
        twapTick = int24((tickCumulatives[0] - tickCumulatives[1]) / int56(uint56(twapWindow))); // Calculate average tick
        return twapTick;
    }
}
```

* **Query TWAP tick:** Use the different of two tick points to extract the TWAP. Make sure you set a time delta appropriate for your application (i.e. 1-minute, 5-minutes).
* **Tick to Price:** Convert the returned tick to a price using Uniswap’s tick-to-price formula.

#### **Example: Converting token amount from base to quote using TWAP**

```
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {OracleLibrary} from "@uniswap/v3-periphery/contracts/libraries/OracleLibrary.sol";
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";

interface IOracle {
    function observe(
        PoolKey calldata key,
        uint32[] calldata secondsAgos
    ) external view returns (int48[] memory tickCumulatives, uint144[] memory secondsPerLiquidityCumulativeX128s);
}

/// @notice derived from Euler's UniswapV3Oracle https://github.com/euler-xyz/euler-price-oracle/blob/master/src/adapter/uniswap/UniswapV3Oracle.sol
contract PriceFeedConsumer {
    error PriceOracle_Overflow();

    IOracle public backGeoOracle;
    
    constructor(IOracle _backGeoOracle) {
        backGeoOracle = _backGeoOracle;
    }

    function getQuote(uint256 inAmount, address base, address quote) external view returns (uint256) {
        // Size limitation enforced by the pool.
        if (inAmount > type(uint128).max) revert PriceOracle_Overflow();

        uint32[] memory secondsAgos = new uint32[](2);
        uint32 twapWindow = 300; // 5-minute TWAP
        secondsAgos[0] = twapWindow;

        PoolKey memory key = PoolKey({
            currency0: Currency.wrap(tokenA),
            currency1: Currency.wrap(tokenB),
            fee: 0,
            tickSpacing: TickMath.MAX_TICK_SPACING,
            hooks: IHooks(backGeoOracle)
        });

        // Calculate the mean tick over the twap window.
        (int48[] memory tickCumulatives,) = IOracle(backGeoOracle).observe(key, secondsAgos);
        int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
        int24 tick = int24(tickCumulativesDelta / int56(uint56(twapWindow)));
        if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int56(uint56(twapWindow)) != 0)) tick--;
        return OracleLibrary.getQuoteAtTick(tick, uint128(inAmount), base, quote);
    }
}
```

## Creating a New Price Feed

To create a new price feed for a token pair:

* Initialize a Uniswap V4 Pool:
  * Initialize a new pool via the Uniswap V4 Pool Manager, using the oracle hook.
  * Set maximum tick spacing and full range liquidity (initialization will fail otherwise).
  * Be mindful about correctly setting the initial price, as otherwise the hook will need to get in par with other pools ≃ 10% per block (manually or via arbitrage) once liquidity is provided (10% per second on sub-second chains).

```
// Example: Initialize pool with oracle hook (simplified)
import "@uniswap/v4-core/contracts/interfaces/IPoolManager.sol";

contract PoolInitializer {
    address public immutable oracleHook;

    IPoolManager public poolManager = IPoolManager(POSM_ADDRESS);
    
    constructor(address backGeoOracle) {
        oracleHook = backGeoOracle;
    }

    /// @notice fee must be 0, tickSpacing must be TickMath.MAX_TICK_SPACING
    function createPool(
        address token0,
        address token1,
        uint24 fee,
        int24 tickSpacing
    ) external {
        poolManager.initialize(token0, token1, fee, tickSpacing, oracleHook);
    }
}
```

**Add Liquidity:**

* Provide liquidity to the pool to enable trading and price discovery (full range).
* Your position will be modified via arbitraged if price feed tick is not in line with market.

**Verify Oracle Functionality:**

* Call the observe method to confirm the oracle is providing price data.
* Test manipulation resistance by simulating large swaps and verifying tick stability.
* If you created the price feed, make sure you increase pair cardinality by calling the \`increaseCardinalityNext\` method in the BackGeoOracle contract, to increase its robustness (with a cardinality of 1, the extracted TWAP will only return the last stored tick, making it susceptible to manipulation).

## **Automatic Backrunning**

The oracle hook automatically executes backrunning to counteract price manipulations, requiring no user intervention. The hook:

* Monitors tick deltas during swaps.
* Triggers backrunning if the tick delta exceeds \~2280 ticks per block.
* Reverts manipulations by adjusting liquidity or executing counter-swaps within the same or next block.

This ensures the price feed remains robust without additional user setup.

The Backrunning Geomean Oracle has been selected as part of the Uniswap Foundation Security Fund (UFSF) Cohort 2. The smart contracts have been audited by [33Audits](https://www.33audits.xyz/). The audit report can be found in the [Github repository](https://github.com/RigoBlock/back-geo-oracle/tree/main/audits).

## Oracle Deployments

#### Mainnet Deployments

1. [Ethereum](https://github.com/RigoBlock/back-geo-oracle/blob/main/src/BackGeoOracle.sol) -> [0xB13250f0Dc8ec6dE297E81CDA8142DB51860BaC4](https://etherscan.io/address/0xB13250f0Dc8ec6dE297E81CDA8142DB51860BaC4)
2. [Arbitrum](https://github.com/RigoBlock/back-geo-oracle/blob/main/src/BackGeoOracle.sol) -> [0x3043e182047F8696dFE483535785ed1C3681baC4](https://arbiscan.io/address/0x3043e182047F8696dFE483535785ed1C3681baC4)
3. [Base](https://github.com/RigoBlock/back-geo-oracle/blob/main/src/BackGeoOracle.sol) -> [0x59f39091Fd6f47e9D0bCB466F74e305f1709BAC4](https://basescan.org/address/0x59f39091Fd6f47e9D0bCB466F74e305f1709BAC4)
4. [Bsc](https://github.com/RigoBlock/back-geo-oracle/blob/main/src/BackGeoOracle.sol) -> [0x77B2051204306786934BE8bEC29a48584E133aC4](https://bscscan.com/address/0x77B2051204306786934BE8bEC29a48584E133aC4)
5. [Optimism](https://github.com/RigoBlock/back-geo-oracle/blob/main/src/BackGeoOracle.sol) -> [0x79234983dED8EAA571873fffe94e437e11C7FaC4](https://optimistic.etherscan.io/address/0x79234983dED8EAA571873fffe94e437e11C7FaC4)
6. [Polygon](https://github.com/RigoBlock/back-geo-oracle/blob/main/src/BackGeoOracle.sol) -> [0x1D8691A1A7d53B60DeDd99D8079E026cB0E5bac4](https://polygonscan.com/address/0x1D8691A1A7d53B60DeDd99D8079E026cB0E5bac4)
7. [Unichain](https://github.com/RigoBlock/back-geo-oracle/blob/main/src/BackGeoOracle.sol) -> [0x54bd666eA7FD8d5404c0593Eab3Dcf9b6E2A3aC4](https://uniscan.xyz/address/0x54bd666eA7FD8d5404c0593Eab3Dcf9b6E2A3aC4)

#### Testnet Deployments

1. Sepolia [0xE39CAf28BF7C238A42D4CDffB96587862F41bAC4](https://sepolia.etherscan.io/address/0xE39CAf28BF7C238A42D4CDffB96587862F41bAC4)

## **Further Reading**

* [RigoBlock Oracle Blog Post](https://mirror.xyz/rigoblock.eth/yKAD5uYyH0KwfdsOxzt0MyppkFJZzXkxAFeufPGVA2M)
* [UFSF Cohort 2](https://www.uniswapfoundation.org/blog/uniswap-foundation-security-fund-cohort-2)
* [Uniswap Foundation Grant](https://www.uniswapfoundation.org/blog/unichain-grants-4)


# AI Agents

## AGENTS.md — External Agent Integration Guide

> How external AI agents interact with the Rigoblock Agentic Operator via x402. This document covers the security model, access tiers, and what agents can and cannot do.

***

### Overview

The Rigoblock Agentic Operator exposes two x402-gated endpoints:

| Endpoint     | Method | Price       | What it returns                                               |
| ------------ | ------ | ----------- | ------------------------------------------------------------- |
| `/api/quote` | GET    | $0.002 USDC | DEX price quote (no vault context needed)                     |
| `/api/chat`  | POST   | $0.01 USDC  | AI-powered DeFi response (swap calldata, positions, analysis) |

Payments are in USDC on **Base mainnet** (`eip155:8453`) via the [x402 protocol](https://x402.org). The CDP facilitator at `api.cdp.coinbase.com` handles verification and settlement.

***

### Access Tiers

#### Tier 1: Anonymous (x402 payment only)

**What:** Agent pays x402 fee. No operator credentials. **Gets:** Unsigned transaction data, price quotes, DeFi analysis. **Cannot:** Execute transactions on any vault.

```
GET /api/quote?sell=ETH&buy=USDC&amount=1&chain=base
X-PAYMENT: <x402-payment-header>

→ 200: { sell: "1 ETH", buy: "2079.54 USDC", price: "1 ETH = 2079.54 USDC", ... }
```

```
POST /api/chat
X-PAYMENT: <x402-payment-header>
Content-Type: application/json

{
  "messages": [{"role": "user", "content": "swap 1 ETH for USDC on Base"}],
  "vaultAddress": "0xYourVault",
  "chainId": 8453
}

→ 200: {
    "reply": "I'll prepare a swap of 1 ETH → USDC on Base via Uniswap...",
    "transaction": {
      "to": "0xYourVault",
      "data": "0x...",           ← unsigned calldata
      "value": "0x0",
      "chainId": 8453,
      "description": "Swap 1 ETH → 2,079.54 USDC via Uniswap"
    }
  }
```

The agent receives unsigned calldata. To execute it, the agent (or its operator) must sign and broadcast the transaction themselves. The calling agent's wallet is **never** used to operate the vault — the vault contract requires the transaction to come from its owner.

**Use cases:**

* Price discovery across 7 chains
* Natural language → structured DeFi calldata
* Portfolio analysis and position queries (read-only)
* Strategy recommendations (analysis only)

#### Tier 2: Authenticated (x402 payment + operator signature)

**What:** Agent pays x402 fee AND provides operator auth credentials. **Gets:** Everything in Tier 1, plus delegated (auto-execute) mode. **Can:** Trigger our agent wallet to execute trades on the authenticated vault.

```
POST /api/chat
X-PAYMENT: <x402-payment-header>
Content-Type: application/json

{
  "messages": [{"role": "user", "content": "swap 1 ETH for USDC on Base"}],
  "vaultAddress": "0xYourVault",
  "chainId": 8453,
  "operatorAddress": "0xOperatorWallet",
  "authSignature": "0x...",
  "authTimestamp": 1741700000000,
  "executionMode": "delegated",
  "confirmExecution": true
}

→ 200: {
    "reply": "Executed: swapped 1 ETH → 2,079.54 USDC",
    "executionResult": {
      "txHash": "0x...",
      "confirmed": true,
      "explorerUrl": "https://basescan.org/tx/0x..."
    }
  }
```

**Requirements for Tier 2:**

1. The `operatorAddress` must be the vault owner on at least one supported chain
2. The `authSignature` must be a valid EIP-191 signature of the auth message, signed by `operatorAddress`
3. The vault must have active delegation to our agent wallet on the target chain
4. The agent wallet must be authorized for the required function selector

**Auth message format:**

```
Welcome to Rigoblock Operator

Sign this message to verify your wallet and access your smart pool assistant.
```

The signature is valid for 24 hours from `authTimestamp`.

***

### Security Model

#### What the x402 payment wallet CAN do:

* Pay for API access ($0.002–$0.01 per call)
* Receive unsigned transaction data
* Query prices, positions, and vault info
* Get natural language DeFi analysis

#### What the x402 payment wallet CANNOT do:

* Execute transactions on any vault
* Trigger delegated execution (even if the vault has delegation active)
* Access operator-only endpoints without a valid operator signature
* Bypass the NAV guard or any on-chain safety check

#### What the operator signature unlocks:

* Delegated execution mode (our agent wallet executes on the vault)
* Access to vault-specific operations that modify state
* The operator signature proves: "I own this vault and authorize this action"

#### Why these are separate:

The x402 payer and the operator are typically different wallets:

* **x402 payer:** The agent's operational wallet (holds USDC on Base for API fees)
* **Operator:** The vault owner's wallet (controls on-chain vault permissions)

An agent builder might have one x402 payment wallet but interact with multiple vaults owned by different operators. The operator must independently authorize the agent by providing a signed auth credential.

***

### Safety Guarantees

Every transaction that our agent wallet executes passes through these checks **before broadcast:**

#### 1. Operator Authentication

The caller must provide a valid signature proving they own the target vault. No signature, no execution. This prevents any agent from operating vaults they don't control.

#### 2. Delegation Verification

The vault must have active on-chain delegation to our specific agent wallet for the required function selector. The vault owner controls which functions are delegated and can revoke at any time.

#### 3. Seven-Point Execution Validation

1. Delegation config exists and is enabled in our KV store
2. Transaction target is the vault address (prevents cross-contract attacks)
3. Function selector is in the allowed set (whitelist, not blacklist)
4. Agent wallet identity matches stored config
5. Transaction simulation passes via `eth_call` (catches reverts pre-broadcast)
6. Agent wallet has sufficient balance for gas
7. Gas fees within hard caps per chain

#### 4. NAV Guard (10% Maximum Loss)

Before every transaction broadcast, the system simulates the trade's impact on the vault's Net Asset Value per unit:

* Atomically simulates: `multicall([swap, getNavDataView])`
* Compares post-swap NAV against the **higher of:** pre-swap NAV or 24-hour baseline
* If NAV drops > 10% → **transaction BLOCKED**, reason returned to caller
* This check runs outside the agent's control surface — it cannot be disabled, bypassed, or circumvented by any API caller

#### 5. Slippage Protection

Default slippage tolerance: 1% (100 basis points). Combined with the NAV guard, this provides two layers of price protection.

***

### What Agents CANNOT Do (Even with Full Authentication)

Even a fully authenticated agent with delegation access CANNOT:

| Action                                   | Why not                                                          |
| ---------------------------------------- | ---------------------------------------------------------------- |
| Drain vault assets to external address   | `withdraw` and `transferOwnership` selectors are never delegated |
| Execute trades that lose > 10% NAV       | NAV guard blocks pre-broadcast                                   |
| Bypass slippage protection               | Slippage is enforced in swap calldata building                   |
| Call arbitrary contract functions        | Selector whitelist — only approved vault functions               |
| Send transactions to non-vault contracts | Target address must equal vault address                          |
| Spend more gas than the per-chain cap    | Gas caps are hard-coded, not configurable                        |
| Modify delegation settings               | Only vault owner can call `updateDelegation` from their wallet   |

***

### Settlement Policy

x402 settlement (USDC transfer) only occurs when the API returns a **2xx response:**

| Response         | Settlement  | Reason                                |
| ---------------- | ----------- | ------------------------------------- |
| 200 OK           | Settled     | Agent received value — charge applies |
| 400 Bad Request  | NOT settled | Malformed request — agent not charged |
| 401 Unauthorized | NOT settled | Auth failure — agent not charged      |
| 500 Server Error | NOT settled | Our fault — agent not charged         |

If settlement fails or is skipped, the CDP facilitator releases the held funds back to the paying wallet after `maxTimeoutSeconds` (300s).

The `PAYMENT-RESPONSE` header on the response contains the settlement receipt (base64-encoded JSON) when settlement succeeds.

***

### The `/api/quote` Endpoint

Stateless price quotes. No vault context needed. No operator auth.

```
GET /api/quote?sell=ETH&buy=USDC&amount=1&chain=base
```

**Query parameters:**

| Param    | Required           | Description                                                 |
| -------- | ------------------ | ----------------------------------------------------------- |
| `sell`   | Yes                | Token to sell (symbol or contract address)                  |
| `buy`    | Yes                | Token to buy (symbol or contract address)                   |
| `amount` | Yes                | Amount to sell (human-readable, e.g. "1" for 1 ETH)         |
| `chain`  | No (default: 8453) | Chain name or ID: `base`, `arbitrum`, `8453`, `42161`, etc. |

**Response:**

```json
{
  "sell": "1 ETH",
  "buy": "2079.548076 USDC",
  "price": "1 ETH = 2079.5481 USDC",
  "routing": "CLASSIC",
  "gasFeeUSD": "0.002423",
  "gasLimit": "394000",
  "chainId": 8453
}
```

***

### x402 Client Setup (TypeScript)

```typescript
import { createWalletClient, http } from "viem";
import { base } from "viem/chains";
import { privateKeyToAccount } from "viem/accounts";
import { publicActions } from "viem";
import { x402Client, x402HTTPClient } from "@x402/core/client";
import { ExactEvmScheme, toClientEvmSigner } from "@x402/evm";

// 1. Create a signer with USDC on Base (for x402 payments)
const account = privateKeyToAccount(PRIVATE_KEY);
const walletClient = createWalletClient({
  account,
  chain: base,
  transport: http(),
}).extend(publicActions);

// IMPORTANT: pass account as first arg (has .address), walletClient as second
const signer = toClientEvmSigner(account, walletClient);

// 2. Register the EVM exact scheme for Base mainnet
const client = new x402Client();
client.register("eip155:8453", new ExactEvmScheme(signer));
const httpClient = new x402HTTPClient(client);

// 3. Make a paid request
const res = await fetch("https://trader.rigoblock.com/api/quote?sell=ETH&buy=USDC&amount=1&chain=base");

if (res.status === 402) {
  const body = await res.json();
  const paymentRequired = httpClient.getPaymentRequiredResponse(
    (name) => res.headers.get(name),
    body,
  );
  const paymentPayload = await httpClient.createPaymentPayload(paymentRequired);
  const headers = httpClient.encodePaymentSignatureHeader(paymentPayload);

  const paidRes = await fetch(
    "https://trader.rigoblock.com/api/quote?sell=ETH&buy=USDC&amount=1&chain=base",
    { headers },
  );
  console.log(await paidRes.json());
}
```

***

### Supported Chains

| Chain     | ID    | Name      | Short      |
| --------- | ----- | --------- | ---------- |
| Ethereum  | 1     | Ethereum  | `ethereum` |
| Base      | 8453  | Base      | `base`     |
| Arbitrum  | 42161 | Arbitrum  | `arbitrum` |
| Optimism  | 10    | Optimism  | `optimism` |
| Polygon   | 137   | Polygon   | `polygon`  |
| BNB Chain | 56    | BNB Chain | `bsc`      |
| Unichain  | 130   | Unichain  | `unichain` |

***

### Bazaar Discovery

This service is registered in the [x402 Bazaar](https://api.cdp.coinbase.com/platform/v2/x402/discovery/resources), Coinbase's discovery API for x402-enabled services. AI agents using the Bazaar can discover and call our endpoints automatically.

***

### FAQ

**Q: Does the x402 paying wallet need to be the vault operator?** No. The x402 payer and the vault operator are independent. The x402 payer pays for API access. The operator proves vault ownership via signature. They can be different wallets.

**Q: Can an agent execute trades without the operator's private key?** No. Delegated execution requires a valid operator signature. Without it, the agent only gets unsigned transaction data (manual mode).

**Q: What happens if an agent provides a wrong vault address?** In manual mode: they get calldata they can't execute (they don't own the vault). In authenticated mode: `verifyOperatorAuth` checks on-chain that the signer owns the vault — if they don't, the request is rejected with 403.

**Q: Can an agent drain a vault through repeated small trades?** The NAV guard checks against a 24-hour baseline. Each trade is checked independently against the higher of the pre-swap NAV or the 24h baseline. A series of 1% losses would be individually allowed but would shift the baseline down over 24 hours. The 10% per-trade limit is the hard cap.

**Q: What if the agent wallet private key is compromised?** The vault owner can revoke delegation at any time via `revokeAllDelegations()`. The agent wallet can only call whitelisted selectors on the vault — cannot withdraw funds or transfer ownership.


# TWAP Order

## TWAP Orders — Technical Specification

> This document describes the TWAP (Time-Weighted Average Price) order system built into the Rigoblock Agentic Operator. It covers the data model, execution pipeline, safety controls, and API surface for integrators interested in building on top of or integrating with TWAP execution.

***

### What Is a TWAP Order?

A TWAP order splits a large swap into **N equal-sized slices** executed at **regular time intervals**. The goal is to reduce price impact on the DEX by spreading the trade over time rather than executing it as a single atomic swap.

A TWAP order:

* Executes deterministically — no LLM judgment in the execution loop
* Runs autonomously on a cron schedule (minimum 5-minute intervals)
* Has a defined total amount, slice size, and duration
* Supports both **buy-side** (exact-output) and **sell-side** (exact-input) semantics

**Example:**

> "Buy 100 GRG with ETH, 20 per slice, every 5 minutes"
>
> → 5 slices × 20 GRG (exact-output) × 5-minute interval = completes in 25 minutes

***

### How TWAP Orders Work

#### Lifecycle

```
create_twap_order
      │
      ▼
  KV store (twap:{vault})
      │
      ▼  [every cron tick, ≥5 min]
  runDueTwapOrders()
      │
      ├── is order due? (elapsed + jitter > intervalMinutes * 60_000)
      │        │
      │       Yes
      │        ▼
      │   executeToolCall("build_vault_swap", {tokenIn, tokenOut, amount, dex, chain})
      │        │
      │        ├── Swap Shield check (oracle price vs DEX quote)
      │        ├── NAV shield pre-check (simulate: will NAV drop >10%?)
      │        │
      │   [autoExecute=true]       [autoExecute=false]
      │        │                         │
      │   executeTxList()          Telegram notification
      │        │                   (no on-chain execution)
      │   NAV shield broadcast check
      │   (7-point validation + gas check)
      │        │
      │   CDP signs + broadcasts
      │        │
      │   record TwapEvent
      │   notify Telegram
      │        │
      ▼   order.slicesExecuted++
  save updated order state
```

***

### Data Model

```typescript
interface TwapOrder {
  id: number;                // Monotonically increasing per vault (high-water-mark, never reused)
  side: "buy" | "sell";     // "buy" = totalAmount in buyToken; "sell" = totalAmount in sellToken
  sellToken: string;         // Token symbol or address (user input)
  buyToken: string;          // Token symbol or address (user input)
  sellTokenAddress?: string; // Resolved contract address (set at creation time)
  buyTokenAddress?: string;  // Resolved contract address (set at creation time)
  totalAmount: string;       // Total amount of `side` token (human-readable, 6 decimal precision)
  sliceAmount: string;       // Amount per slice (same denomination as totalAmount)
  sliceCount: number;        // Total planned slices
  intervalMinutes: number;   // Minutes between slices (≥5)
  dex: string;               // Target DEX
  chainId: number;           // EVM chain ID
  vaultAddress: string;      // Rigoblock vault address (lowercase)
  operatorAddress: string;   // Vault owner address (who authorized the order)
  active: boolean;           // false = completed or cancelled
  createdAt: number;         // Unix ms timestamp
  lastExecution?: number;    // Unix ms of last successful or failed slice attempt
  consecutiveFailures: number; // Resets to 0 on success; order pauses at 3
  lastError?: string;        // Last error message (sanitized)
  completedAt?: number;      // Unix ms when all slices executed or order cancelled
  amountSpent: string;       // Running total of sellToken spent
  totalBought: string;       // Running total of buyToken received
  slicesExecuted: number;    // Count of successfully executed slices
  autoExecute: boolean;      // true = auto-broadcast; false = notify only
}
```

#### swapMeta — Slice Fill Data

When a slice executes, the `build_vault_swap` tool returns an `UnsignedTransaction` that includes a `swapMeta` object. The TWAP executor reads this to update the order's accounting fields (`amountSpent`, `totalBought`):

```typescript
interface SwapMeta {
  sellAmount: string;  // Actual (or estimated) sell amount in human-readable units
  sellToken: string;   // Sell token symbol or address
  buyAmount: string;   // Actual (or estimated) buy amount in human-readable units
  buyToken: string;    // Buy token symbol or address
  price: string;       // Human-readable price ratio: "1 ETH = 2079.54 USDC"
  dex: string;         // Target DEX
}
```

If the TWAP executor cannot read `swapMeta` from the returned transaction (e.g., the tool returned an error), the slice failure is recorded but `amountSpent` and `totalBought` are not updated for that slice.

````

### Key Invariants

- `id` is assigned from a **per-vault high-water-mark** stored in KV (`twap-hwm:{vault}`).
  Pruning closed orders never causes ID reuse.
- Maximum **3 active orders per vault**.
- Closed orders (inactive) are pruned to 20 per vault to limit KV growth.
- `slicesExecuted + 1` = the slice number for the next execution.

---

## Token Address Resolution

Token addresses are resolved **at order creation time** using the CoinGecko-backed
token resolver (`src/services/tokenResolver.ts`). The resolved addresses are stored
in `sellTokenAddress` and `buyTokenAddress`.

This ensures:
- **Fail-fast** — if the token doesn't exist on the target chain, the order is
  rejected at creation rather than at cron execution time.
- **Cron independence** — TWAP slices use the stored addresses directly, never
  requiring CoinGecko at execution time (avoids transient resolver failures).

If the user passes a contract address instead of a symbol, it is used as-is.

---

## Execution Pipeline (Per Slice)

Each slice calls `executeToolCall(env, ctx, "build_vault_swap", toolArgs)` with:

```typescript
const toolArgs = side === "buy"
  ? { tokenOut: buyRef, tokenIn: sellRef, amountOut: order.sliceAmount, dex: order.dex }
  : { tokenIn: sellRef, tokenOut: buyRef, amountIn: order.sliceAmount, dex: order.dex };
toolArgs.chain = chainName;
````

This is **identical** to the standard swap tool call path — it goes through the same safety stack as a manually triggered swap.

#### Safety Controls Applied on Every TWAP Slice

**1. Swap Shield (Oracle Price Protection)**

Before building swap calldata, the system compares the DEX quote against the vault's on-chain BackgeoOracle price:

* Blocks if DEX quote is **>5% off** than oracle
* Gracefully allows the swap when the oracle has no price feed for a token (`NO_PRICE_FEED`) within vaults, this case only allows selling non-tracked tokens (i.e. airdrops or direct transfers).

This greatly limits TWAP orders from executing at unfavorable prices due to poor liquidity, stale DEX state, or oracle manipulation.

**2. NAV Shield Pre-Check**

Before the slice transaction is built and returned, the system atomically simulates:

```
multicall([swap_calldata, updateUnitaryValue()])
```

If the simulated post-swap NAV drops **>10%** versus the pre-swap NAV (or the 24-hour baseline, whichever is higher), the slice is **blocked** and an error is recorded.

**3. NAV Shield at Broadcast Time (auto-execute mode)**

For `autoExecute: true`, a second NAV shield check runs inside `executeTxList()` immediately before the CDP-signed transaction is broadcast. This is a belt-and-suspenders check in case market conditions changed between building and broadcasting the calldata.

**4. Seven-Point Execution Validation**

For `autoExecute: true`, `executeTxList()` runs the full 7-point validation:

1. Delegation config exists and is enabled in KV
2. Transaction target == vault address (prevents cross-contract attacks)
3. Function selector is in the allowed whitelist
4. Agent wallet identity matches stored config
5. `eth_call` simulation passes (pre-broadcast revert check)
6. Agent wallet has sufficient ETH for gas - unless sponsored transaction
7. Gas fees within per-chain hard caps

**5. Slippage Protection**

Default slippage: **1% (100 bps)**. Configurable by the operator via:

* `set_default_slippage` tool (persisted per operator in KV)
* `slippageBps` field in the chat request body

Clamped to \[10, 500] bps (0.1%–5%). The LLM cannot set slippage directly.

**6. Auto-Pause on Failure**

After **3 consecutive slice failures**, the order is automatically paused (`active = false`). The operator is notified via Telegram on every failure (not just on auto-pause).

***

### Execution Context

When a TWAP slice fires at cron time, the request context is:

```typescript
const ctx: RequestContext = {
  vaultAddress: order.vaultAddress,
  chainId: order.chainId,
  operatorAddress: order.operatorAddress,
  isBrowserRequest: false,      // allows building unsigned calldata without browser auth
  executionMode: order.autoExecute ? "delegated" : "manual",
};
```

`isBrowserRequest: false` bypasses the browser auth gate (which requires a connected wallet), since TWAP slices run server-side without a browser session. Security is maintained via delegation verification in the execution pipeline.

***

### Manual vs Autonomous Mode

| Mode           | `autoExecute`     | Behavior                                                                        |
| -------------- | ----------------- | ------------------------------------------------------------------------------- |
| **Manual**     | `false` (default) | LLM analyzes + builds tx, sends Telegram notification. No on-chain execution.   |
| **Autonomous** | `true`            | Builds tx + broadcasts via CDP agent wallet. Operator notified after execution. |

Both modes apply the Swap Shield and NAV pre-check when building the transaction. Only autonomous mode applies the broadcast-time NAV check and 7-point validation.

For autonomous mode, the vault must have **active delegation** to the agent wallet on the target chain, with the `execute()` selector included.

***

### KV Storage Schema

| Key                   | Value                                                  | TTL  |
| --------------------- | ------------------------------------------------------ | ---- |
| `twap:{vault}`        | JSON array of `TwapOrder[]` (active + up to 20 closed) | none |
| `twap-hwm:{vault}`    | Highest ID ever assigned (integer string)              | none |
| `twap-events:{vault}` | JSON array of `TwapEvent[]` (last 20 events)           | 24h  |

#### TwapEvent Schema

```typescript
interface TwapEvent {
  orderId: number;
  timestamp: number;    // Unix ms
  sliceNumber: number;  // 1-indexed
  totalSlices: number;
  sellAmount: string;   // Actual amount sold (from swapMeta)
  buyAmount: string;    // Actual amount received (from swapMeta)
  success: boolean;
  error?: string;       // Present on failure (truncated to 400 chars)
}
```

Events are served via `GET /api/strategy-events?vault=0x…&since={timestamp}` and polled by the frontend to show slice history.

***

### API Tools

TWAP orders are created and managed via the `/api/chat` endpoint using the following tools:

#### `create_twap_order`

```json
{
  "side": "buy" | "sell",
  "sellToken": "ETH",
  "buyToken": "GRG",
  "totalAmount": "100",
  "sliceAmount": "20",        // or sliceCount or durationMinutes
  "intervalMinutes": 5,
  "dex": "0x" | "uniswap",
  "chain": "base",
  "autoExecute": true
}
```

**Returns:** Confirmation message with order ID, duration, and mode.

#### `cancel_twap_order`

```json
{ "id": 3 }          // cancel specific order
{ "id": 0 }          // cancel all active orders
```

#### `list_twap_orders`

No parameters. Returns formatted list of all orders (active and closed) with progress, amounts spent, and status.

**Alias:** `list_strategies` maps to the same handler — both names work interchangeably in the chat interface.

***

### Fast-Path Processing

The chat agent includes a **regex-based fast path** for commonly phrased TWAP commands. When a message matches the fast path, the TWAP order is created directly without invoking the LLM — reducing latency and cost.

The fast path activates when the message contains both:

* `"every N minutes"` — sets `intervalMinutes`
* `"X at a time"` — sets `sliceAmount`

Examples that hit the fast path:

```
"Sell 1 ETH for USDC, 0.2 at a time, every 10 minutes"
"Buy 100 GRG with ETH, 20 at a time, every 5 minutes, auto-execute"
```

If neither pattern is present, the full inference path handles the request. The LLM is always invoked for ambiguous phrasing, multi-step requests, or when the user asks follow-up questions about an order.

The fast path also handles:

* `"list twap orders"` / `"list strategies"` → `list_twap_orders`
* `"cancel twap {id}"` / `"cancel all twap orders"` → `cancel_twap_order`
* `"enable/disable swap shield"` → `enable_swap_shield` / `disable_swap_shield`

***

### Constraints

| Constraint                                 | Value                   |
| ------------------------------------------ | ----------------------- |
| Max active orders per vault                | 3                       |
| Max stored closed orders per vault         | 20                      |
| Minimum interval                           | 5 minutes               |
| Max consecutive failures before auto-pause | 3                       |
| Max stored events                          | 20 (per vault, 24h TTL) |

***

### Delegation Requirements (Autonomous Mode)

For `autoExecute: true`, the vault must have **active on-chain delegation** to the agent wallet for each function selector the TWAP executor will call.

#### How Rigoblock Delegation Works

Rigoblock vaults implement a **granular per-selector delegation system**. The vault contract maintains a permission mapping:

```
delegation().selectorToAddressPosition[bytes4 selector][address agent] → bool
```

When a call arrives at the vault's fallback, the contract checks this mapping before forwarding the call to the appropriate adapter. If the calling address is not delegated for that selector, the call reverts.

The operator grants permissions by sending an `updateDelegation(Delegation[])` transaction from their EOA (the vault owner address):

```solidity
struct Delegation {
    address delegated;   // the agent wallet address
    bytes4 selector;     // the function selector to permit
    bool isDelegated;    // true to grant, false to revoke
}
```

Revocation is atomic: `revokeAllDelegations(agentAddress)` removes all selectors for the agent in a single call.

#### Setting Up Delegation

Via the chat interface (browser or API):

```
"Set up delegation on Base"
```

Or programmatically:

```
POST /api/delegation/setup   →  unsigned updateDelegation() tx
  [operator signs + broadcasts]
POST /api/delegation/confirm →  stores delegation state in KV
```

The operator can revoke all permissions instantly at any time:

```
"Revoke delegation on Base"
```

Or on-chain: `pool.revokeAllDelegations(agentAddress)`.

#### EIP-7702 — Code Delegation (Pectra)

EIP-7702, introduced in Ethereum's Pectra upgrade, allows an **EOA to temporarily adopt smart contract code** within a single transaction. It is designed for smart-wallet use cases: a user's EOA can batch calls, pay gas in ERC-20 tokens, or execute sponsored transactions by delegating to a chosen implementation contract for the duration of one transaction.

**TWAP does not use EIP-7702.** The agent wallet is a CDP-managed EOA with its own signing capability — it does not need to adopt smart contract code. The delegation problem TWAP solves is different: it is not "allow this EOA to batch-call during one transaction" but rather "allow this external EOA to call specific vault functions indefinitely, until the operator revokes." That is a **persistent, contract-level** permission that EIP-7702 (which is transaction-scoped and EOA-level) cannot express.

#### EIP-7715 — Scoped Wallet Permissions (`wallet_grantPermissions`)

EIP-7715 proposes a wallet RPC method (`wallet_grantPermissions`) for granting **scoped permissions** to dApps or agents — specifying which functions they may call, with which parameters, and under which conditions (spend limits, expiry, allowed contracts). This is the EIP that most closely resembles Rigoblock's delegation model.

**Conceptual alignment:**

* Both are selector-scoped (specific `bytes4` function signatures)
* Both are address-bound (permission granted to a specific agent address)
* Both support revocation

**Key difference in layer:**

* EIP-7715 operates at the **wallet level** — the permission is enforced by the user's wallet before it signs any transaction.
* Rigoblock delegation operates at the **vault contract level** — the permission is enforced on-chain inside the vault's fallback function, independent of who signs or how.

As EIP-7715 matures, an operator could use it to further constrain what the agent's wallet is permitted to sign (e.g., only transactions targeting this specific vault), complementing the existing on-chain vault delegation. The two layers are not mutually exclusive — vault-level delegation remains the primary enforcement layer.

***

### EIPs and Standards Used

#### EIP-191: Signed Data Standard

Used for **operator authentication**. When setting up TWAP orders via the chat or API, the operator must sign:

```
Welcome to Rigoblock Operator

Sign this message to verify your wallet and access your smart pool assistant.
```

The signature is verified server-side via `viem.verifyMessage()`. Valid for 24 hours. Purpose: proves the caller owns the vault operator wallet, not just the x402 payer wallet.

#### EIP-712: Typed Structured Data Hashing (implicit)

The Rigoblock vault's `updateDelegation()` function uses typed structs:

```solidity
struct Delegation {
    address delegated;
    bytes4 selector;
    bool isDelegated;
}
```

When the operator sets up delegation, they sign and send `updateDelegation(Delegation[])` from their EOA. This grants the agent wallet selector-level permissions.

#### EIP-1193: Ethereum Provider JavaScript API

The TWAP creation flow runs inside the chat agent. Actual slice execution (for autonomous mode) uses the **CDP Server Wallet** (Coinbase Developer Platform). CDP manages the agent's private key server-side in a TEE (Trusted Execution Environment) — the key never appears in Worker code or KV storage. The CDP account is wrapped into a viem-compatible `EvmServerAccount` / `LocalAccount` interface for signing.

For manual mode, the slice transaction is returned as unsigned calldata (same as all other vault transactions) and the operator signs it via their connected wallet using the standard `eth_sendTransaction` call.

#### x402: HTTP Micropayments (RFC Draft)

TWAP orders are created via the `/api/chat` endpoint, which is x402-gated at **$0.015 USDC per request** (paid on Base mainnet). The x402 payment is an **API access fee** — it does NOT authorize vault operations. Vault authorization requires a separate operator signature (EIP-191) AND active on-chain delegation. These are completely independent layers: a request may have x402 payment without operator auth (anonymous mode, receives unsigned calldata only) or both (full access including delegated execution).

See AGENTS.md for full x402 setup instructions.

***

### Observability

#### Telegram Notifications

If Telegram is paired (`/api/telegram/pair`), the operator receives:

* **Per-slice execution** (autonomous mode): swap amounts, progress fraction, tx link
* **Order completion**: total spent/bought summary
* **Slice failure**: error message + Tenderly debug calldata (to/from/value/data)
* **Auto-pause**: notification when 3 consecutive failures occur

#### Strategy Events Polling

```
GET /api/strategy-events?vault=0xYourVault&since=1700000000000
```

Returns:

```json
{
  "events": [
    {
      "type": "twap",
      "timestamp": 1700000300000,
      "success": true,
      "twapOrderId": 3,
      "summary": "Slice 2/5: 0.042 ETH → 21.3 GRG"
    }
  ]
}
```

***

### Security Properties

TWAP orders cannot:

| Action                             | Reason                                            |
| ---------------------------------- | ------------------------------------------------- |
| Execute without delegation         | Agent wallet only has whitelisted selectors       |
| Execute a swap that drops NAV >10% | NAV shield blocked at build AND broadcast time    |
| Execute at an unfavorable price    | Swap Shield compares against on-chain TWAP oracle |
| Call arbitrary contracts           | Transaction target must equal vault address       |
| Exceed gas caps                    | Hard-coded per-chain gas limits                   |

The vault contract enforces these constraints on-chain, independently of the agent or TWAP scheduler code. Even a compromised Worker cannot bypass the on-chain delegation mapping.

***

### Example: Creating a TWAP Order via x402

```typescript
import { x402Client, x402HTTPClient } from "@x402/core/client";
import { ExactEvmScheme, toClientEvmSigner } from "@x402/evm";
import { createWalletClient, http } from "viem";
import { base } from "viem/chains";
import { privateKeyToAccount } from "viem/accounts";

// 1. Set up x402 payment client (USDC on Base)
const account = privateKeyToAccount(PRIVATE_KEY);
const walletClient = createWalletClient({ account, chain: base, transport: http() });
const signer = toClientEvmSigner(account, walletClient.extend(publicActions));
const client = new x402Client();
client.register("eip155:8453", new ExactEvmScheme(signer));
const httpClient = new x402HTTPClient(client);

// 2. Sign the operator auth message
const authMessage = [
  "Welcome to Rigoblock Operator",
  "",
  "Sign this message to verify your wallet and access your smart pool assistant.",
].join("\n");
const authSignature = await walletClient.signMessage({ message: authMessage });
const authTimestamp = Date.now();

// 3. Create the TWAP order via /api/chat
const res = await fetch("https://trader.rigoblock.com/api/chat");
if (res.status === 402) {
  const paymentPayload = await httpClient.createPaymentPayload(
    httpClient.getPaymentRequiredResponse(name => res.headers.get(name), await res.json())
  );
  const headers = {
    ...httpClient.encodePaymentSignatureHeader(paymentPayload),
    "Content-Type": "application/json",
  };

  const chatRes = await fetch("https://trader.rigoblock.com/api/chat", {
    method: "POST",
    headers,
    body: JSON.stringify({
      messages: [{ role: "user", content: "Buy 100 GRG with ETH, 20 per slice, every 5 minutes, auto-execute" }],
      vaultAddress: "0xYourVaultAddress",
      chainId: 8453,
      operatorAddress: "0xYourOperatorAddress",
      authSignature,
      authTimestamp,
      executionMode: "delegated",
    }),
  });

  const result = await chatRes.json();
  console.log(result.reply);
  // → "✅ TWAP order #1 created! Buy 100 GRG with ETH | 5 slices of ~20.000000 GRG every 5m | Duration: 25 minutes | DEX: 0x | Mode: ⚡ Auto-execute | First slice: next cron tick"
}
```

***

### Direct Tool API (x402)

You can also call the `create_twap_order` tool directly without going through the LLM, using `POST /api/tools/create_twap_order`:

```bash
curl -X POST https://trader.rigoblock.com/api/tools/create_twap_order \
  -H "X-PAYMENT: <x402-payment-header>" \
  -H "Content-Type: application/json" \
  -d '{
    "side": "sell",
    "sellToken": "ETH",
    "buyToken": "USDC",
    "totalAmount": "1",
    "sliceCount": 4,
    "intervalMinutes": 10,
    "dex": "uniswap",
    "chain": "base",
    "autoExecute": true,
    "vaultAddress": "0xYourVault",
    "operatorAddress": "0xYourOperator",
    "authSignature": "0x...",
    "authTimestamp": 1700000000000
  }'
```

***

### Comparison with Strategy System

The Rigoblock Agentic Operator also has a general **strategy system** (LLM-driven) where an LLM evaluates market conditions and decides whether to execute a trade. TWAP orders differ fundamentally:

| Aspect           | TWAP Orders                                 | LLM Strategies                                    |
| ---------------- | ------------------------------------------- | ------------------------------------------------- |
| Execution logic  | Deterministic (always executes on schedule) | LLM judgment (may skip if conditions unfavorable) |
| Tool calls       | Direct tool dispatch (no LLM involved)      | LLM decides what to call                          |
| Latency          | Low (sub-second build time)                 | Higher (LLM inference)                            |
| Cost             | Lower (no LLM tokens on execution)          | Higher (LLM tokens per run)                       |
| Flexibility      | Fixed: swap at regular intervals            | Flexible: any supported operation                 |
| Monitoring       | Per-slice events + Telegram                 | Per-run recommendations + Telegram                |
| Failure handling | Auto-pause at 3 failures                    | Auto-pause at 3 failures                          |

TWAP orders are the right choice for mechanical, scheduled execution. LLM strategies are better for adaptive, market-condition-sensitive execution.


# Swap Shield

Oracle-protected Swaps

Rigoblock offers oracle-protected swaps. Every quote is compared against an oracle price and the API returns the deviation from said price. Integrators can inspect the reponse, and decide whether the quote should be executed or not. When a price feed is not available for the target token pair, a `false` boolean is returned alongside a null `oracleAmount`.

The trader.rigoblock.com agent blocks rogue swaps via the Swap Shield - a component outside of control of the agent that reverts any trade that is off the oracle price. It is the first line of defense in Rigoblock’s two-layer agent safety stack and is enabled by default on every trade.

### How Swap Shield Works

Before any swap calldata is built or broadcast the system automatically compares the received DEX quote against the onchain BackGeoOracle price.

The trade is instantly blocked if the DEX quote deviates more than 5 percent in either direction from the oracle price. This unified two-sided tolerance means:

* More than 5 percent worse than oracle → protects against bad fills, low liquidity, or stale DEX state
* More than 5 percent better than oracle → protects against manipulation, front-running, or stale oracle routes
* The default 5% deviation can be adjusted by the user in the range of 0.1% and 50%, outside of control of the agent (meaning the agent cannot modify the parameter to execute a swap outside the operator-defined or default deviation - protected from prompt injection attacks).

If the oracle returns NO\_PRICE\_FEED for a token Swap Shield gracefully allows the swap. This is reserved for legitimate actions such as selling airdrops or tokens received via direct transfer. Otherwise, tokens held by the Rigoblock smart pools are guaranteed to have a price feed.

Swap Shield operates completely separately from your configurable slippage tolerance which you can still set between 0.1 percent and 50 percent.

### Key Benefits

* Prevents execution at clearly unfavorable prices
* Works identically for manual chat commands TWAP slices and fully autonomous agents
* Mandatory for scoped delegation — cannot be bypassed without explicit temporary opt-out
* Fully open-source and verifiable in the agentic-operator repository
* Cannot be modified or disabled by the agent

### Configuration and Tools

* Enabled by default on all vaults using the AI Agent
* Temporary override the default tolerance for 10 minutes. During this window you can override the parameter up to 50 percent if needed. The shield automatically re-enables after the TTL.
* Monitoring shield status and events are visible directly in the agent chat and via Telegram notifications.

### Activation Scope

Swap Shield activates on:

* every manual swap command
* every TWAP slice
* every trade executed via the x402 API

It always runs before NAV Shield slippage checks and the 7-point execution validation.

### See also

NAV Shield\
[TWAP Order](/ai-agents/twap-order)\
[Code repository on GitHub](https://github.com/RigoBlock/agentic-operator)

Try it now at [trader.rigoblock.com](https://trader.rigoblock.com)


# Protocol fee


# Overview

Rigoblock Protocol Fees

The Rigoblock protocol applies a spread (set by the pool operator to prevent unfair entries or exits) to mint and burn operations. Since version 4.1.0, the resulting spread token amount is transferred to the TokenJar contract, where it accrues alongside fees collected in any other token.

TokenJar token balances can be released by paying a decreasing amount of GRG tokens. This payment is determined through a reverse Dutch auction mechanism: the amount of GRG required to clear the TokenJar balances progressively decreases over time until it reaches a predefined minimum threshold. The paid GRG is then transferred to the `0xdead` address on each chain, effectively burning those tokens.

When interacting with the releaser contract, searchers specify the maximum amount of GRG they are willing to pay. This design prevents front-running and enables a MEV-minimized conversion of fees to GRG.

The protocol fee smart contracts are derived from the Uniswap protocol fees implementation [(https://github.com/Uniswap/protocol-fees)](https://github.com/Uniswap/protocol-fees) but replace the fixed threshold model with a reverse Dutch auction. This approach minimizes MEV exposure (fee release becomes progressively less expensive, especially in the case of a large single fee accrual during the initial decay phase) and allows for less frequent clearing of balances. Instead of converting TokenJar tokens at a fixed price threshold, the effective price of the token portfolio decreases over time until it reaches the original equivalent threshold value.


# Deployments

```
Deployer: 0x8fe2051B8107192D695449Cf2b002C2EcB479832
TokenJar: 0xA0F9C380ad1E1be09046319fd907335B2B452B37
Firepit: [
    Ethereum: 0x0ADcf4Fa0DfFcCEeCAD2705dFA1caaF1A9E9f79F
    Arbitrum: 0x5C1B29fDa692a4a36B6667751af2e2907052cA32
    Base: 0x2e554eb40b417080A7e4b18b485A59f832e226A5
    Optimism: 0x30287f9159f0D613588885AA87F58619eA000eF3
    Unichain: 0x6D9B25b76b73ff58a9b88DD4365cE0a639377148
    Bsc: 0x9d8a28c5D67E09f7495a13a8F355B10aCFF5665C
    Polygon: 0xBDdf82964B71b83f00AF2217eD4b0400d35770e8
```


# Governance

### **Core Components of the Rigoblock Governance Framework**

* **Modular and Deterministic Proxy Pattern**\
  A lightweight **governance proxy** is deployed at the **same address** on every supported network (e.g., Ethereum mainnet, L2s like Optimism or Arbitrum). This proxy holds the governance state (proposals, votes, etc.) and delegates execution to a **canonical governance implementation** contract that contains the core logic.\
  The deterministic nature ensures consistent addressing across chains, simplifying multichain deployments and interactions.
* **Voting Strategy as a Plug-in**\
  The voting logic is separated into a distinct **voting strategy contract**, which is project-specific. This allows each project (or DAO) to define its own rules—e.g., quadratic voting, token-weighted, reputation-based, or custom logic—while reusing the proxy and core governance layer.\
  Projects can opt to use Rigoblock's highly efficient proxy pattern even if they provide their own custom governance implementation on top of their strategy.
* **Upgradability via Proposals**\
  Governance is **upgradeable** through successful proposals. Upgradable parameters include:\
  a) **Implementation** address (the canonical logic contract)\
  b) **Voting strategy** contract\
  c) **Proposal threshold** (minimum tokens/power needed to create a proposal)\
  d) **Voting threshold** (e.g., quorum or majority requirements)
  * New implementation (a) and voting strategy (b) must be valid smart contract addresses.
  * Changes to thresholds (c and d) must pass validation checks defined in the active voting strategy contract (to prevent invalid or unsafe configurations).

This setup enables projects to start with a battle-tested, canonical Rigoblock governance setup and later evolve (e.g., migrate to a fully custom implementation or tweak voting mechanics) without breaking multichain consistency or requiring users to track different addresses.

### Benefits of This Approach

* **Multichain Consistency** — Same governance address everywhere, reducing complexity for users and frontends.
* **Efficiency** — Proxies minimize gas costs and deployment overhead compared to deploying full logic contracts per chain.
* **Flexibility** — Projects retain sovereignty over their voting rules and can upgrade as needs evolve (e.g., shifting from simple token voting to more advanced mechanisms).
* **Security & Composability** — Separation of state (proxy), logic (implementation), and rules (strategy) follows best practices for upgradeable contracts, similar to patterns in OpenZeppelin or other DeFi protocols.


# Rigoblock Governance

Rigoblock voting power is equivalent to a wallet's GRG active stake. A proposal requires a voting power of at least 100k GRG on Ethereum mainnet, 40k GRG on L2s in order for it to be valid. A voter can vote in favor, aginst, or abstain. A proposal requires a quorum of at least 400k GRG on Ethereum mainnnet, 200k GRG on L2s (100k on Unichain - these quorum can be modified by the governance only). Each network is managed separately in order to maximize the cost benefit of L2, while maintaining Ethereum L1 voting on L1. This rule is subject to change as Rigoblock could later decide to leverage chain message bridging to improve running its multichain governance.

Two thirds of votes in favor are required for a proposal to be successful. Abstained votes are counted for but are not computed in the quorum or the voting for/against. The voting period starts from the start of the next GRG staking epoch and lasts for 7 days. The voting period is required to be shorter than the epoch period. If during the voting period, the proposal finds an absolute qualified majority of support, i.e. the state is final and cannot be changed by further votes against, the proposal state is updated to "Qualified" and the transaction can be executed from the next block.

### Governance Tasks

In the context of the Rigoblock Protocol and Staking System, the Rigoblock Governance is responsible for the following tasks:

* Set owner in Factory
* Update implementation address in Factory
* Update registry address in Factory
* Set owner in Authority
* Add a new factory address in Authority
* add/remove adapter(s) address in Authority
* add/remove whitelister(s) address in Authority
* add/remove authorized address in ERC20 Proxy
* add/remove authorized in GRG Vault
* set staking proxy in GRG Vault
* add/remove authorized address in Staking Proxy
* add Proof of Performance address in Staking Proxy

<pre><code>0xd784d426 poolFactory.setImplementation(address newImplementation);
<strong>0x091ee0dc poolFactory.setRegistry(address newRegistry);
</strong>0x13af4035 authority.setOwner(address newOwner);
0x71013c10 authority.setFactory(address factory, bool whitelisted);
<strong>0x332f6465 authority.setAdapter(address adapter, bool whitelisted);
</strong>0xc91b0149 authority.setWhitelister(address whitelister, bool whitelisted);
0x7a9e5e4b registry.setAuthority(address newAuthority);
0xb516e6e1 registry.setRigoblockDao(address newRigoblockDao);
0x42f1181e erc20proxy.addAuthorizedAddress(address target); (grgVault)
0x70712939 erc20Proxy.removeAuthorizedAddress(address target);
0x9ad26744 erc20Proxy.removeAuthorizedAddressAtIndex(address target, uint256 index);
0xf2fde38b erc20Proxy.transferOwnership(address newOwner);
0x42f1181e grgVault.addAuthorizedAddress(address target); (self)
0x70712939 grgVault.removeAuthorizedAddress(address target); (self)
0x9ad26744 grgVault.removeAuthorizedAddressAtIndex(address target, uint256 index);
0x502e5a7f grgVault.enterCatastrophicFailure();
0xdb8e54bd grgVault.setGrgProxy(address erc20Proxy);
0x6bf3f9e5 grgVault.setStakingProxy(address proxy);
0xf2fde38b grgVault.transferOwnership(address newOwner);
0x42f1181e stakingProxy.addAuthorizedAddress(address target); (self)
0x70712939 stakingProxy.removeAuthorizedAddress(address target);
0x9ad26744 stakingProxy.removeAuthorizedAddressAtIndex(address target, uint256 index);
0xf2fde38b stakingProxy.transferOwnership(address newOwner);
<strong>0x1f81eb80 stakingProxy.addPopAddress(address proofOfPerformance);
</strong><strong>0x66615d56 stakingProxy.attachStakingContract(address newStakingImplementation);
</strong><strong>0x37b006a6 stakingProxy.detachStakingContract(); (when authorized(self))
</strong></code></pre>

### Governance Delegated Tasks

The Rigoblock Governance can delegate the task of activating/deactivating previously approved adapters' methods to authorized addresses, in order to remove the need for an onchain vote. At any moment the governance can remove such delegation(s) partially or entirely, and even take over the tasks by becoming the only delegated wallet, thus requiring an onchain voting for:

* adding a selector to adapter address mapping in the authority contract
* removing a selector to adapter address mapping in the authority contract

```
0xcd29d473 authority.addMethod(bytes4 selector, address adapter);
0xd9efcc1e authority.removeMethod(bytes4 selector, address adapter);
```


# Supported Applications

Currently the Rigoblock protocol supports the following external applications

1. Uniswap Fungile Tokens Swaps (V2 + V3 + V4 swaps)
2. Uniswap Liquidity Providing (V4 , including hooks)
3. GRG Staking
4. Rigoblock Governance
5. Across - Superfast crosschain transfers
6. 0x Aggregator - a ton of liquidity sources
7. GMX Dex

Further applications can be flexibly added by the governance based on demand.


# Supported Methods

Notice: in Rigoblock V4, extensions are hardcoded in the implementation via the ExtensionsMap contract, and therefore not upgradable. Adapters are upgradable, as they enable interaction with external applications.

The Rigoblock protocols requires adapters that communicate with external applications to be explicitly approved. Once an adapter is approved, the adapter methods can be added to the protocol by adding a mapping of selector to adapter. This way, the protocol correctly routes external calls by making the preemptive checks within said adapters. Once an adapter has been added, the governance can remove it by voting. Certain wallets hold governance permit to add-remove methods. Adding and removing methods of preemptively approved adapters does not require governance voting. Things are subject to change as a governance or protocol upgrade could modify these requirements.


# Selectors - V4

## Whitelisted Adapter Methods

can be called by Rigoblock pools to interact with new external applications without requiring an upgrade of the implementation.

### AMulticall

```
"ac9650d8": "multicall(bytes[])"
"5ae401dc": "multicall(uint256,bytes[])"
"1f0464d1": "multicall(bytes32,bytes[])"
```

### AStaking

```
"a694fc3a": "stake(uint256)"
"4aace835": "undelegateStake(uint256)",
"2e17de78": "unstake(uint256)",
"b880660b": "withdrawDelegatorRewards()"
```

### AUniswap

<pre><code><strong>"49616997": "unwrapWETH9(uint256)",
</strong>"49404b7c": "unwrapWETH9(uint256,address)",
"1c58db4f": "wrapETH(uint256)",
</code></pre>

### AUniswapRouter

```
"3593564c": "execute(bytes calldata, bytes[] calldata, uint256)",
"24856bc3": "execute(bytes calldata, bytes[] calldata)"
"dd46508f": "modifyLiquidities(bytes calldata, uint256)"
```

### AGovernance

```
"56781388": "castVote(uint256, VoteType)",
"fe0d94c1": "execute(uint256)",
"367015bb": "propose(Proposal, string)"
```

### AIntents

```
"770d096f": "depositV3(AcrossParams)"
```

### A0xRouter

```
"0x2213bc0b": "exec(address, address, uint256, bytes)"
```

### AGmxV2 (Arbitrum)

<pre><code>"0x7489ec23": "cancelOrder(bytes32)"
"0xe9249b57": "claimCollateral(address[],address[],address[],address)"
"0xc41b1ab3": "claimFundingFees(address[],address[],address)"
<strong>"0xe478512e": "createDecreaseOrder(CreateOrderParams)"
</strong>"0x13b4312f": "createIncreaseOrder(CreateOrderParams)"
"0xdd5baad2": "updateOrder(bytes32,uint256,uint256,uint256,uint256,uint256,bool)"
</code></pre>


# Selectors - V3

## Whitelisted Methods

can be called by Rigoblock V3 pools

### EUpgrade

```
"466f3dc3": "upgradeImplementation()"
"2d6b3a6b": "getBeacon()"
```

### AMulticall

```
"ac9650d8": "multicall(bytes[])"
"5ae401dc": "multicall(uint256,bytes[])"
"1f0464d1": "multicall(bytes32,bytes[])"
```

### AStaking

```
"a694fc3a": "stake(uint256)"
"4aace835": "undelegateStake(uint256)",
"2e17de78": "unstake(uint256)",
"b880660b": "withdrawDelegatorRewards()"
```

### AGovernance

```
"56781388": "castVote(uint256, VoteType)",
"fe0d94c1": "execute(uint256)",
"367015bb": "propose(Proposal, string)"
```


# Bug Bounty

Rigoblock V4 Bug Bounty

### Overview

Starting on September 8th, 2024, the [rigoblock-v3-contracts](https://github.com/RigoBlock/v3-contracts) repository is subject to the Rigoblock V3 Bug Bounty (the “Program”) to incentivize responsible bug disclosure.

Starting on May 29th, 2025, the [rigoblock-v3-contracts](https://github.com/RigoBlock/v3-contracts) repository is subject to the Rigoblock V4 Bug Bounty (the “Program”) to incentivize responsible bug disclosure. Rigoblock V3 smart contracts are deprecated and not covered by the Program.

### Scope

The scope of the Program is limited to bugs that result in the draining of contract funds located under contracts/protocol, and abuse of voting power in the Rigoblock governance located under contract/governance.

The following are not within the scope of the Program:

* Any contract located under contracts/mocks contracts/test or contracts/examples.
* Bugs in any third party contract or platform that interacts with Rigoblock V4.
* Vulnerabilities already reported and/or discovered in contracts built by third parties on Rigoblock V4.
* Attacks that require a Rigoblock governance takeover.
* Issues described in the "Known Issues" section.
* Any already-reported bugs.

Vulnerabilities contingent upon the occurrence of any of the following also are outside the scope of this Program:

* Frontend bugs
* Clickjacking (we do allow 3rd parties to iframe us)
* DDOS attacks
* Bugs in third party code
* Dev branches that are *not* deployed in public packages or contracts
* Third party contracts that are not under the direct control of Rigoblock
* Issues already listed in the audits for the contracts above
* Bugs in third party contracts or applications that use Rigoblock contracts
* Attacks that require oracle manipulation
* Brute force attacks
* Rounding errors
* Extreme market turmoil vulnerability
* Gas optimization recommendations
* Task Hijacking (Strandhogg)
* Spamming
* Phishing
* Automated tools (Github Actions, AWS, etc.)
* Compromise or misuse of third party systems or services

### Assumptions

Rigoblock V4 was developed with the following assumptions, and thus any bug must also adhere to the following assumptions to be eligible for the bug bounty:

* The relation between the smart pool operator and its holders is trust-minimized, but not completely trustless, with documented abuse vectors.
* The pool unitary value is automatically calculated onchain.
* Rebase tokens, interest bearing tokens and fee-on-transfer tokens, although technically usable as base tokens for a smart pool, are excluded.
* Any token is potentially ownable by the smart pools, as long as a price feed on the [BackGeoOracle](/oracles-and-price-feeds) exists. The protocol is unopinionated about the validity of the price feed, and uses a geometric mean TWAP to calculate prices for token conversions.

### Rewards

Rewards will be allocated based on the severity of the bug disclosed and will be evaluated and rewarded at the discretion of the Rigoblock team. For critical bugs that lead to any loss of smart pool funds, rewards of up to $10,000 will be granted. Lower severity bugs will be rewarded at the discretion of the team. The amount is in any case capped at 10% of the protocol TVL at risk for high and critical bugs. Rewards are paid in stablecoin.

### Prohibited Actions

* Live testing on public chains, including public mainnet deployments and public testnet deployments.
  * We recommend testing on the integrated testing framework, or on local forks, for example using foundry.
* Public disclosure of bugs without the consent of the protocol team.
* *Conflict of Interest*: any employee or contractor who currently works, or previously worked, with Rigoblock cannot participate in the Bug Bounty without prior approval.

### Disclosure

Any vulnerability or bug discovered must be reported only to the following email: <security@rigoblock.com>.

The vulnerability must not be disclosed publicly or to any other person, entity or email address before Rigoblock has been notified, has fixed the issue, and has granted permission for public disclosure. In addition, disclosure must be made within 24 hours following discovery of the vulnerability.

A detailed report of a vulnerability increases the likelihood of a reward and may increase the reward amount. Please provide as much information about the vulnerability as possible, including:

* The conditions on which reproducing the bug is contingent.
* The steps needed to reproduce the bug or, preferably, a proof of concept.
* The potential implications of the vulnerability being abused.

Anyone who reports a unique, previously-unreported vulnerability that results in a change to the code or a configuration change and who keeps such vulnerability confidential until it has been resolved by our engineers will be recognized publicly for their contribution if they so choose.

### Eligibility

To be eligible for a reward under this Program, you must:

* Discover a previously-unreported, non-public vulnerability that is not previously known by the team and within the scope of this Program.
* Be the first to disclose the unique vulnerability to <security@rigoblock.com>, in compliance with the disclosure requirements above. If similar vulnerabilities are reported within the same 24 hour period, rewards will be split at the discretion of Rigoblock.
* Provide sufficient information to enable our engineers to reproduce and fix the vulnerability.
* Not engage in any unlawful conduct when disclosing the bug, including through threats, demands, or any other coercive tactics.
* Not exploit the vulnerability in any way, including through making it public or by obtaining a profit (other than a reward under this Program).
* Make a good faith effort to avoid privacy violations, destruction of data, interruption or degradation of Rigoblock V4.
* Submit only one vulnerability per submission, unless you need to chain vulnerabilities to provide impact regarding any of the vulnerabilities.
* Not submit a vulnerability caused by an underlying issue that is the same as an issue on which a reward has been paid under this Program.
* Not engage in any unlawful conduct when disclosing the bug, including through threats, demands, or any other coercive tactics.
* Not be one of our current or former employees, vendors, or contractors or an employee of any of those vendors or contractors.
* Not be subject to US sanctions or reside in a US-embargoed country.
* Be at least 18 years of age or, if younger, submit your vulnerability with the consent of your parent or guardian.
* Comply with all the eligibility requirements of the Program.

### Rewards

The Program includes the following 3 level severity scale:

* **Critical** Issues that could impact numerous users and have serious reputational, legal or financial implications. An example would be being able to lock contracts permanently or take funds from all smart pools / users.
* **High** Issues that impact individual smart pools / users where exploitation would pose reputational, legal or moderate financial risk to the smart pool / user.
* **Medium** The risk is relatively small and does not pose a threat to smart pool / user funds.

Rewards will be given based on the above severity as well as the likelihood of the bug being triggered or exploited, to be determined at the sole discretion of Rigoblock.

### Payout Calculations

| Risk Score | Payout                       |
| ---------- | ---------------------------- |
| Critical   | up to $10,000 - minimum $200 |
| High       | up to $2,000 - minimum $150  |
| Medium     | up to $250 - minimum $100    |

### Other Terms

By submitting your report, you grant Rigoblock any and all rights, including intellectual property rights, needed to validate, mitigate, and disclose the vulnerability. All reward decisions, including eligibility for and amounts of the rewards and the manner in which such rewards will be paid, are made at our sole discretion. The terms and conditions of this Program may be altered at any time.


# Known Issues

The following is a non-exhaustive list of known potential attack vectors:

* **Pool Transaction Front-Running by a Malicious Pool Operator**\
  A pool operator's coordinated wallet could front-run pool transactions. A potential mitigation, such as setting a maximum slippage against an on-chain price feed, may cause transaction reverts in high-volatility environments. However, this does not fully address the issue, as a rogue pool operator could achieve the same result by executing multiple smaller transactions. This attack assumes privileged access (pool operator) with malicious intent against the pool's Total Value Locked (TVL). Additionally, an external attacker could exploit the binding to prevent a pool from executing swaps by manipulating the token price in a sandwich attack. Temporarily blocking a smart pool from executing transactions after a significant price drawdown is not a viable solution, as it could hinder operations during high-volatility periods—when the greatest opportunities arise—and unnecessarily increase gas costs. Developers can implement custom rules on top of the protocol to apply their preferred mitigation strategies.
* **Pool Burn Front-Running by a Malicious Pool Operator**

  A pool operator could initiate a crosschain Sync operation using input param that result in the crosschain deposit to expire without being filled on the destination chain. This can result in the burn to fail, or in the holder to receive a smaller amount than he should. At the same time, the pool operator cannot know when the refund will occur, which partially counterbalances the incentive for such an attack.
* **Purchase of a Rogue Token**\
  A rogue token, such as one created by the pool operator, could be purchased. This issue is not addressed, as the RigoBlock protocol is unopinionated about which tokens can be included in a pool, as long as they conform to token standards and can be exchanged.
* **Setting a Rogue Token as Accepted for Mint Operations**

  A rogue token could be deployed and set as acceptable mint token by the pool operator. Whenever someone mints using the base token, anyone could manipulate the rogue token price on the open market and mint big amounts of pool tokens.
* **Purchase of a Debt Token**\
  Purchasing a debt token via a swap or similar action should not be possible on the open market, as debt positions typically have no positive value. However, a sophisticated attack by the pool operator could potentially enable this.
* **Unitary Value Calculation Errors Due to Price Feed**\
  On tokens where the oracle liquidity pool is small, or on chains where gas price is high, thus not resulting in a timely price feed update, the smart pool's unitary price calculations may result in error, which might become significant if the owned token has a big percentage of the total portfolio weight. Furthermore, an incorrectly initialized token price feed could take time to get corrected. Pool operators should use caution when using new or illiquid tokens. In particular, the protocol is not opinionated about a price feed's cardinality (a cardinality of 2 - the minimum required - means that the TWAP is very sensitive to changes in the spot price, while a correctly configured oracle is slower to adapt).
* **Oracle Manipulation Attacks**

  Rigoblock uses the BackGeoOracle, a MEV-resistant onchain price feed oracle, for real time NAV calculations. An oracle manipulation, either via MEV-boost, or via a pure market manipulation, could result in the oracle returning an incorrect price, thus distorting NAV calculations. An attacker could decide to lose funds in order to manipulate the market price, as long as the gain is bigger. This is true for any type of oracle used. Using a geometric mean protects against temporary price fluctuations.
* **Attacks Requiring Special Privileges**\
  Attacks that rely on privileged access, such as those executed by the pool operator.
* **Attacks Involving a Compromised Pool Operator Private Key**\
  Attacks that exploit a compromised pool operator private key.
* **Use of a Malicious Uniswap V4 Hook**\
  Although Rigoblock V4 includes safeguards to prevent accidental input errors and restrict hooks' access to a pool's liquidity token balances, the protocol does not restrict the types of hooks a pool may use. A malicious Uniswap V4 hook could impose fees up to 100% of the swap amount, resulting in significant or total loss of funds. As when interacting directly with Uniswap V4, users must exercise extreme caution when interacting with Uniswap V4 hooks via RigoBlock.
* **Crosschain Sync Latency**\
  While single-chain pool price is updated in real time, the price will differ across chains until a Sync operation is prompted by the pool operator. These operations can be sent programmatically, and are entirely under the pool operator's control.
* **Chains that do not use address(0) as Native Currency**\
  Chains that use a token as base currency are not currently supported by the v4 protocol.
* **Chains that do not Support Transient Storage Opcodes**\
  Chains that do not support transient storage are not compatible with Rigoblock V4.

Therefore, the relationship between the pool operator and pool holder(s) is trust-minimized, and serves as the rails to run strategies onchain, where the LPs have agreed to some offchain terms which the protocol does not enforce. Rigoblock provides an extra layer of security for pool operators to interact with on-chain applications and enhances transparency by tracking real-time pool activity, portfolio positions, and price calculations.


# Contracts

The smart contract used in the Rigoblock ecosystem

{% content-ref url="/pages/xv7L9ogJs8z4nE8jHbuk" %}
[Protocol](/contracts/protocol)
{% endcontent-ref %}

{% content-ref url="/pages/zJdOVWuy72ta6StfwtiY" %}
[GRG Token](/contracts/grg-token)
{% endcontent-ref %}

{% content-ref url="/pages/mbAPys21KL7k2Zs90MfK" %}
[GRG Staking](/contracts/grg-staking)
{% endcontent-ref %}

{% content-ref url="/pages/6oLMzjeRIFZMOE1wTNi9" %}
[Governance](/governance)
{% endcontent-ref %}


# Protocol

The contracts of the RigoBlock protocol

{% content-ref url="/pages/yq4xTVvGvxWjFtgPUjVj" %}
[Core](/contracts/protocol/core)
{% endcontent-ref %}

{% content-ref url="/pages/CjvjyfL8ZchPcdse5nGR" %}
[Deps](/contracts/protocol/deps)
{% endcontent-ref %}

{% content-ref url="/pages/oKQnv2p06zgfOtOLaMwa" %}
[Extensions](/contracts/protocol/extensions)
{% endcontent-ref %}

{% content-ref url="/pages/wkcdmcyGuR72ldLt04Va" %}
[Proxies](/contracts/protocol/proxies)
{% endcontent-ref %}

### Mapping of versions to implementation addresses

* HF 3.1.0 -> 0xeb0c08Ad44af89BcBB5Ed6dD28caD452311B8516 (initial v3 implementation)
* HF 3.1.2 -> 0x7Df14Ba4a5f565cD56206e49Fc66b3002A91841d (self custody deprecated)
* 4.0.1 -> 0xe99DEC5Ba5747E8ADF81Bd58026527c7CB042108 (automated nav)
* 4.0.2 -> 0x34481A0A48A579586B3555ed80af482ad9F79EDE (first mint fix)
* 4.0.3 -> 0xa1D8d68FFa1d7fE4863101599aF09D9C60bF49D6 (burn dos fix)
* 4.1.1 -> 0x1DB955265B8DC18715cAb12E805F9b71Fa545420
* 4.3.2 -> 0xee84f3D9095dc173a5ed1c60a7f30C3ff3064bBD

HF 3.1.0 is also the initial v3 implementation, to be used in the proxy factory constructor to obtain the same deterministic deployed address for the same pool on all networks (relevant for protocol deployment on new chains).

***

The interface "[IRigoblockPoolExtended](/contracts/protocol/rigoblockpoolextended)" includes all the methods from core implementation and supported adapters. A new instance of a Rigoblock pool can be initialized by the client by attaching a Pool Proxy's address to this interface. This way, a client can initialize the pool just once and use the same instance inside the application.

The interface is not inherited by the pool implementation, as it includes the extensions' methods, which are not implemented at the core of the protocol. Generally speaking, the implementation accepts transactions in the same format as the external applications' ABI specification, therefore a user looking to underact i.e. with the Uniswap universal router through the proxy, will be able to use the Uniswap sdk or api without modifications to the function selector.


# RigoblockPoolExtended

The interface of the Rigoblock pool, including all adapters and extensions methods.

```
[
    {
      "anonymous": false,
      "inputs": [
        {
          "indexed": true,
          "internalType": "address",
          "name": "owner",
          "type": "address"
        },
        {
          "indexed": true,
          "internalType": "address",
          "name": "spender",
          "type": "address"
        },
        {
          "indexed": false,
          "internalType": "uint256",
          "name": "value",
          "type": "uint256"
        }
      ],
      "name": "Approval",
      "type": "event"
    },
    {
      "anonymous": false,
      "inputs": [
        {
          "indexed": true,
          "internalType": "address",
          "name": "pool",
          "type": "address"
        },
        {
          "indexed": true,
          "internalType": "address",
          "name": "kycProvider",
          "type": "address"
        }
      ],
      "name": "KycProviderSet",
      "type": "event"
    },
    {
      "anonymous": false,
      "inputs": [
        {
          "indexed": true,
          "internalType": "address",
          "name": "pool",
          "type": "address"
        },
        {
          "indexed": false,
          "internalType": "uint48",
          "name": "minimumPeriod",
          "type": "uint48"
        }
      ],
      "name": "MinimumPeriodChanged",
      "type": "event"
    },
    {
      "anonymous": false,
      "inputs": [
        {
          "indexed": true,
          "internalType": "address",
          "name": "pool",
          "type": "address"
        },
        {
          "indexed": true,
          "internalType": "address",
          "name": "who",
          "type": "address"
        },
        {
          "indexed": false,
          "internalType": "address",
          "name": "feeCollector",
          "type": "address"
        }
      ],
      "name": "NewCollector",
      "type": "event"
    },
    {
      "anonymous": false,
      "inputs": [
        {
          "indexed": true,
          "internalType": "address",
          "name": "pool",
          "type": "address"
        },
        {
          "indexed": true,
          "internalType": "address",
          "name": "who",
          "type": "address"
        },
        {
          "indexed": false,
          "internalType": "uint16",
          "name": "transactionFee",
          "type": "uint16"
        }
      ],
      "name": "NewFee",
      "type": "event"
    },
    {
      "anonymous": false,
      "inputs": [
        {
          "indexed": true,
          "internalType": "address",
          "name": "sender",
          "type": "address"
        },
        {
          "indexed": true,
          "internalType": "address",
          "name": "pool",
          "type": "address"
        },
        {
          "indexed": false,
          "internalType": "uint256",
          "name": "unitaryValue",
          "type": "uint256"
        }
      ],
      "name": "NewNav",
      "type": "event"
    },
    {
      "anonymous": false,
      "inputs": [
        {
          "indexed": true,
          "internalType": "address",
          "name": "old",
          "type": "address"
        },
        {
          "indexed": true,
          "internalType": "address",
          "name": "current",
          "type": "address"
        }
      ],
      "name": "NewOwner",
      "type": "event"
    },
    {
      "anonymous": false,
      "inputs": [
        {
          "indexed": true,
          "internalType": "address",
          "name": "holder",
          "type": "address"
        },
        {
          "indexed": true,
          "internalType": "address",
          "name": "operator",
          "type": "address"
        },
        {
          "indexed": false,
          "internalType": "bool",
          "name": "approved",
          "type": "bool"
        }
      ],
      "name": "OperatorSet",
      "type": "event"
    },
    {
      "anonymous": false,
      "inputs": [
        {
          "indexed": true,
          "internalType": "address",
          "name": "group",
          "type": "address"
        },
        {
          "indexed": true,
          "internalType": "address",
          "name": "owner",
          "type": "address"
        },
        {
          "indexed": true,
          "internalType": "address",
          "name": "baseToken",
          "type": "address"
        },
        {
          "indexed": false,
          "internalType": "string",
          "name": "name",
          "type": "string"
        },
        {
          "indexed": false,
          "internalType": "bytes8",
          "name": "symbol",
          "type": "bytes8"
        }
      ],
      "name": "PoolInitialized",
      "type": "event"
    },
    {
      "anonymous": false,
      "inputs": [
        {
          "indexed": true,
          "internalType": "address",
          "name": "pool",
          "type": "address"
        },
        {
          "indexed": false,
          "internalType": "uint16",
          "name": "spread",
          "type": "uint16"
        }
      ],
      "name": "SpreadChanged",
      "type": "event"
    },
    {
      "anonymous": false,
      "inputs": [
        {
          "indexed": true,
          "internalType": "address",
          "name": "from",
          "type": "address"
        },
        {
          "indexed": true,
          "internalType": "address",
          "name": "to",
          "type": "address"
        },
        {
          "indexed": false,
          "internalType": "uint256",
          "name": "value",
          "type": "uint256"
        }
      ],
      "name": "Transfer",
      "type": "event"
    },
    {
      "anonymous": false,
      "inputs": [
        {
          "indexed": true,
          "internalType": "address",
          "name": "implementation",
          "type": "address"
        }
      ],
      "name": "Upgraded",
      "type": "event"
    },
    {
      "stateMutability": "payable",
      "type": "fallback"
    },
    {
      "inputs": [],
      "name": "VERSION",
      "outputs": [
        {
          "internalType": "string",
          "name": "",
          "type": "string"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "address",
          "name": "owner",
          "type": "address"
        },
        {
          "internalType": "address",
          "name": "spender",
          "type": "address"
        }
      ],
      "name": "allowance",
      "outputs": [
        {
          "internalType": "uint256",
          "name": "",
          "type": "uint256"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "address",
          "name": "spender",
          "type": "address"
        },
        {
          "internalType": "uint256",
          "name": "value",
          "type": "uint256"
        }
      ],
      "name": "approve",
      "outputs": [
        {
          "internalType": "bool",
          "name": "success",
          "type": "bool"
        }
      ],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [],
      "name": "authority",
      "outputs": [
        {
          "internalType": "address",
          "name": "",
          "type": "address"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "address",
          "name": "who",
          "type": "address"
        }
      ],
      "name": "balanceOf",
      "outputs": [
        {
          "internalType": "uint256",
          "name": "",
          "type": "uint256"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "uint256",
          "name": "amountIn",
          "type": "uint256"
        },
        {
          "internalType": "uint256",
          "name": "amountOutMin",
          "type": "uint256"
        }
      ],
      "name": "burn",
      "outputs": [
        {
          "internalType": "uint256",
          "name": "netRevenue",
          "type": "uint256"
        }
      ],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "uint256",
          "name": "amountIn",
          "type": "uint256"
        },
        {
          "internalType": "uint256",
          "name": "amountOutMin",
          "type": "uint256"
        },
        {
          "internalType": "address",
          "name": "tokenOut",
          "type": "address"
        }
      ],
      "name": "burnForToken",
      "outputs": [
        {
          "internalType": "uint256",
          "name": "netRevenue",
          "type": "uint256"
        }
      ],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "uint256",
          "name": "proposalId",
          "type": "uint256"
        },
        {
          "internalType": "enum IGovernanceVoting.VoteType",
          "name": "voteType",
          "type": "uint8"
        }
      ],
      "name": "castVote",
      "outputs": [],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "address",
          "name": "feeCollector",
          "type": "address"
        }
      ],
      "name": "changeFeeCollector",
      "outputs": [],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "uint48",
          "name": "minPeriod",
          "type": "uint48"
        }
      ],
      "name": "changeMinPeriod",
      "outputs": [],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "uint16",
          "name": "newSpread",
          "type": "uint16"
        }
      ],
      "name": "changeSpread",
      "outputs": [],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "address[]",
          "name": "tokens",
          "type": "address[]"
        },
        {
          "internalType": "int256[]",
          "name": "amounts",
          "type": "int256[]"
        },
        {
          "internalType": "address",
          "name": "targetToken",
          "type": "address"
        }
      ],
      "name": "convertBatchTokenAmounts",
      "outputs": [
        {
          "internalType": "int256",
          "name": "totalConvertedAmount",
          "type": "int256"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "address",
          "name": "token",
          "type": "address"
        },
        {
          "internalType": "int256",
          "name": "amount",
          "type": "int256"
        },
        {
          "internalType": "address",
          "name": "targetToken",
          "type": "address"
        }
      ],
      "name": "convertTokenAmount",
      "outputs": [
        {
          "internalType": "int256",
          "name": "convertedAmount",
          "type": "int256"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [],
      "name": "decimals",
      "outputs": [
        {
          "internalType": "uint8",
          "name": "",
          "type": "uint8"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "bytes",
          "name": "commands",
          "type": "bytes"
        },
        {
          "internalType": "bytes[]",
          "name": "inputs",
          "type": "bytes[]"
        }
      ],
      "name": "execute",
      "outputs": [],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "bytes",
          "name": "commands",
          "type": "bytes"
        },
        {
          "internalType": "bytes[]",
          "name": "inputs",
          "type": "bytes[]"
        },
        {
          "internalType": "uint256",
          "name": "deadline",
          "type": "uint256"
        }
      ],
      "name": "execute",
      "outputs": [],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "uint256",
          "name": "proposalId",
          "type": "uint256"
        }
      ],
      "name": "execute",
      "outputs": [],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [],
      "name": "getActiveApplications",
      "outputs": [
        {
          "internalType": "uint256",
          "name": "packedApplications",
          "type": "uint256"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [],
      "name": "getActiveTokens",
      "outputs": [
        {
          "components": [
            {
              "internalType": "address[]",
              "name": "activeTokens",
              "type": "address[]"
            },
            {
              "internalType": "address",
              "name": "baseToken",
              "type": "address"
            }
          ],
          "internalType": "struct ISmartPoolState.ActiveTokens",
          "name": "tokens",
          "type": "tuple"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "uint256",
          "name": "packedApplications",
          "type": "uint256"
        }
      ],
      "name": "getAppTokenBalances",
      "outputs": [
        {
          "components": [
            {
              "components": [
                {
                  "internalType": "address",
                  "name": "token",
                  "type": "address"
                },
                {
                  "internalType": "int256",
                  "name": "amount",
                  "type": "int256"
                }
              ],
              "internalType": "struct AppTokenBalance[]",
              "name": "balances",
              "type": "tuple[]"
            },
            {
              "internalType": "uint256",
              "name": "appType",
              "type": "uint256"
            }
          ],
          "internalType": "struct ExternalApp[]",
          "name": "appBalances",
          "type": "tuple[]"
        }
      ],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [],
      "name": "getBeacon",
      "outputs": [
        {
          "internalType": "address",
          "name": "",
          "type": "address"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [],
      "name": "getPool",
      "outputs": [
        {
          "components": [
            {
              "internalType": "string",
              "name": "name",
              "type": "string"
            },
            {
              "internalType": "string",
              "name": "symbol",
              "type": "string"
            },
            {
              "internalType": "uint8",
              "name": "decimals",
              "type": "uint8"
            },
            {
              "internalType": "address",
              "name": "owner",
              "type": "address"
            },
            {
              "internalType": "address",
              "name": "baseToken",
              "type": "address"
            }
          ],
          "internalType": "struct ISmartPoolState.ReturnedPool",
          "name": "",
          "type": "tuple"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [],
      "name": "getPoolParams",
      "outputs": [
        {
          "components": [
            {
              "internalType": "uint48",
              "name": "minPeriod",
              "type": "uint48"
            },
            {
              "internalType": "uint16",
              "name": "spread",
              "type": "uint16"
            },
            {
              "internalType": "uint16",
              "name": "transactionFee",
              "type": "uint16"
            },
            {
              "internalType": "address",
              "name": "feeCollector",
              "type": "address"
            },
            {
              "internalType": "address",
              "name": "kycProvider",
              "type": "address"
            }
          ],
          "internalType": "struct ISmartPoolState.PoolParams",
          "name": "",
          "type": "tuple"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [],
      "name": "getPoolStorage",
      "outputs": [
        {
          "components": [
            {
              "internalType": "string",
              "name": "name",
              "type": "string"
            },
            {
              "internalType": "string",
              "name": "symbol",
              "type": "string"
            },
            {
              "internalType": "uint8",
              "name": "decimals",
              "type": "uint8"
            },
            {
              "internalType": "address",
              "name": "owner",
              "type": "address"
            },
            {
              "internalType": "address",
              "name": "baseToken",
              "type": "address"
            }
          ],
          "internalType": "struct ISmartPoolState.ReturnedPool",
          "name": "poolInitParams",
          "type": "tuple"
        },
        {
          "components": [
            {
              "internalType": "uint48",
              "name": "minPeriod",
              "type": "uint48"
            },
            {
              "internalType": "uint16",
              "name": "spread",
              "type": "uint16"
            },
            {
              "internalType": "uint16",
              "name": "transactionFee",
              "type": "uint16"
            },
            {
              "internalType": "address",
              "name": "feeCollector",
              "type": "address"
            },
            {
              "internalType": "address",
              "name": "kycProvider",
              "type": "address"
            }
          ],
          "internalType": "struct ISmartPoolState.PoolParams",
          "name": "poolVariables",
          "type": "tuple"
        },
        {
          "components": [
            {
              "internalType": "uint256",
              "name": "unitaryValue",
              "type": "uint256"
            },
            {
              "internalType": "uint256",
              "name": "totalSupply",
              "type": "uint256"
            }
          ],
          "internalType": "struct ISmartPoolState.PoolTokens",
          "name": "poolTokensInfo",
          "type": "tuple"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [],
      "name": "getPoolTokens",
      "outputs": [
        {
          "components": [
            {
              "internalType": "uint256",
              "name": "unitaryValue",
              "type": "uint256"
            },
            {
              "internalType": "uint256",
              "name": "totalSupply",
              "type": "uint256"
            }
          ],
          "internalType": "struct ISmartPoolState.PoolTokens",
          "name": "",
          "type": "tuple"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "uint256",
          "name": "offset",
          "type": "uint256"
        },
        {
          "internalType": "uint256",
          "name": "length",
          "type": "uint256"
        }
      ],
      "name": "getStorageAt",
      "outputs": [
        {
          "internalType": "bytes",
          "name": "",
          "type": "bytes"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "uint256[]",
          "name": "slots",
          "type": "uint256[]"
        }
      ],
      "name": "getStorageSlotsAt",
      "outputs": [
        {
          "internalType": "bytes",
          "name": "",
          "type": "bytes"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "address",
          "name": "token",
          "type": "address"
        }
      ],
      "name": "getTwap",
      "outputs": [
        {
          "internalType": "int24",
          "name": "twap",
          "type": "int24"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [],
      "name": "getUniV4TokenIds",
      "outputs": [
        {
          "internalType": "uint256[]",
          "name": "tokenIds",
          "type": "uint256[]"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "address",
          "name": "_who",
          "type": "address"
        }
      ],
      "name": "getUserAccount",
      "outputs": [
        {
          "components": [
            {
              "internalType": "uint208",
              "name": "userBalance",
              "type": "uint208"
            },
            {
              "internalType": "uint48",
              "name": "activation",
              "type": "uint48"
            }
          ],
          "internalType": "struct ISmartPoolState.UserAccount",
          "name": "",
          "type": "tuple"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "address",
          "name": "token",
          "type": "address"
        }
      ],
      "name": "hasPriceFeed",
      "outputs": [
        {
          "internalType": "bool",
          "name": "",
          "type": "bool"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [],
      "name": "initializePool",
      "outputs": [],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "address",
          "name": "holder",
          "type": "address"
        },
        {
          "internalType": "address",
          "name": "operator",
          "type": "address"
        }
      ],
      "name": "isOperator",
      "outputs": [
        {
          "internalType": "bool",
          "name": "approved",
          "type": "bool"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "address",
          "name": "recipient",
          "type": "address"
        },
        {
          "internalType": "uint256",
          "name": "amountIn",
          "type": "uint256"
        },
        {
          "internalType": "uint256",
          "name": "amountOutMin",
          "type": "uint256"
        }
      ],
      "name": "mint",
      "outputs": [
        {
          "internalType": "uint256",
          "name": "recipientAmount",
          "type": "uint256"
        }
      ],
      "stateMutability": "payable",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "bytes",
          "name": "unlockData",
          "type": "bytes"
        },
        {
          "internalType": "uint256",
          "name": "deadline",
          "type": "uint256"
        }
      ],
      "name": "modifyLiquidities",
      "outputs": [],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "bytes32",
          "name": "previousBlockhash",
          "type": "bytes32"
        },
        {
          "internalType": "bytes[]",
          "name": "data",
          "type": "bytes[]"
        }
      ],
      "name": "multicall",
      "outputs": [
        {
          "internalType": "bytes[]",
          "name": "results",
          "type": "bytes[]"
        }
      ],
      "stateMutability": "payable",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "uint256",
          "name": "deadline",
          "type": "uint256"
        },
        {
          "internalType": "bytes[]",
          "name": "data",
          "type": "bytes[]"
        }
      ],
      "name": "multicall",
      "outputs": [
        {
          "internalType": "bytes[]",
          "name": "results",
          "type": "bytes[]"
        }
      ],
      "stateMutability": "payable",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "bytes[]",
          "name": "data",
          "type": "bytes[]"
        }
      ],
      "name": "multicall",
      "outputs": [
        {
          "internalType": "bytes[]",
          "name": "results",
          "type": "bytes[]"
        }
      ],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [],
      "name": "name",
      "outputs": [
        {
          "internalType": "string",
          "name": "",
          "type": "string"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [],
      "name": "owner",
      "outputs": [
        {
          "internalType": "address",
          "name": "",
          "type": "address"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [
        {
          "components": [
            {
              "internalType": "address",
              "name": "target",
              "type": "address"
            },
            {
              "internalType": "bytes",
              "name": "data",
              "type": "bytes"
            },
            {
              "internalType": "uint256",
              "name": "value",
              "type": "uint256"
            }
          ],
          "internalType": "struct IGovernanceVoting.ProposedAction[]",
          "name": "actions",
          "type": "tuple[]"
        },
        {
          "internalType": "string",
          "name": "description",
          "type": "string"
        }
      ],
      "name": "propose",
      "outputs": [],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [],
      "name": "purgeInactiveTokensAndApps",
      "outputs": [],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "address",
          "name": "kycProvider",
          "type": "address"
        }
      ],
      "name": "setKycProvider",
      "outputs": [],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "address",
          "name": "operator",
          "type": "address"
        },
        {
          "internalType": "bool",
          "name": "approved",
          "type": "bool"
        }
      ],
      "name": "setOperator",
      "outputs": [
        {
          "internalType": "bool",
          "name": "",
          "type": "bool"
        }
      ],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "address",
          "name": "newOwner",
          "type": "address"
        }
      ],
      "name": "setOwner",
      "outputs": [],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "uint16",
          "name": "transactionFee",
          "type": "uint16"
        }
      ],
      "name": "setTransactionFee",
      "outputs": [],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "uint256",
          "name": "amount",
          "type": "uint256"
        }
      ],
      "name": "stake",
      "outputs": [],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [],
      "name": "symbol",
      "outputs": [
        {
          "internalType": "string",
          "name": "",
          "type": "string"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [],
      "name": "totalSupply",
      "outputs": [
        {
          "internalType": "uint256",
          "name": "",
          "type": "uint256"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "address",
          "name": "to",
          "type": "address"
        },
        {
          "internalType": "uint256",
          "name": "value",
          "type": "uint256"
        }
      ],
      "name": "transfer",
      "outputs": [
        {
          "internalType": "bool",
          "name": "success",
          "type": "bool"
        }
      ],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "address",
          "name": "from",
          "type": "address"
        },
        {
          "internalType": "address",
          "name": "to",
          "type": "address"
        },
        {
          "internalType": "uint256",
          "name": "value",
          "type": "uint256"
        }
      ],
      "name": "transferFrom",
      "outputs": [
        {
          "internalType": "bool",
          "name": "success",
          "type": "bool"
        }
      ],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "uint256",
          "name": "amount",
          "type": "uint256"
        }
      ],
      "name": "undelegateStake",
      "outputs": [],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "uint256",
          "name": "amount",
          "type": "uint256"
        }
      ],
      "name": "unstake",
      "outputs": [],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "uint256",
          "name": "amountMinimum",
          "type": "uint256"
        },
        {
          "internalType": "address",
          "name": "recipient",
          "type": "address"
        }
      ],
      "name": "unwrapWETH9",
      "outputs": [],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "uint256",
          "name": "amountMinimum",
          "type": "uint256"
        }
      ],
      "name": "unwrapWETH9",
      "outputs": [],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [],
      "name": "updateUnitaryValue",
      "outputs": [],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [],
      "name": "upgradeImplementation",
      "outputs": [],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [],
      "name": "withdrawDelegatorRewards",
      "outputs": [],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [
        {
          "internalType": "uint256",
          "name": "value",
          "type": "uint256"
        }
      ],
      "name": "wrapETH",
      "outputs": [],
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "inputs": [],
      "name": "wrappedNative",
      "outputs": [
        {
          "internalType": "address",
          "name": "",
          "type": "address"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },
    {
      "stateMutability": "payable",
      "type": "receive"
    }
  ]
```


# Core

The modular core is designed in order to maximize code readability and is divided in sub-modules

* constants --> the deployment constants
* immutables --> the deployment immutables, initialized in the constructor
* storage --> the deterministic pool storage (the order of variable declaration is irrelevant as the variable is assigned a randomly big-enough storage slot
* owner actions --> the actions restricted to the pool operator only
* actions --> the publicly accessible write methods
* state --> the public read methods
* storage accessible --> a generic contracts which can retrieve any batch of data at any combination of storage slots
* events --> the logs emitted at a pool's transaction


# constants

## MixinConstants

Constants are copied in the bytecode and not assigned a storage slot, can safely be added to this contract.

*Inheriting from interface is required as we override public variables.*

### VERSION

```solidity
string VERSION
```

Returns a string of the pool version.

#### Return Values

### \_POOL\_INIT\_SLOT

```solidity
bytes32 _POOL_INIT_SLOT
```

### \_POOL\_VARIABLES\_SLOT

```solidity
bytes32 _POOL_VARIABLES_SLOT
```

### \_POOL\_TOKENS\_SLOT

```solidity
bytes32 _POOL_TOKENS_SLOT
```

### \_POOL\_ACCOUNTS\_SLOT

```solidity
bytes32 _POOL_ACCOUNTS_SLOT
```

### \_FEE\_BASE

```solidity
uint16 _FEE_BASE
```

### \_INITIAL\_SPREAD

```solidity
uint16 _INITIAL_SPREAD
```

### \_MAX\_SPREAD

```solidity
uint16 _MAX_SPREAD
```

### \_MAX\_TRANSACTION\_FEE

```solidity
uint16 _MAX_TRANSACTION_FEE
```

### \_MINIMUM\_ORDER\_DIVISOR

```solidity
uint16 _MINIMUM_ORDER_DIVISOR
```

### \_SPREAD\_BASE

```solidity
uint16 _SPREAD_BASE
```

### \_MAX\_LOCKUP

```solidity
uint48 _MAX_LOCKUP
```

### \_MIN\_LOCKUP

```solidity
uint48 _MIN_LOCKUP
```

### \_TRANSFER\_FROM\_SELECTOR

```solidity
bytes4 _TRANSFER_FROM_SELECTOR
```

### \_TRANSFER\_SELECTOR

```solidity
bytes4 _TRANSFER_SELECTOR
```


# immutables

## MixinImmutables

Immutables are not assigned a storage slot, can be safely added to this contract.

### authority

```solidity
address authority
```

Returns the address of the authority contract.

#### Return Values

### \_implementation

```solidity
address _implementation
```

### constructor

```solidity
constructor(address newAuthority) internal
```


# storage

## MixinStorage

Storage slots must be preserved to prevent storage clashing.

*Pool storage is not sequential: each variable is wrapped into a struct which is assigned a storage slot.*

### constructor

```solidity
constructor() internal
```

### Accounts

```solidity
struct Accounts {
  mapping(address => struct IRigoblockV3PoolState.UserAccount) userAccounts;
}
```

### accounts

```solidity
function accounts() internal pure returns (struct MixinStorage.Accounts s)
```

### Pool

```solidity
struct Pool {
  string name;
  bytes8 symbol;
  uint8 decimals;
  address owner;
  bool unlocked;
  address baseToken;
}
```

### pool

```solidity
function pool() internal pure returns (struct MixinStorage.Pool s)
```

### PoolWrapper

```solidity
struct PoolWrapper {
  struct MixinStorage.Pool pool;
}
```

### poolWrapper

```solidity
function poolWrapper() internal pure returns (struct MixinStorage.PoolWrapper s)
```

### poolParams

```solidity
function poolParams() internal pure returns (struct IRigoblockV3PoolState.PoolParams s)
```

### poolTokens

```solidity
function poolTokens() internal pure returns (struct IRigoblockV3PoolState.PoolTokens s)
```


# actions

## MixinActions

### nonReentrant

```solidity
modifier nonReentrant()
```

Functions with this modifer cannot be reentered. The mutex will be locked before function execution and unlocked after.

### mint

```solidity
function mint(address recipient, uint256 amountIn, uint256 amountOutMin) public payable returns (uint256 recipientAmount)
```

Allows a user to mint pool tokens on behalf of an address.

#### Parameters

| Name         | Type    | Description                                                         |
| ------------ | ------- | ------------------------------------------------------------------- |
| recipient    | address | Address receiving the tokens.                                       |
| amountIn     | uint256 | Amount of base tokens.                                              |
| amountOutMin | uint256 | Minimum amount to be received, prevents pool operator frontrunning. |

#### Return Values

| Name            | Type    | Description                           |
| --------------- | ------- | ------------------------------------- |
| recipientAmount | uint256 | Number of tokens minted to recipient. |

### burn

```solidity
function burn(uint256 amountIn, uint256 amountOutMin) external returns (uint256 netRevenue)
```

Allows a pool holder to burn pool tokens.

#### Parameters

| Name         | Type    | Description                                                         |
| ------------ | ------- | ------------------------------------------------------------------- |
| amountIn     | uint256 | Number of tokens to burn.                                           |
| amountOutMin | uint256 | Minimum amount to be received, prevents pool operator frontrunning. |

#### Return Values

| Name       | Type    | Description                      |
| ---------- | ------- | -------------------------------- |
| netRevenue | uint256 | Net amount of burnt pool tokens. |

### decimals

```solidity
function decimals() public view virtual returns (uint8)
```

Returns token decimals.

#### Return Values

| Name | Type  | Description               |
| ---- | ----- | ------------------------- |
| \[0] | uint8 | Uint8 number of decimals. |

### \_getFeeCollector

```solidity
function _getFeeCollector() internal view virtual returns (address)
```

### \_getMinPeriod

```solidity
function _getMinPeriod() internal view virtual returns (uint48)
```

### \_getSpread

```solidity
function _getSpread() internal view virtual returns (uint16)
```

### \_getUnitaryValue

```solidity
function _getUnitaryValue() internal view virtual returns (uint256)
```

### \_allocateMintTokens

```solidity
function _allocateMintTokens(address recipient, uint256 mintedAmount) private returns (uint256 recipientAmount)
```

Allocates tokens to recipient. Fee tokens are locked too.

*Each new mint on same recipient sets new activation on all owned tokens.*

#### Parameters

| Name         | Type    | Description               |
| ------------ | ------- | ------------------------- |
| recipient    | address | Address of the recipient. |
| mintedAmount | uint256 | Value of issued tokens.   |

#### Return Values

| Name            | Type    | Description                               |
| --------------- | ------- | ----------------------------------------- |
| recipientAmount | uint256 | Number of new tokens issued to recipient. |

### \_allocateBurnTokens

```solidity
function _allocateBurnTokens(uint256 amountIn) private returns (uint256 burntAmount)
```

Destroys tokens of holder.

*Fee is paid in pool tokens.*

#### Parameters

| Name     | Type    | Description                  |
| -------- | ------- | ---------------------------- |
| amountIn | uint256 | Value of tokens to be burnt. |

#### Return Values

| Name        | Type    | Description                 |
| ----------- | ------- | --------------------------- |
| burntAmount | uint256 | Number of net burnt tokens. |

### \_assertBiggerThanMinimum

```solidity
function _assertBiggerThanMinimum(uint256 amount) private view
```

### \_safeTransfer

```solidity
function _safeTransfer(address to, uint256 amount) private
```

### \_safeTransferFrom

```solidity
function _safeTransferFrom(address from, address to, uint256 amount) private
```


# owner actions

## MixinOwnerActions

### notPriceError

```solidity
modifier notPriceError(uint256 newUnitaryValue)
```

*We keep this check to prevent accidental failure in Nav calculations.*

### onlyOwner

```solidity
modifier onlyOwner()
```

### changeFeeCollector

```solidity
function changeFeeCollector(address feeCollector) external
```

Allows owner to decide where to receive the fee.

#### Parameters

| Name         | Type    | Description                  |
| ------------ | ------- | ---------------------------- |
| feeCollector | address | Address of the fee receiver. |

### changeMinPeriod

```solidity
function changeMinPeriod(uint48 minPeriod) external
```

Allows pool owner to change the minimum holding period.

#### Parameters

| Name      | Type   | Description      |
| --------- | ------ | ---------------- |
| minPeriod | uint48 | Time in seconds. |

### changeSpread

```solidity
function changeSpread(uint16 newSpread) external
```

Allows pool owner to change the mint/burn spread.

#### Parameters

| Name      | Type   | Description                                 |
| --------- | ------ | ------------------------------------------- |
| newSpread | uint16 | Number between 0 and 1000, in basis points. |

### setKycProvider

```solidity
function setKycProvider(address kycProvider) external
```

Allows pool owner to set/update the user whitelist contract.

*Kyc provider can be set to null, removing user whitelist requirement.*

#### Parameters

| Name        | Type    | Description                  |
| ----------- | ------- | ---------------------------- |
| kycProvider | address | Address if the kyc provider. |

### setTransactionFee

```solidity
function setTransactionFee(uint16 transactionFee) external
```

Allows pool owner to set the transaction fee.

#### Parameters

| Name           | Type   | Description                                   |
| -------------- | ------ | --------------------------------------------- |
| transactionFee | uint16 | Value of the transaction fee in basis points. |

### setUnitaryValue

```solidity
function setUnitaryValue(uint256 unitaryValue) external
```

Allows pool owner to set the pool price.

#### Parameters

| Name         | Type    | Description                    |
| ------------ | ------- | ------------------------------ |
| unitaryValue | uint256 | Value of 1 token in wei units. |

### setOwner

```solidity
function setOwner(address newOwner) public
```

Allows pool owner to set a new owner address.

*Method restricted to owner.*

#### Parameters

| Name     | Type    | Description               |
| -------- | ------- | ------------------------- |
| newOwner | address | Address of the new owner. |

### totalSupply

```solidity
function totalSupply() public view virtual returns (uint256)
```

Returns the total amount of issued tokens for this pool.

#### Return Values

| Name | Type    | Description                    |
| ---- | ------- | ------------------------------ |
| \[0] | uint256 | Number of total issued tokens. |

### decimals

```solidity
function decimals() public view virtual returns (uint8)
```

Returns token decimals.

#### Return Values

| Name | Type  | Description               |
| ---- | ----- | ------------------------- |
| \[0] | uint8 | Uint8 number of decimals. |

### \_getUnitaryValue

```solidity
function _getUnitaryValue() internal view virtual returns (uint256)
```

### \_isContract

```solidity
function _isContract(address target) private view returns (bool)
```


# abstract

## MixinAbstract

This contract makes it easy for clients to track ERC20.

### transfer

```solidity
function transfer(address to, uint256 value) external returns (bool success)
```

*Non-implemented ERC20 method.*

### transferFrom

```solidity
function transferFrom(address from, address to, uint256 value) external returns (bool success)
```

*Non-implemented ERC20 method.*

### approve

```solidity
function approve(address spender, uint256 value) external returns (bool success)
```

*Non-implemented ERC20 method.*

### allowance

```solidity
function allowance(address owner, address spender) external view returns (uint256)
```

*Non-implemented ERC20 method.*


# fallback

## MixinFallback

### onlyDelegateCall

```solidity
modifier onlyDelegateCall()
```

### fallback

```solidity
fallback() external payable
```

Delegate calls to pool extension.

*Delegatecall restricted to owner, staticcall accessible by everyone. Restricting delegatecall to owner effectively locks direct calls.*

### receive

```solidity
receive() external payable
```

Allows transfers to pool.

*Prevents accidental transfer to implementation contract.*

### \_checkDelegateCall

```solidity
function _checkDelegateCall() private view
```

### \_getApplicationAdapter

```solidity
function _getApplicationAdapter(bytes4 selector) private view returns (address)
```

*Returns the address of the application adapter.*

#### Parameters

| Name     | Type   | Description                   |
| -------- | ------ | ----------------------------- |
| selector | bytes4 | Hash of the method signature. |

#### Return Values

| Name | Type    | Description                         |
| ---- | ------- | ----------------------------------- |
| \[0] | address | Address of the application adapter. |


# initializer

## MixinInitializer

### onlyUninitialized

```solidity
modifier onlyUninitialized()
```

### initializePool

```solidity
function initializePool() external
```

Initializes to pool storage.

*Pool can only be initialized at creation, meaning this method cannot be called directly to implementation.*


# state

## MixinPoolState

### balanceOf

```solidity
function balanceOf(address who) external view returns (uint256)
```

*Returns how many pool tokens a user holds.*

#### Parameters

| Name | Type    | Description                    |
| ---- | ------- | ------------------------------ |
| who  | address | Address of the target account. |

#### Return Values

| Name | Type    | Description     |
| ---- | ------- | --------------- |
| \[0] | uint256 | Number of pool. |

### getPoolStorage

```solidity
function getPoolStorage() external view returns (struct IRigoblockV3PoolState.ReturnedPool poolInitParams, struct IRigoblockV3PoolState.PoolParams poolVariables, struct IRigoblockV3PoolState.PoolTokens poolTokensInfo)
```

Returns the aggregate pool generic storage.

#### Return Values

| Name           | Type                                      | Description                           |
| -------------- | ----------------------------------------- | ------------------------------------- |
| poolInitParams | struct IRigoblockV3PoolState.ReturnedPool | The pool's initialization parameters. |
| poolVariables  | struct IRigoblockV3PoolState.PoolParams   | The pool's variables.                 |
| poolTokensInfo | struct IRigoblockV3PoolState.PoolTokens   | The pool's tokens info.               |

### getUserAccount

```solidity
function getUserAccount(address who) external view returns (struct IRigoblockV3PoolState.UserAccount)
```

### owner

```solidity
function owner() external view returns (address)
```

Returns the address of the owner.

#### Return Values

| Name | Type    | Description           |
| ---- | ------- | --------------------- |
| \[0] | address | Address of the owner. |

### decimals

```solidity
function decimals() public view returns (uint8)
```

Decimals are initialized at proxy creation.

#### Return Values

| Name | Type  | Description         |
| ---- | ----- | ------------------- |
| \[0] | uint8 | Number of decimals. |

### getPool

```solidity
function getPool() public view returns (struct IRigoblockV3PoolState.ReturnedPool)
```

Returns the struct containing pool initialization parameters.

*Symbol is stored as bytes8 but returned as string in the returned struct, unlocked is omitted as alwasy true.*

#### Return Values

| Name | Type                                      | Description          |
| ---- | ----------------------------------------- | -------------------- |
| \[0] | struct IRigoblockV3PoolState.ReturnedPool | ReturnedPool struct. |

### getPoolParams

```solidity
function getPoolParams() public view returns (struct IRigoblockV3PoolState.PoolParams)
```

Returns the struct compaining pool parameters.

#### Return Values

| Name | Type                                    | Description        |
| ---- | --------------------------------------- | ------------------ |
| \[0] | struct IRigoblockV3PoolState.PoolParams | PoolParams struct. |

### getPoolTokens

```solidity
function getPoolTokens() public view returns (struct IRigoblockV3PoolState.PoolTokens)
```

Returns the struct containing pool tokens info.

#### Return Values

| Name | Type                                    | Description        |
| ---- | --------------------------------------- | ------------------ |
| \[0] | struct IRigoblockV3PoolState.PoolTokens | PoolTokens struct. |

### name

```solidity
function name() public view returns (string)
```

Returns a string of the pool name.

*Name maximum length 31 bytes.*

#### Return Values

| Name | Type   | Description         |
| ---- | ------ | ------------------- |
| \[0] | string | String of the name. |

### symbol

```solidity
function symbol() public view returns (string)
```

Returns a string of the pool symbol.

#### Return Values

| Name | Type   | Description           |
| ---- | ------ | --------------------- |
| \[0] | string | String of the symbol. |

### totalSupply

```solidity
function totalSupply() public view returns (uint256)
```

### \_getFeeCollector

```solidity
function _getFeeCollector() internal view returns (address)
```

### \_getMinPeriod

```solidity
function _getMinPeriod() internal view returns (uint48)
```

### \_getSpread

```solidity
function _getSpread() internal view returns (uint16)
```

### \_getUnitaryValue

```solidity
function _getUnitaryValue() internal view returns (uint256)
```


# storage accessible

## MixinStorageAccessible

See <https://github.com/gnosis/util-contracts/blob/bb5fe5fb5df6d8400998094fb1b32a178a47c3a1/contracts/StorageAccessible.sol>

### getStorageAt

```solidity
function getStorageAt(uint256 offset, uint256 length) public view returns (bytes)
```

Reads `length` bytes of storage in the currents contract.

#### Parameters

| Name   | Type    | Description                                                                    |
| ------ | ------- | ------------------------------------------------------------------------------ |
| offset | uint256 | - the offset in the current contract's storage in words to start reading from. |
| length | uint256 | - the number of words (32 bytes) of data to read.                              |

#### Return Values

| Name | Type  | Description                               |
| ---- | ----- | ----------------------------------------- |
| \[0] | bytes | Bytes string of the bytes that were read. |

### getStorageSlotsAt

```solidity
function getStorageSlotsAt(uint256[] slots) public view returns (bytes)
```

Reads bytes of storage at different storage locations.

*Returns a string with values regarless of where they are stored, i.e. variable, mapping or struct.*

#### Parameters

| Name  | Type       | Description                               |
| ----- | ---------- | ----------------------------------------- |
| slots | uint256\[] | The array of storage slots to query into. |

#### Return Values

| Name | Type  | Description                                                   |
| ---- | ----- | ------------------------------------------------------------- |
| \[0] | bytes | Bytes string composite of different storage locations' value. |


# Deps

Contracts that add base functionality to the protocol

* Authority --> contains all protocol permissions, it is owned by the Rigoblock governance and stores the approved factories, adapters, whitelisted methods on adapters and the wallets that have whitelister role.
* PoolRegistry --> stores the mapping of a pool proxy address to its assigned ID, which is the hash of the name and the owner, making it unique for a said name and pool operator. A pool's name is not stored in the registry and can be used multiple times (but with different pool owners) in order to prevent a race condition which would make it not 100% certain that they could deploy the same pool to multiple chains. The pool registry is used by applications like the Rigoblock Staking system for querying a pool's unique ID. A pool owner can set metamadata for its pool.
* KYC --> a mock module, since a canonical KYC module is not provided and the pool operator is responsible, if decides to opt-in for whitelisting its pool proxy users, to implementing/selecting the KYC module of his choice, potentially restricting who can mint his operated pool's tokens or the maximum mintable amount.


# Authority

<figure><img src="/files/8P6E7SjYnMSaaBEyUGW7" alt=""><figcaption><p>Credits: UML diagram generated with <a href="https://github.com/naddison36/sol2uml">SOL2UML</a></p></figcaption></figure>


# authority docs

## Authority

### \_adapterBySelector

```solidity
mapping(bytes4 => address) _adapterBySelector
```

### \_permission

```solidity
mapping(address => struct IAuthority.Permission) _permission
```

### \_roleToList

```solidity
mapping(enum IAuthority.Role => address[]) _roleToList
```

### onlyWhitelister

```solidity
modifier onlyWhitelister()
```

### constructor

```solidity
constructor(address newOwner) public
```

### addMethod

```solidity
function addMethod(bytes4 selector, address adapter) external
```

Allows a whitelister to whitelist a method. We do not save list of approved as better queried by events.

#### Parameters

| Name     | Type    | Description                                     |
| -------- | ------- | ----------------------------------------------- |
| selector | bytes4  | Bytes4 hex of the method selector.              |
| adapter  | address | Address of the adapter implementing the method. |

### removeMethod

```solidity
function removeMethod(bytes4 selector, address adapter) external
```

Allows a whitelister to remove a method.

#### Parameters

| Name     | Type    | Description                                     |
| -------- | ------- | ----------------------------------------------- |
| selector | bytes4  | Bytes4 hex of the method selector.              |
| adapter  | address | Address of the adapter implementing the method. |

### setWhitelister

```solidity
function setWhitelister(address whitelister, bool isWhitelisted) external
```

Allows the owner to set whitelister permission. Whitelister permission is required to approve methods in extensions adapter.

#### Parameters

| Name          | Type    | Description                 |
| ------------- | ------- | --------------------------- |
| whitelister   | address | Address of the whitelister. |
| isWhitelisted | bool    | Bool whitelisted.           |

### setAdapter

```solidity
function setAdapter(address adapter, bool isWhitelisted) external
```

Allows owner to set extension adapter address.

#### Parameters

| Name          | Type    | Description                    |
| ------------- | ------- | ------------------------------ |
| adapter       | address | Address of the target adapter. |
| isWhitelisted | bool    | Bool whitelisted.              |

### setFactory

```solidity
function setFactory(address factory, bool isWhitelisted) external
```

Allows an admin to set factory permission.

#### Parameters

| Name          | Type    | Description                    |
| ------------- | ------- | ------------------------------ |
| factory       | address | Address of the target factory. |
| isWhitelisted | bool    | Bool whitelisted.              |

### isWhitelistedFactory

```solidity
function isWhitelistedFactory(address target) external view returns (bool)
```

Provides whether a factory is whitelisted.

#### Parameters

| Name   | Type    | Description                    |
| ------ | ------- | ------------------------------ |
| target | address | Address of the target factory. |

#### Return Values

| Name | Type | Description          |
| ---- | ---- | -------------------- |
| \[0] | bool | Bool is whitelisted. |

### getApplicationAdapter

```solidity
function getApplicationAdapter(bytes4 selector) external view returns (address)
```

Returns the address of the adapter associated to the signature.

#### Parameters

| Name     | Type   | Description                  |
| -------- | ------ | ---------------------------- |
| selector | bytes4 | Hex of the method signature. |

#### Return Values

| Name | Type    | Description             |
| ---- | ------- | ----------------------- |
| \[0] | address | Address of the adapter. |

### isWhitelister

```solidity
function isWhitelister(address target) public view returns (bool)
```

Provides whether an address is whitelister.

#### Parameters

| Name   | Type    | Description                        |
| ------ | ------- | ---------------------------------- |
| target | address | Address of the target whitelister. |

#### Return Values

| Name | Type | Description          |
| ---- | ---- | -------------------- |
| \[0] | bool | Bool is whitelisted. |

### \_changePermission

```solidity
function _changePermission(address target, bool isWhitelisted, enum IAuthority.Role role) private
```


# PoolRegistry

The pool registry stores a mapping of pool address to pool ID. Furthermore, runs a sanity checks on the name and symbol string.

<figure><img src="/files/r4SjgrEQNb6kCCfIVSXb" alt=""><figcaption><p>Credits: UML diagram generated with <a href="https://github.com/naddison36/sol2uml">SOL2UML</a></p></figcaption></figure>


# pool registry docs

## PoolRegistry

### authority

```solidity
address authority
```

Returns the address of the Rigoblock authority contract.

#### Return Values

### rigoblockDao

```solidity
address rigoblockDao
```

Returns the address of the Rigoblock Dao.

#### Return Values

### \_mapIdByAddress

```solidity
mapping(address => bytes32) _mapIdByAddress
```

### \_poolMetaByAddress

```solidity
mapping(address => struct IPoolRegistry.PoolMeta) _poolMetaByAddress
```

### onlyWhitelistedFactory

```solidity
modifier onlyWhitelistedFactory()
```

### onlyPoolOperator

```solidity
modifier onlyPoolOperator(address pool)
```

### onlyRigoblockDao

```solidity
modifier onlyRigoblockDao()
```

### whenAddressFree

```solidity
modifier whenAddressFree(address pool)
```

### whenPoolRegistered

```solidity
modifier whenPoolRegistered(address pool)
```

### constructor

```solidity
constructor(address newAuthority, address newRigoblockDao) public
```

### register

```solidity
function register(address pool, string name, string symbol, bytes32 poolId) external
```

Allows a factory which is an authority to register a pool.

#### Parameters

| Name   | Type    | Description                                            |
| ------ | ------- | ------------------------------------------------------ |
| pool   | address | Address of the pool.                                   |
| name   | string  | String name of the pool (31 characters/bytes or less). |
| symbol | string  | String symbol of the pool (3 to 5 characters/bytes).   |
| poolId | bytes32 | Bytes32 of the pool id.                                |

### setAuthority

```solidity
function setAuthority(address newAuthority) external
```

Allows Rigoblock governance to update authority.

#### Parameters

| Name         | Type    | Description |
| ------------ | ------- | ----------- |
| newAuthority | address |             |

### setMeta

```solidity
function setMeta(address pool, bytes32 key, bytes32 value) external
```

Allows pool owner to set metadata for a pool.

#### Parameters

| Name  | Type    | Description           |
| ----- | ------- | --------------------- |
| pool  | address | Address of the pool.  |
| key   | bytes32 | Bytes32 of the key.   |
| value | bytes32 | Bytes32 of the value. |

### setRigoblockDao

```solidity
function setRigoblockDao(address newRigoblockDao) external
```

Allows Rigoblock Dao to update its address.

*Creates internal record.*

#### Parameters

| Name            | Type    | Description                   |
| --------------- | ------- | ----------------------------- |
| newRigoblockDao | address | Address of the Rigoblock Dao. |

### getPoolIdFromAddress

```solidity
function getPoolIdFromAddress(address pool) external view returns (bytes32 poolId)
```

Returns the id of a pool from its address.

#### Parameters

| Name | Type    | Description          |
| ---- | ------- | -------------------- |
| pool | address | Address of the pool. |

#### Return Values

| Name   | Type    | Description             |
| ------ | ------- | ----------------------- |
| poolId | bytes32 | bytes32 id of the pool. |

### getMeta

```solidity
function getMeta(address pool, bytes32 key) external view returns (bytes32 poolMeta)
```

Returns metadata for a given pool.

#### Parameters

| Name | Type    | Description          |
| ---- | ------- | -------------------- |
| pool | address | Address of the pool. |
| key  | bytes32 | Bytes32 key.         |

#### Return Values

| Name     | Type    | Description  |
| -------- | ------- | ------------ |
| poolMeta | bytes32 | Meta by key. |

### \_assertValidNameAndSymbol

```solidity
function _assertValidNameAndSymbol(string name, string symbol) internal pure
```

### \_isContract

```solidity
function _isContract(address target) private view returns (bool)
```


# Extensions

Methods not implemented in the core can be added as an extension without requiring a governance implementation upgrade. This is relevant for bridges with external applications

* EWhitelist --> extension which stores the whitelisted tokens, uses Rigoblock Authority permissions. It also allows the whitelisting and blacklisting of different tokens in batches.
* EUpgrade --> extension to upgrading the pool implementation, returns the current implementation. It also returns the address of the beacon, which stored the address of the latest implementation.
* AUniswap --> bridge to the uniswap V3 and V2 protocols, allows pools to swap tokens on both V3 and V2 and potentially split swaps between the two protocols if optimal. Allows the pool to farm liquidity rewards on Uniswap V3 pools.
* AStaking --> allows the pool operator to stake GRG tokens to its own Rigoblock staking pool in 1 single call. Creates the staking pool if doesn't exist, stakes to the staking system and delegates the stake to itself.
* AMulticall --> allows to send multiple transactions to the pool at once.
* ASelfCustody (deprecated in v4) --> an extension that allows a pool operator to transfer tokens from the pool to external wallet, i.e. cold storage. Designed for professional market makers, requires a minimum holding of 100K GRG tokens.


# AGovernance

Rigoblock pools can interact with the Rigoblock governance. In particular, they can:

* make a proposal
* vote on an active proposal
* execute a successful proposal

In the future, this adapter might be upgraded through governance voting to support a broader number of governance projects.

<figure><img src="/files/X8H6cYkdVVXAKCuQfPFR" alt=""><figcaption><p>Credits: UML diagram generated with <a href="https://github.com/naddison36/sol2uml">SOL2UML</a></p></figcaption></figure>


# Solidity API

## AGovernance

### \_governance

```solidity
address _governance
```

### constructor

```solidity
constructor(address governance) public
```

### propose

```solidity
function propose(struct IGovernanceVoting.ProposedAction[] actions, string description) external
```

Allows to make a proposal to the Rigoblock governance.

#### Parameters

| Name        | Type                                       | Description                          |
| ----------- | ------------------------------------------ | ------------------------------------ |
| actions     | struct IGovernanceVoting.ProposedAction\[] | Array of tuples of proposed actions. |
| description | string                                     | A human-readable description.        |

### castVote

```solidity
function castVote(uint256 proposalId, enum IGovernanceVoting.VoteType voteType) external
```

Allows a pool to vote on a proposal.

#### Parameters

| Name       | Type                            | Description             |
| ---------- | ------------------------------- | ----------------------- |
| proposalId | uint256                         | Number of the proposal. |
| voteType   | enum IGovernanceVoting.VoteType | Enum of the vote type.  |

### execute

```solidity
function execute(uint256 proposalId) external
```

Allows a pool to execute a proposal.

#### Parameters

| Name       | Type    | Description             |
| ---------- | ------- | ----------------------- |
| proposalId | uint256 | Number of the proposal. |

### \_getGovernance

```solidity
function _getGovernance() private view returns (address)
```


# AMulticall

Batches of transactions sent in multicall format are forwarded to the proxy and executed individually, requiring individual methods' sanity checks to be successful before the call can be executed.

<figure><img src="/files/i2g2s6JGozF0HJa1KfLY" alt=""><figcaption><p>Credits: UML diagram generated with <a href="https://github.com/naddison36/sol2uml">SOL2UML</a></p></figcaption></figure>


# aMulticall docs

## AMulticall

As per <https://github.com/Uniswap/swap-router-contracts/blob/main/contracts/base/MulticallExtended.sol>

### checkDeadline

```solidity
modifier checkDeadline(uint256 deadline)
```

### checkPreviousBlockhash

```solidity
modifier checkPreviousBlockhash(bytes32 previousBlockhash)
```

### multicall

```solidity
function multicall(bytes[] data) public returns (bytes[] results)
```

Enables calling multiple methods in a single call to the contract

#### Parameters

| Name | Type     | Description             |
| ---- | -------- | ----------------------- |
| data | bytes\[] | Array of encoded calls. |

#### Return Values

| Name    | Type     | Description              |
| ------- | -------- | ------------------------ |
| results | bytes\[] | Array of call responses. |

### multicall

```solidity
function multicall(uint256 deadline, bytes[] data) external payable returns (bytes[])
```

Call multiple functions in the current contract and return the data from all of them if they all succeed

*The `msg.value` should not be trusted for any method callable from multicall.*

#### Parameters

| Name     | Type     | Description                                                              |
| -------- | -------- | ------------------------------------------------------------------------ |
| deadline | uint256  | The time by which this function must be called before failing            |
| data     | bytes\[] | The encoded function data for each of the calls to make to this contract |

#### Return Values

| Name | Type     | Description |
| ---- | -------- | ----------- |
| \[0] | bytes\[] |             |

### multicall

```solidity
function multicall(bytes32 previousBlockhash, bytes[] data) external payable returns (bytes[])
```

Call multiple functions in the current contract and return the data from all of them if they all succeed

*The `msg.value` should not be trusted for any method callable from multicall.*

#### Parameters

| Name              | Type     | Description                                                              |
| ----------------- | -------- | ------------------------------------------------------------------------ |
| previousBlockhash | bytes32  | The expected parent blockHash                                            |
| data              | bytes\[] | The encoded function data for each of the calls to make to this contract |

#### Return Values

| Name | Type     | Description |
| ---- | -------- | ----------- |
| \[0] | bytes\[] |             |

### \_blockTimestamp

```solidity
function _blockTimestamp() internal view virtual returns (uint256)
```

*Method that exists purely to be overridden for tests*

#### Return Values

| Name | Type    | Description                 |
| ---- | ------- | --------------------------- |
| \[0] | uint256 | The current block timestamp |


# AStaking

GRG staking is simplified for the pool operators by enabling the creation, staking and activating stake in 1 single call without having to worry about correctly formatting inputs.

<figure><img src="/files/bf9ZSbQuJlhLLDYATdPL" alt=""><figcaption><p>Credits: UML diagram generated with <a href="https://github.com/naddison36/sol2uml">SOL2UML</a></p></figcaption></figure>


# aStaking docs

## AStaking

### \_stakingProxy

```solidity
address _stakingProxy
```

### \_grgToken

```solidity
address _grgToken
```

### \_grgTransferProxy

```solidity
address _grgTransferProxy
```

### constructor

```solidity
constructor(address stakingProxy, address grgToken, address grgTransferProxy) public
```

### stake

```solidity
function stake(uint256 amount) external
```

Stakes an amount of GRG to own staking pool. Creates staking pool if doesn't exist.

*Creating staking pool if doesn't exist effectively locks direct call.*

#### Parameters

| Name   | Type    | Description             |
| ------ | ------- | ----------------------- |
| amount | uint256 | Amount of GRG to stake. |

### undelegateStake

```solidity
function undelegateStake(uint256 amount) external
```

Undelegates stake for the pool.

#### Parameters

| Name   | Type    | Description                          |
| ------ | ------- | ------------------------------------ |
| amount | uint256 | Number of GRG units with undelegate. |

### unstake

```solidity
function unstake(uint256 amount) external
```

Unstakes staked undelegated tokens for the pool.

#### Parameters

| Name   | Type    | Description                     |
| ------ | ------- | ------------------------------- |
| amount | uint256 | Number of GRG units to unstake. |

### withdrawDelegatorRewards

```solidity
function withdrawDelegatorRewards() external
```

Withdraws delegator rewards of the pool.

### \_getGrgToken

```solidity
function _getGrgToken() private view returns (address)
```

### \_getGrgTransferProxy

```solidity
function _getGrgTransferProxy() private view returns (address)
```

### \_getStakingProxy

```solidity
function _getStakingProxy() private view returns (address)
```


# AUniswap

Transactions to Uniswap are handled by a custom adapter, which makes some sanity checks and then sends a swap/mint/burn op to the Uniswap V2 router, which includes methods for Uniswap V3, V2, NPM.

Being RigoBlock oracle-agnostic, slippage protection against a market's best price cannot be offered at a protocol level at the moment. A pool operator can set slippage protection parameters which will be enforced on-chain at runtime, however, nothing prevents a pool operator from sending a rogue transaction to his operated pool. A possible attack involves the smart contract pool operator using the pool's tokens to move a whitelisted token price on a just created illiquid pair, at the same borrowing the same token from the owner smart contract, selling the token on the same pair, and returning the borrowed tokens for a profit. In the same way, a pool operator may send token swap transactions by selecting a pair where the pool operator is the only liquidity provider, therefore charging the pool unnecessary swap fees. This is a known limitation of the RigoBlock protocol and possible improvements are being researched. It is therefore not advisable to mint tokens of anonymous pools and pools that do not have clear Terms\&Conditions they abide by.

<figure><img src="/files/ACDItQIdcyumN0pEDxmV" alt=""><figcaption><p>Credits: UML diagram generated with <a href="https://github.com/naddison36/sol2uml">SOL2UML</a></p></figcaption></figure>


# aUniswap docs

## AUniswap

### uniswapRouter02

```solidity
address uniswapRouter02
```

Returns the address of the Uniswap swap router contract.

#### Return Values

### uniswapv3Npm

```solidity
address uniswapv3Npm
```

Returns the address of the Uniswap NPM contract.

#### Return Values

### weth

```solidity
address weth
```

Returns the address of the Weth contract.

#### Return Values

### constructor

```solidity
constructor(address newUniswapRouter02) public
```

### swapExactTokensForTokens

```solidity
function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to) external returns (uint256 amountOut)
```

Swaps `amountIn` of one token for as much as possible of another token.

*Setting `amountIn` to 0 will cause the contract to look up its own balance, and swap the entire amount, enabling contracts to send tokens before calling this function.*

#### Parameters

| Name         | Type       | Description                                         |
| ------------ | ---------- | --------------------------------------------------- |
| amountIn     | uint256    | The amount of token to swap.                        |
| amountOutMin | uint256    | The minimum amount of output that must be received. |
| path         | address\[] | The ordered list of tokens to swap through.         |
| to           | address    | The recipient address.                              |

#### Return Values

| Name      | Type    | Description                       |
| --------- | ------- | --------------------------------- |
| amountOut | uint256 | The amount of the received token. |

### swapTokensForExactTokens

```solidity
function swapTokensForExactTokens(uint256 amountOut, uint256 amountInMax, address[] path, address to) external returns (uint256 amountIn)
```

Swaps as little as possible of one token for an exact amount of another token.

#### Parameters

| Name        | Type       | Description                                           |
| ----------- | ---------- | ----------------------------------------------------- |
| amountOut   | uint256    | The amount of token to swap for.                      |
| amountInMax | uint256    | The maximum amount of input that the caller will pay. |
| path        | address\[] | The ordered list of tokens to swap through.           |
| to          | address    | The recipient address.                                |

#### Return Values

| Name     | Type    | Description                 |
| -------- | ------- | --------------------------- |
| amountIn | uint256 | The amount of token to pay. |

### exactInputSingle

```solidity
function exactInputSingle(struct IV3SwapRouter.ExactInputSingleParams params) external returns (uint256 amountOut)
```

Swaps `amountIn` of one token for as much as possible of another token.

#### Parameters

| Name   | Type                                        | Description                                                                           |
| ------ | ------------------------------------------- | ------------------------------------------------------------------------------------- |
| params | struct IV3SwapRouter.ExactInputSingleParams | The parameters necessary for the swap, encoded as `ExactInputSingleParams` in memory. |

#### Return Values

| Name      | Type    | Description                       |
| --------- | ------- | --------------------------------- |
| amountOut | uint256 | The amount of the received token. |

### exactInput

```solidity
function exactInput(struct IV3SwapRouter.ExactInputParams params) external returns (uint256 amountOut)
```

Swaps `amountIn` of one token for as much as possible of another along the specified path.

#### Parameters

| Name   | Type                                  | Description                                                                               |
| ------ | ------------------------------------- | ----------------------------------------------------------------------------------------- |
| params | struct IV3SwapRouter.ExactInputParams | The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in memory. |

#### Return Values

| Name      | Type    | Description                       |
| --------- | ------- | --------------------------------- |
| amountOut | uint256 | The amount of the received token. |

### exactOutputSingle

```solidity
function exactOutputSingle(struct IV3SwapRouter.ExactOutputSingleParams params) external returns (uint256 amountIn)
```

Swaps as little as possible of one token for `amountOut` of another token.

#### Parameters

| Name   | Type                                         | Description                                                                            |
| ------ | -------------------------------------------- | -------------------------------------------------------------------------------------- |
| params | struct IV3SwapRouter.ExactOutputSingleParams | The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in memory. |

#### Return Values

| Name     | Type    | Description                    |
| -------- | ------- | ------------------------------ |
| amountIn | uint256 | The amount of the input token. |

### exactOutput

```solidity
function exactOutput(struct IV3SwapRouter.ExactOutputParams params) external returns (uint256 amountIn)
```

Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed).

#### Parameters

| Name   | Type                                   | Description                                                                                |
| ------ | -------------------------------------- | ------------------------------------------------------------------------------------------ |
| params | struct IV3SwapRouter.ExactOutputParams | The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in memory. |

#### Return Values

| Name     | Type    | Description                    |
| -------- | ------- | ------------------------------ |
| amountIn | uint256 | The amount of the input token. |

### sweepToken

```solidity
function sweepToken(address token, uint256 amountMinimum) external
```

Transfers the full amount of a token held by this contract to recipient.

*The amountMinimum parameter prevents malicious contracts from stealing the token from users.*

#### Parameters

| Name          | Type    | Description                                                                 |
| ------------- | ------- | --------------------------------------------------------------------------- |
| token         | address | The contract address of the token which will be transferred to `recipient`. |
| amountMinimum | uint256 | The minimum amount of token required for a transfer.                        |

### sweepToken

```solidity
function sweepToken(address token, uint256 amountMinimum, address recipient) external
```

Transfers the full amount of a token held by this contract to recipient.

*The amountMinimum parameter prevents malicious contracts from stealing the token from users.*

#### Parameters

| Name          | Type    | Description                                                                 |
| ------------- | ------- | --------------------------------------------------------------------------- |
| token         | address | The contract address of the token which will be transferred to `recipient`. |
| amountMinimum | uint256 | The minimum amount of token required for a transfer.                        |
| recipient     | address | The destination address of the token.                                       |

### sweepTokenWithFee

```solidity
function sweepTokenWithFee(address token, uint256 amountMinimum, uint256 feeBips, address feeRecipient) external
```

Transfers the full amount of a token held by this contract to recipient, with a percentage between 0 (exclusive) and 1 (inclusive) going to feeRecipient.

*The amountMinimum parameter prevents malicious contracts from stealing the token from users.*

#### Parameters

| Name          | Type    | Description                                                                 |
| ------------- | ------- | --------------------------------------------------------------------------- |
| token         | address | The contract address of the token which will be transferred to `recipient`. |
| amountMinimum | uint256 | The minimum amount of token required for a transfer.                        |
| feeBips       | uint256 | The amount of fee in basis points.                                          |
| feeRecipient  | address | The destination address of the token.                                       |

### sweepTokenWithFee

```solidity
function sweepTokenWithFee(address token, uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient) external
```

Transfers the full amount of a token held by this contract to recipient, with a percentage between 0 (exclusive) and 1 (inclusive) going to feeRecipient.

*The amountMinimum parameter prevents malicious contracts from stealing the token from users.*

#### Parameters

| Name          | Type    | Description                                                                 |
| ------------- | ------- | --------------------------------------------------------------------------- |
| token         | address | The contract address of the token which will be transferred to `recipient`. |
| amountMinimum | uint256 | The minimum amount of token required for a transfer.                        |
| recipient     | address | The destination address of the token.                                       |
| feeBips       | uint256 | The amount of fee in basis points.                                          |
| feeRecipient  | address | The destination address of the token.                                       |

### unwrapWETH9

```solidity
function unwrapWETH9(uint256 amountMinimum) external
```

Unwraps the contract's WETH9 balance and sends it to recipient as ETH.

*The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.*

#### Parameters

| Name          | Type    | Description                            |
| ------------- | ------- | -------------------------------------- |
| amountMinimum | uint256 | The minimum amount of WETH9 to unwrap. |

### unwrapWETH9

```solidity
function unwrapWETH9(uint256 amountMinimum, address recipient) external
```

Unwraps ETH from WETH9.

#### Parameters

| Name          | Type    | Description                                    |
| ------------- | ------- | ---------------------------------------------- |
| amountMinimum | uint256 | The minimum amount of WETH9 to unwrap.         |
| recipient     | address | The address to keep same uniswap npm selector. |

### unwrapWETH9WithFee

```solidity
function unwrapWETH9WithFee(uint256 amountMinimum, uint256 feeBips, address feeRecipient) external virtual
```

Unwraps the contract's WETH9 balance and sends it to recipient as ETH, with a percentage between 0 (exclusive), and 1 (inclusive) going to feeRecipient.

*The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.*

#### Parameters

| Name          | Type    | Description                                          |
| ------------- | ------- | ---------------------------------------------------- |
| amountMinimum | uint256 | The minimum amount of token required for a transfer. |
| feeBips       | uint256 | The amount of fee in basis points.                   |
| feeRecipient  | address | The destination address of the token.                |

### unwrapWETH9WithFee

```solidity
function unwrapWETH9WithFee(uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient) external virtual
```

Unwraps the contract's WETH9 balance and sends it to recipient as ETH, with a percentage between 0 (exclusive), and 1 (inclusive) going to feeRecipient.

*The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.*

#### Parameters

| Name          | Type    | Description                                          |
| ------------- | ------- | ---------------------------------------------------- |
| amountMinimum | uint256 | The minimum amount of token required for a transfer. |
| recipient     | address | The destination address of the token.                |
| feeBips       | uint256 | The amount of fee in basis points.                   |
| feeRecipient  | address | The destination address of the token.                |

### wrapETH

```solidity
function wrapETH(uint256 value) external
```

Wraps ETH.

*Client must wrap if input is native currency.*

#### Parameters

| Name  | Type    | Description                   |
| ----- | ------- | ----------------------------- |
| value | uint256 | The ETH amount to be wrapped. |

### refundETH

```solidity
function refundETH() external virtual
```

Allows sending pool transactions exactly as Uniswap original transactions.

*Declared virtual as we never send ETH to Uniswap router contract.*

### \_safeApprove

```solidity
function _safeApprove(address token, address spender, uint256 value) internal
```

### \_assertTokenWhitelisted

```solidity
function _assertTokenWhitelisted(address token) internal view
```

### \_getUniswapNpm

```solidity
function _getUniswapNpm() internal view returns (address)
```

### \_isContract

```solidity
function _isContract(address target) internal view returns (bool)
```

### \_getUniswapRouter2

```solidity
function _getUniswapRouter2() private view returns (address)
```

### \_getWeth

```solidity
function _getWeth() private view returns (address)
```


# EUpgrade

An upgrade is executed by the pool operator calling the upgrade method. The upgraded implementation address is returned by the beacon, which address is stored in the EUpgrade contract bytecode as deployment immutable. The proxy factory is used as the beacon, allowing for potentially different factories using different implementations.

<figure><img src="/files/GePhEwVAIPezIFACVqGs" alt=""><figcaption><p>Credits: UML diagram generated with <a href="https://github.com/naddison36/sol2uml">SOL2UML</a></p></figcaption></figure>


# eUpgrade docs

## EUpgrade

### \_eUpgrade

```solidity
address _eUpgrade
```

### \_factory

```solidity
address _factory
```

### constructor

```solidity
constructor(address factory) public
```

### upgradeImplementation

```solidity
function upgradeImplementation() external
```

Allows caller to upgrade pool implementation.

*Cannot be called directly and in pool is restricted to pool owner.*

### getBeacon

```solidity
function getBeacon() public view returns (address)
```


# EWhitelist

A token whitelist is used to prevent pool operator abuse by operating with rogue tokens, EOAs as a transaction's target. While this makes a DeFi transaction slightly more expensive in terms of gas, it provides security benefits to the pool holders.

As a rule of thumb, any token that has a decent reputation will be whitelisted.

<figure><img src="/files/g8MEAd8opNdnHfVQWz3W" alt=""><figcaption><p>Credits: UML diagram generated with <a href="https://github.com/naddison36/sol2uml">SOL2UML</a></p></figcaption></figure>


# eWhitelist docs

## EWhitelist

This contract has its own storage, which could potentially clash with pool storage if the allocated slot were already used by the implementation. Warning: careful with upgrades as pool only accesses isWhitelistedToken view method. Other methods are locked and should never be approved by governance.

### \_EWHITELIST\_TOKEN\_WHITELIST\_SLOT

```solidity
bytes32 _EWHITELIST_TOKEN_WHITELIST_SLOT
```

### authority

```solidity
address authority
```

### WhitelistSlot

```solidity
struct WhitelistSlot {
  mapping(address => bool) isWhitelisted;
}
```

### onlyAuthorized

```solidity
modifier onlyAuthorized()
```

### constructor

```solidity
constructor(address newAuthority) public
```

### whitelistToken

```solidity
function whitelistToken(address token) public
```

Allows a whitelister to whitelist a token.

#### Parameters

| Name  | Type    | Description                  |
| ----- | ------- | ---------------------------- |
| token | address | Address of the target token. |

### removeToken

```solidity
function removeToken(address token) public
```

Allows a whitelister to remove a token.

#### Parameters

| Name  | Type    | Description                  |
| ----- | ------- | ---------------------------- |
| token | address | Address of the target token. |

### batchUpdateTokens

```solidity
function batchUpdateTokens(address[] tokens, bool[] whitelisted) external
```

Allows a whitelister to whitelist/remove a list of tokens.

#### Parameters

| Name        | Type       | Description                                              |
| ----------- | ---------- | -------------------------------------------------------- |
| tokens      | address\[] | Address array to tokens.                                 |
| whitelisted | bool\[]    | Bollean array the token is to be whitelisted or removed. |

### isWhitelistedToken

```solidity
function isWhitelistedToken(address token) external view returns (bool)
```

Returns whether a token has been whitelisted.

#### Parameters

| Name  | Type    | Description                  |
| ----- | ------- | ---------------------------- |
| token | address | Address of the target token. |

#### Return Values

| Name | Type | Description                       |
| ---- | ---- | --------------------------------- |
| \[0] | bool | Boolean the token is whitelisted. |

### getAuthority

```solidity
function getAuthority() public view returns (address)
```

Returns the address of the authority contract.

#### Return Values

| Name | Type    | Description                        |
| ---- | ------- | ---------------------------------- |
| \[0] | address | Address of the authority contract. |

### \_getWhitelistSlot

```solidity
function _getWhitelistSlot() internal pure returns (struct EWhitelist.WhitelistSlot s)
```

### \_assertCallerIsAuthorized

```solidity
function _assertCallerIsAuthorized() private view
```

### \_isContract

```solidity
function _isContract(address target) private view returns (bool)
```


# Proxies

Each Rigoblock pool proxy is deployed by the proxy factory, which also serves as a beacon for pool implementation upgrades

* proxy --> the contract which delegates calls to the implementation
* proxy factory --> the proxy deployer contract. Produces a unique pool ID, which is stored in a mapping in the registry. A user inputs a name of maximum 31 characters and a symbol between 3 and 5 characters and a base tokens, the factory deploys the proxy, updates its initialization storage values and registers the pool at the pool registry. Limiting the name length to 31 bytes is required for storing a name in its deterministic slot. A name longer than that, in fact, would be stored in a different storage slot (the assigned storage slot would only store the string length).


# proxy

RigoBlock proxies are ultra-light contracts developed according EIP1967 that only declare \_IMPLEMENTATION\_SLOT in their storage, where the implementation address is stored. At contract creation, the initialization storage slots are written to the proxy storage at a deterministic slot which, by design, will never accidentally clash with other variables.

<figure><img src="/files/iAaus2SBgAgcmqeNbZes" alt=""><figcaption><p>Credits: UML diagram generated with <a href="https://github.com/naddison36/sol2uml">SOL2UML</a></p></figcaption></figure>


# proxy docs

## RigoblockPoolProxy

### \_IMPLEMENTATION\_SLOT

```solidity
bytes32 _IMPLEMENTATION_SLOT
```

### constructor

```solidity
constructor() public payable
```

Sets address of implementation contract.

### fallback

```solidity
fallback() external payable
```

Fallback function forwards all transactions and returns all received return data.

### ImplementationSlot

```solidity
struct ImplementationSlot {
  address implementation;
}
```

### getImplementation

```solidity
function getImplementation() private pure returns (struct RigoblockPoolProxy.ImplementationSlot s)
```

Method to read/write from/to implementation slot.

#### Return Values

| Name | Type                                         | Description                              |
| ---- | -------------------------------------------- | ---------------------------------------- |
| s    | struct RigoblockPoolProxy.ImplementationSlot | Storage slot of the pool implementation. |


# proxy factory

<figure><img src="/files/Q5JjnFJgrXKSrzVkzldh" alt=""><figcaption><p>Credits: UML diagram generated with <a href="https://github.com/naddison36/sol2uml">SOL2UML</a></p></figcaption></figure>


# proxyFactory docs

## RigoblockPoolProxyFactory

### implementation

```solidity
address implementation
```

Returns the implementation address for the pool proxies.

#### Return Values

### \_registry

```solidity
address _registry
```

### \_parameters

```solidity
struct IRigoblockPoolProxyFactory.Parameters _parameters
```

### onlyRigoblockDao

```solidity
modifier onlyRigoblockDao()
```

### constructor

```solidity
constructor(address newImplementation, address registry) public
```

### createPool

```solidity
function createPool(string name, string symbol, address baseToken) external returns (address newPoolAddress, bytes32 poolId)
```

Creates a new Rigoblock pool.

#### Parameters

| Name      | Type    | Description                |
| --------- | ------- | -------------------------- |
| name      | string  | String of the name.        |
| symbol    | string  | String of the symbol.      |
| baseToken | address | Address of the base token. |

#### Return Values

| Name           | Type    | Description              |
| -------------- | ------- | ------------------------ |
| newPoolAddress | address | Address of the new pool. |
| poolId         | bytes32 | Id of the new pool.      |

### setImplementation

```solidity
function setImplementation(address newImplementation) external
```

Allows Rigoblock Dao to update factory pool implementation.

#### Parameters

| Name              | Type    | Description                                 |
| ----------------- | ------- | ------------------------------------------- |
| newImplementation | address | Address of the new implementation contract. |

### setRegistry

```solidity
function setRegistry(address newRegistry) external
```

Allows owner to update the registry.

#### Parameters

| Name        | Type    | Description                  |
| ----------- | ------- | ---------------------------- |
| newRegistry | address | Address of the new registry. |

### parameters

```solidity
function parameters() external view returns (struct IRigoblockPoolProxyFactory.Parameters)
```

Returns the pool initialization parameters at proxy deploy.

#### Return Values

| Name | Type                                         | Description                   |
| ---- | -------------------------------------------- | ----------------------------- |
| \[0] | struct IRigoblockPoolProxyFactory.Parameters | Tuple of the pool parameters. |

### getRegistry

```solidity
function getRegistry() public view returns (address)
```

Returns the address of the pool registry.

#### Return Values

| Name | Type    | Description              |
| ---- | ------- | ------------------------ |
| \[0] | address | Address of the registry. |

### \_createPool

```solidity
function _createPool(string name, string symbol, address baseToken) internal returns (bytes32 salt, contract RigoblockPoolProxy newProxy)
```

*Creates a pool and routes to eventful.*

#### Parameters

| Name      | Type    | Description                |
| --------- | ------- | -------------------------- |
| name      | string  | String of the name.        |
| symbol    | string  | String of the symbol.      |
| baseToken | address | Address of the base token. |

### \_isContract

```solidity
function _isContract(address target) private view returns (bool)
```

*Returns whether an address is a contract.*

#### Return Values

| Name | Type | Description                   |
| ---- | ---- | ----------------------------- |
| \[0] | bool | Bool target address has code. |


# GRG Token

The Rigo token is the utility token at the core of the Rigoblock incentives. A maximum of 2% of total supply p.a. is minted and distributed entirely to pools operators and GRG stakers

New tokens mint is autonomous, fully transparent and entirely distributed to network contributors according to their relative importance, as defined in the ProofOfPerformance module.

Proof of performance uses a pool's own staked and locked GRG as a proxy for its assets and performance.

GRG has been deployed on the Ethereum Mainnet and bridged to Optimism, Base, Unichain, Bnb Chain, Arbitrum and Polygon.


# RigoToken

<figure><img src="/files/jfe25NqNSe8XVi8O1Ag0" alt=""><figcaption><p>Credits: UML diagram generated with <a href="https://github.com/naddison36/sol2uml">SOL2UML</a></p></figcaption></figure>


# rigoToken docs

## RigoToken

UnlimitedAllowanceToken is ERC20

### name

```solidity
string name
```

### symbol

```solidity
string symbol
```

### decimals

```solidity
uint8 decimals
```

### minter

```solidity
address minter
```

Returns the address of the minter.

#### Return Values

### rigoblock

```solidity
address rigoblock
```

Returns the address of the Rigoblock Dao.

#### Return Values

### onlyMinter

```solidity
modifier onlyMinter()
```

### onlyRigoblock

```solidity
modifier onlyRigoblock()
```

### constructor

```solidity
constructor(address setMinter, address setRigoblock, address grgHolder) public
```

### mintToken

```solidity
function mintToken(address recipient, uint256 amount) external
```

Allows minter to create new tokens.

*Mint method is reserved for minter module.*

#### Parameters

| Name      | Type    | Description                       |
| --------- | ------- | --------------------------------- |
| recipient | address | Address receiving the new tokens. |
| amount    | uint256 | Number of minted tokens.          |

### changeMintingAddress

```solidity
function changeMintingAddress(address newAddress) external
```

Allows Rigoblock Dao to update minter.

#### Parameters

| Name       | Type    | Description                |
| ---------- | ------- | -------------------------- |
| newAddress | address | Address of the new minter. |

### changeRigoblockAddress

```solidity
function changeRigoblockAddress(address newAddress) external
```

Allows Rigoblock Dao to update its address.

#### Parameters

| Name       | Type    | Description             |
| ---------- | ------- | ----------------------- |
| newAddress | address | Address of the new Dao. |


# Inflation

The inflation module allows the staking proxy to mint a maximum of 2% p.a. of GRG supply during each epoch. The inflation module, after the initial setup, cannot be upgraded.

<figure><img src="/files/zvOZN6REIDmJ8YR3QIGZ" alt=""><figcaption><p>Credits: UML diagram generated with <a href="https://github.com/naddison36/sol2uml">SOL2UML</a></p></figcaption></figure>


# inflation docs

## Inflation

### rigoToken

```solidity
address rigoToken
```

Returns the address of the GRG token.

#### Return Values

### stakingProxy

```solidity
address stakingProxy
```

Returns the address of the GRG staking proxy.

#### Return Values

### epochLength

```solidity
uint48 epochLength
```

Returns the epoch length in seconds.

#### Return Values

### slot

```solidity
uint32 slot
```

Returns epoch slot.

*Increases by one every new epoch.*

#### Return Values

### \_ANNUAL\_INFLATION\_RATE

```solidity
uint32 _ANNUAL_INFLATION_RATE
```

### \_PPM\_DENOMINATOR

```solidity
uint32 _PPM_DENOMINATOR
```

### \_epochEndTime

```solidity
uint48 _epochEndTime
```

### onlyStakingProxy

```solidity
modifier onlyStakingProxy()
```

### constructor

```solidity
constructor(address newRigoToken, address newStakingProxy) public
```

### mintInflation

```solidity
function mintInflation() external returns (uint256 mintedInflation)
```

Allows staking proxy to mint rewards.

#### Return Values

| Name            | Type    | Description                 |
| --------------- | ------- | --------------------------- |
| mintedInflation | uint256 | Number of allocated tokens. |

### epochEnded

```solidity
function epochEnded() external view returns (bool)
```

Returns whether an epoch has ended.

#### Return Values

| Name | Type | Description               |
| ---- | ---- | ------------------------- |
| \[0] | bool | Bool the epoch has ended. |

### getEpochInflation

```solidity
function getEpochInflation() public view returns (uint256)
```

Returns the epoch inflation.

#### Return Values

| Name | Type    | Description                               |
| ---- | ------- | ----------------------------------------- |
| \[0] | uint256 | Value of units of GRG minted in an epoch. |

### timeUntilNextClaim

```solidity
function timeUntilNextClaim() external view returns (uint256)
```

Returns how long until next claim.

#### Return Values

| Name | Type    | Description        |
| ---- | ------- | ------------------ |
| \[0] | uint256 | Number in seconds. |

### \_assertCallerIsStakingProxy

```solidity
function _assertCallerIsStakingProxy() private view
```

*Asserts that the caller is the Staking Proxy.*

### \_getEpochEndTime

```solidity
function _getEpochEndTime() private view returns (uint256)
```

### \_getEpochLength

```solidity
function _getEpochLength() private view returns (uint256)
```

### \_getRigoToken

```solidity
function _getRigoToken() private view returns (address)
```

### \_getStakingProxy

```solidity
function _getStakingProxy() private view returns (address)
```


# ProofOfPerformance

The proof of performance module uses a pool's own active stake to self as a proxy for assets and performance. The higher the pool's own stake, the higher the reward credited to the staking proxy.

Using the pool's own stake to self as a proxy for a pool's influence over the network has a number of perks, among which are gas savings and network effects. The formula may be reviewed in the future and a copy/performance fee may be applied.

In this context, GRG acts as a universal unit of measure of the different pools' tokens.

<figure><img src="/files/SnkxMHzhzTSyqZPazeVX" alt=""><figcaption><p>Credits: UML diagram generated with <a href="https://github.com/naddison36/sol2uml">SOL2UML</a></p></figcaption></figure>


# pop docs

## ProofOfPerformance

### \_stakingProxy

```solidity
address _stakingProxy
```

### constructor

```solidity
constructor(address stakingProxy) public
```

### creditPopRewardToStakingProxy

```solidity
function creditPopRewardToStakingProxy(address targetPool) external
```

*Credits the pop reward to the Staking Proxy contract.*

#### Parameters

| Name       | Type    | Description          |
| ---------- | ------- | -------------------- |
| targetPool | address | Address of the pool. |

### proofOfPerformance

```solidity
function proofOfPerformance(address targetPool) external view returns (uint256)
```

*Returns the proof of performance reward for a pool.*

#### Parameters

| Name       | Type    | Description          |
| ---------- | ------- | -------------------- |
| targetPool | address | Address of the pool. |

#### Return Values

| Name | Type    | Description                             |
| ---- | ------- | --------------------------------------- |
| \[0] | uint256 | Value of the pop reward in Rigo tokens. |

### \_getStakingProxy

```solidity
function _getStakingProxy() private view returns (address)
```


# GRG Staking

GRG holders stake to their preferred staking pool and earn part of the pool's rewards

When a pool is registered in the Rigoblock staking system, it becomes eligible for receiving GRG rewards. The wallet registering the pool in the staking system is tagged as "staking pal" and receives 10% of the pool operator's rewards, unless it is the same wallet, which receives 100% of the rewards.

GRG holders can stake to their preferred staking pool (or the staking pool which maximizes their ROS) and, as a return for helping the pool operator maximizing its rewards, receive a portion of the pool operator's reward. By default, a minimum of 30% of reward is shared with the pool's stakers. The pool operator can increase the percentage shared with the community in order to attracting more stake and increasing its rewards. Once increased, the percentage shared cannot be decreased, therefore the pool operator must carefully consider the tradeoff between attracting stake and maximizing profitability.

During an epoch (2-weeks long initially) any wallet can credit the proof-of-performance reward for a said pool to the staking system, which is initially equal to the pool's locked staked GRG to itself.

At the end of each epoch a pool's own stake competes with the other active pools' own stakes. In the same way, the total stake delegated to a pool competes with the total stake delegated to all active pools. The two metrics are weighted according to an Arrow-Pratt exponential weighting formula, which initial setting of 2/3 weight for the pool's own relative stake and 1/3 weight for the pool's overall relative delegated stake.

GRG staking is available on Ethereum Mainnet, Arbitrum, Optimism, Base, Unichain, Polygon and BNB chain.


# GrgVault

The GRG vault holds the stakers' staked amount. The stake in the GRG vault is always accessible to the staker, so that even in the remote possibility of an emergency shutdown of the staking system, the staker is always able to withdraw his stake. The staked GRG, in its original design, is always in possession of the GRG vault and segregated from the staking proxy, where GRG rewards are stored.

<figure><img src="/files/oEiFLkc2O24RDjr89zco" alt=""><figcaption><p>Credits: UML diagram generated with <a href="https://github.com/naddison36/sol2uml">SOL2UML</a></p></figcaption></figure>


# grgVault docs

## GrgVault

### stakingProxy

```solidity
address stakingProxy
```

### isInCatastrophicFailure

```solidity
bool isInCatastrophicFailure
```

### \_balances

```solidity
mapping(address => uint256) _balances
```

### grgAssetProxy

```solidity
contract IAssetProxy grgAssetProxy
```

### \_grgToken

```solidity
contract IERC20Token _grgToken
```

### \_grgAssetData

```solidity
bytes _grgAssetData
```

### onlyStakingProxy

```solidity
modifier onlyStakingProxy()
```

*Only stakingProxy can call this function.*

### onlyInCatastrophicFailure

```solidity
modifier onlyInCatastrophicFailure()
```

*Function can only be called in catastrophic failure mode.*

### onlyNotInCatastrophicFailure

```solidity
modifier onlyNotInCatastrophicFailure()
```

*Function can only be called not in catastropic failure mode*

### constructor

```solidity
constructor(address grgProxyAddress, address grgTokenAddress, address newOwner) public
```

*Constructor.*

#### Parameters

| Name            | Type    | Description                         |
| --------------- | ------- | ----------------------------------- |
| grgProxyAddress | address | Address of the RigoBlock Grg Proxy. |
| grgTokenAddress | address | Address of the Grg Token.           |
| newOwner        | address | Address of the Grg vault owner.     |

### setStakingProxy

```solidity
function setStakingProxy(address stakingProxyAddress) external
```

*Sets the address of the StakingProxy contract. Note that only the contract owner can call this function.*

#### Parameters

| Name                | Type    | Description                        |
| ------------------- | ------- | ---------------------------------- |
| stakingProxyAddress | address | Address of Staking proxy contract. |

### enterCatastrophicFailure

```solidity
function enterCatastrophicFailure() external
```

*Vault enters into Catastrophic Failure Mode. \*\*\* WARNING - ONCE IN CATOSTROPHIC FAILURE MODE, YOU CAN NEVER GO BACK! \*\*\* Note that only the contract owner can call this function.*

### setGrgProxy

```solidity
function setGrgProxy(address grgProxyAddress) external
```

*Sets the Grg proxy. Note that only an authorized address can call this function. Note that this can only be called when not in Catastrophic Failure mode.*

#### Parameters

| Name            | Type    | Description                         |
| --------------- | ------- | ----------------------------------- |
| grgProxyAddress | address | Address of the RigoBlock Grg Proxy. |

### depositFrom

```solidity
function depositFrom(address staker, uint256 amount) external
```

*Deposit an `amount` of Grg Tokens from `staker` into the vault. Note that only the Staking contract can call this. Note that this can only be called when not in Catastrophic Failure mode.*

#### Parameters

| Name   | Type    | Description               |
| ------ | ------- | ------------------------- |
| staker | address | of Grg Tokens.            |
| amount | uint256 | of Grg Tokens to deposit. |

### withdrawFrom

```solidity
function withdrawFrom(address staker, uint256 amount) external
```

*Withdraw an `amount` of Grg Tokens to `staker` from the vault. Note that only the Staking contract can call this. Note that this can only be called when not in Catastrophic Failure mode.*

#### Parameters

| Name   | Type    | Description                |
| ------ | ------- | -------------------------- |
| staker | address | of Grg Tokens.             |
| amount | uint256 | of Grg Tokens to withdraw. |

### withdrawAllFrom

```solidity
function withdrawAllFrom(address staker) external returns (uint256)
```

*Withdraw ALL Grg Tokens to `staker` from the vault. Note that this can only be called when in Catastrophic Failure mode.*

#### Parameters

| Name   | Type    | Description    |
| ------ | ------- | -------------- |
| staker | address | of Grg Tokens. |

### balanceOf

```solidity
function balanceOf(address staker) external view returns (uint256)
```

*Returns the balance in Grg Tokens of the `staker`*

#### Return Values

| Name | Type    | Description     |
| ---- | ------- | --------------- |
| \[0] | uint256 | Balance in Grg. |

### balanceOfGrgVault

```solidity
function balanceOfGrgVault() external view returns (uint256)
```

*Returns the entire balance of Grg tokens in the vault.*

### \_withdrawFrom

```solidity
function _withdrawFrom(address staker, uint256 amount) internal
```

*Withdraw an `amount` of Grg Tokens to `staker` from the vault.*

#### Parameters

| Name   | Type    | Description                |
| ------ | ------- | -------------------------- |
| staker | address | of Grg Tokens.             |
| amount | uint256 | of Grg Tokens to withdraw. |

### \_assertSenderIsStakingProxy

```solidity
function _assertSenderIsStakingProxy() private view
```

*Asserts that sender is stakingProxy contract.*

### \_assertInCatastrophicFailure

```solidity
function _assertInCatastrophicFailure() private view
```

*Asserts that vault is in catastrophic failure mode.*

### \_assertNotInCatastrophicFailure

```solidity
function _assertNotInCatastrophicFailure() private view
```

*Asserts that vault is not in catastrophic failure mode.*


# StakingProxy

The staking proxy implements a minimal set of methods used to manage the proxy itself. All methods related to staking are implemented in the staking contract, therefore all non-implemented calls are forwarded to the staking implementation with a delegatecall. Before upgrading the implementation, the Rigoblock Governance must check that those new variables added to the staking implementation storage are placed after the existing variables and that the order of declaration is preserved, otherwise, a storage clash is possible.

<figure><img src="/files/PD12bfVSEpkKkSRBeINk" alt=""><figcaption><p>Credits: UML diagram generated with <a href="https://github.com/naddison36/sol2uml">SOL2UML</a></p></figcaption></figure>


# stakingProxy docs

## StakingProxy

\#dev The RigoBlock Staking contract.

### constructor

```solidity
constructor(address stakingImplementation, address newOwner) public
```

Constructor.

#### Parameters

| Name                  | Type    | Description                                           |
| --------------------- | ------- | ----------------------------------------------------- |
| stakingImplementation | address | Address of the staking contract to delegate calls to. |
| newOwner              | address | Address of the staking proxy owner.                   |

### fallback

```solidity
fallback() external
```

Delegates calls to the staking contract, if it is set.

### attachStakingContract

```solidity
function attachStakingContract(address stakingImplementation) external
```

Attach a staking contract; future calls will be delegated to the staking contract.

*Note that this is callable only by an authorized address.*

#### Parameters

| Name                  | Type    | Description                  |
| --------------------- | ------- | ---------------------------- |
| stakingImplementation | address | Address of staking contract. |

### detachStakingContract

```solidity
function detachStakingContract() external
```

Detach the current staking contract.

*Note that this is callable only by an authorized address.*

### batchExecute

```solidity
function batchExecute(bytes[] data) external returns (bytes[] batchReturnData)
```

Batch executes a series of calls to the staking contract.

#### Parameters

| Name | Type     | Description                                                                             |
| ---- | -------- | --------------------------------------------------------------------------------------- |
| data | bytes\[] | An array of data that encodes a sequence of functions to call in the staking contracts. |

### assertValidStorageParams

```solidity
function assertValidStorageParams() public view
```

Asserts initialziation parameters are correct.

*Asserts that an epoch is between 5 and 30 days long. Asserts that 0 < cobb douglas alpha value <= 1. Asserts that a stake weight is <= 100%. Asserts that pools allow >= 1 maker. Asserts that all addresses are initialized.*

### \_attachStakingContract

```solidity
function _attachStakingContract(address stakingImplementation) internal
```

*Attach a staking contract; future calls will be delegated to the staking contract.*

#### Parameters

| Name                  | Type    | Description                  |
| --------------------- | ------- | ---------------------------- |
| stakingImplementation | address | Address of staking contract. |


# Staking

Staking implementation

Calls to the staking proxy that are not implemented in the proxy (i.e. logic for staking) are forwarded to the staking implementation. Storage is upgradeable but must be preserved, and new variables must be added after the existing storage declarations, otherwise there could be a storage overwrite. The staking proxy was deployed with the same storage dep as the initial staking implementation, thus ensuring that new variables, as long as added at the end of the previous storage declarations, do not generate storage clashing.

{% content-ref url="/pages/Xo59BkavciJxmZJN0ACl" %}
[staking docs](/contracts/grg-staking/staking/staking-docs)
{% endcontent-ref %}


# staking docs

## Staking

### constructor

```solidity
constructor(address grgVault, address poolRegistry, address rigoToken) public
```

Setting owner to null address prevents admin direct calls to implementation.

*Initializing immutable implementation address is used to allow delegatecalls only. Direct calls to the implementation contract are effectively locked.*

#### Parameters

| Name         | Type    | Description                             |
| ------------ | ------- | --------------------------------------- |
| grgVault     | address | Address of the Grg vault.               |
| poolRegistry | address | Address of the RigoBlock pool registry. |
| rigoToken    | address | Address of the Grg token.               |

### init

```solidity
function init() public
```

Initialize storage owned by this contract.

*This function should not be called directly. The StakingProxy contract will call it in `attachStakingContract()`.*

## MixinConstants

### \_PPM\_DENOMINATOR

```solidity
uint32 _PPM_DENOMINATOR
```

### \_NIL\_POOL\_ID

```solidity
bytes32 _NIL_POOL_ID
```

### \_NIL\_ADDRESS

```solidity
address _NIL_ADDRESS
```

### \_MIN\_TOKEN\_VALUE

```solidity
uint256 _MIN_TOKEN_VALUE
```

## MixinDeploymentConstants

### constructor

```solidity
constructor(address grgVault, address poolRegistry, address rigoToken) internal
```

### \_implementation

```solidity
address _implementation
```

### \_rigoToken

```solidity
address _rigoToken
```

### \_grgVault

```solidity
address _grgVault
```

### \_poolRegistry

```solidity
address _poolRegistry
```

### getGrgContract

```solidity
function getGrgContract() public view virtual returns (contract IRigoToken)
```

An overridable way to access the deployed GRG contract.

*Must be view to allow overrides to access state.*

#### Return Values

| Name | Type                | Description                |
| ---- | ------------------- | -------------------------- |
| \[0] | contract IRigoToken | The GRG contract instance. |

### getGrgVault

```solidity
function getGrgVault() public view virtual returns (contract IGrgVault)
```

An overridable way to access the deployed grgVault.

*Must be view to allow overrides to access state.*

#### Return Values

| Name | Type               | Description             |
| ---- | ------------------ | ----------------------- |
| \[0] | contract IGrgVault | The GRG vault contract. |

### getPoolRegistry

```solidity
function getPoolRegistry() public view virtual returns (contract IPoolRegistry)
```

An overridable way to access the deployed rigoblock pool registry.

*Must be view to allow overrides to access state.*

#### Return Values

| Name | Type                   | Description                 |
| ---- | ---------------------- | --------------------------- |
| \[0] | contract IPoolRegistry | The pool registry contract. |

## MixinStorage

### stakingContract

```solidity
address stakingContract
```

Address of staking contract.

#### Return Values

### \_globalStakeByStatus

```solidity
mapping(uint8 => struct IStructs.StoredBalance) _globalStakeByStatus
```

### \_ownerStakeByStatus

```solidity
mapping(uint8 => mapping(address => struct IStructs.StoredBalance)) _ownerStakeByStatus
```

### \_delegatedStakeToPoolByOwner

```solidity
mapping(address => mapping(bytes32 => struct IStructs.StoredBalance)) _delegatedStakeToPoolByOwner
```

### \_delegatedStakeByPoolId

```solidity
mapping(bytes32 => struct IStructs.StoredBalance) _delegatedStakeByPoolId
```

### poolIdByRbPoolAccount

```solidity
mapping(address => bytes32) poolIdByRbPoolAccount
```

Mapping from RigoBlock pool subaccount to pool Id of rigoblock pool

*0 RigoBlock pool subaccount address.*

#### Return Values

### \_poolById

```solidity
mapping(bytes32 => struct IStructs.Pool) _poolById
```

### rewardsByPoolId

```solidity
mapping(bytes32 => uint256) rewardsByPoolId
```

mapping from pool ID to reward balance of members

*0 Pool ID.*

#### Return Values

### currentEpoch

```solidity
uint256 currentEpoch
```

The current epoch.

#### Return Values

### currentEpochStartTimeInSeconds

```solidity
uint256 currentEpochStartTimeInSeconds
```

The current epoch start time.

#### Return Values

### \_cumulativeRewardsByPool

```solidity
mapping(bytes32 => mapping(uint256 => struct IStructs.Fraction)) _cumulativeRewardsByPool
```

### \_cumulativeRewardsByPoolLastStored

```solidity
mapping(bytes32 => uint256) _cumulativeRewardsByPoolLastStored
```

### validPops

```solidity
mapping(address => bool) validPops
```

Registered RigoBlock Proof\_of\_Performance contracts, capable of paying protocol fees.

*0 The address to check.*

#### Return Values

### epochDurationInSeconds

```solidity
uint256 epochDurationInSeconds
```

Minimum seconds between epochs.

#### Return Values

### rewardDelegatedStakeWeight

```solidity
uint32 rewardDelegatedStakeWeight
```

#### Return Values

### minimumPoolStake

```solidity
uint256 minimumPoolStake
```

Minimum amount of stake required in a pool to collect rewards.

#### Return Values

### cobbDouglasAlphaNumerator

```solidity
uint32 cobbDouglasAlphaNumerator
```

Numerator for cobb douglas alpha factor.

#### Return Values

### cobbDouglasAlphaDenominator

```solidity
uint32 cobbDouglasAlphaDenominator
```

Denominator for cobb douglas alpha factor.

#### Return Values

### poolStatsByEpoch

```solidity
mapping(bytes32 => mapping(uint256 => struct IStructs.PoolStats)) poolStatsByEpoch
```

Stats for each pool that generated fees with sufficient stake to earn rewards.

*See `_minimumPoolStake` in `MixinParams`.*

#### Parameters

#### Return Values

### aggregatedStatsByEpoch

```solidity
mapping(uint256 => struct IStructs.AggregatedStats) aggregatedStatsByEpoch
```

Aggregated stats across all pools that generated fees with sufficient stake to earn rewards.

*See `_minimumPoolStake` in MixinParams.*

#### Parameters

#### Return Values

### grgReservedForPoolRewards

```solidity
uint256 grgReservedForPoolRewards
```

The GRG balance of this contract that is reserved for pool reward payouts.

#### Return Values

## IGrgVault

### StakingProxySet

```solidity
event StakingProxySet(address stakingProxyAddress)
```

Emmitted whenever a StakingProxy is set in a vault.

#### Parameters

| Name                | Type    | Description                            |
| ------------------- | ------- | -------------------------------------- |
| stakingProxyAddress | address | Address of the staking proxy contract. |

### InCatastrophicFailureMode

```solidity
event InCatastrophicFailureMode(address sender)
```

Emitted when the Staking contract is put into Catastrophic Failure Mode

#### Parameters

| Name   | Type    | Description                      |
| ------ | ------- | -------------------------------- |
| sender | address | Address of sender (`msg.sender`) |

### Deposit

```solidity
event Deposit(address staker, uint256 amount)
```

Emitted when Grg Tokens are deposited into the vault.

#### Parameters

| Name   | Type    | Description                |
| ------ | ------- | -------------------------- |
| staker | address | Address of the Grg staker. |
| amount | uint256 | of Grg Tokens deposited.   |

### Withdraw

```solidity
event Withdraw(address staker, uint256 amount)
```

Emitted when Grg Tokens are withdrawn from the vault.

#### Parameters

| Name   | Type    | Description                |
| ------ | ------- | -------------------------- |
| staker | address | Address of the Grg staker. |
| amount | uint256 | of Grg Tokens withdrawn.   |

### GrgProxySet

```solidity
event GrgProxySet(address grgProxyAddress)
```

Emitted whenever the Grg AssetProxy is set.

#### Parameters

| Name            | Type    | Description                        |
| --------------- | ------- | ---------------------------------- |
| grgProxyAddress | address | Address of the Grg transfer proxy. |

### setStakingProxy

```solidity
function setStakingProxy(address stakingProxyAddress) external
```

Sets the address of the StakingProxy contract.

*Note that only the contract staker can call this function.*

#### Parameters

| Name                | Type    | Description                        |
| ------------------- | ------- | ---------------------------------- |
| stakingProxyAddress | address | Address of Staking proxy contract. |

### enterCatastrophicFailure

```solidity
function enterCatastrophicFailure() external
```

Vault enters into Catastrophic Failure Mode.

*\*\*\* WARNING - ONCE IN CATOSTROPHIC FAILURE MODE, YOU CAN NEVER GO BACK! \*\*\* Note that only the contract staker can call this function.*

### setGrgProxy

```solidity
function setGrgProxy(address grgProxyAddress) external
```

Sets the Grg proxy.

*Note that only the contract staker can call this. Note that this can only be called when not in Catastrophic Failure mode.*

#### Parameters

| Name            | Type    | Description                         |
| --------------- | ------- | ----------------------------------- |
| grgProxyAddress | address | Address of the RigoBlock Grg Proxy. |

### depositFrom

```solidity
function depositFrom(address staker, uint256 amount) external
```

Deposit an `amount` of Grg Tokens from `staker` into the vault.

*Note that only the Staking contract can call this. Note that this can only be called when not in Catastrophic Failure mode.*

#### Parameters

| Name   | Type    | Description                |
| ------ | ------- | -------------------------- |
| staker | address | Address of the Grg staker. |
| amount | uint256 | of Grg Tokens to deposit.  |

### withdrawFrom

```solidity
function withdrawFrom(address staker, uint256 amount) external
```

Withdraw an `amount` of Grg Tokens to `staker` from the vault.

*Note that only the Staking contract can call this. Note that this can only be called when not in Catastrophic Failure mode.*

#### Parameters

| Name   | Type    | Description                |
| ------ | ------- | -------------------------- |
| staker | address | Address of the Grg staker. |
| amount | uint256 | of Grg Tokens to withdraw. |

### withdrawAllFrom

```solidity
function withdrawAllFrom(address staker) external returns (uint256)
```

Withdraw ALL Grg Tokens to `staker` from the vault.

*Note that this can only be called when in Catastrophic Failure mode.*

#### Parameters

| Name   | Type    | Description                |
| ------ | ------- | -------------------------- |
| staker | address | Address of the Grg staker. |

### balanceOf

```solidity
function balanceOf(address staker) external view returns (uint256)
```

Returns the balance in Grg Tokens of the `staker`

#### Parameters

| Name   | Type    | Description                |
| ------ | ------- | -------------------------- |
| staker | address | Address of the Grg staker. |

#### Return Values

| Name | Type    | Description     |
| ---- | ------- | --------------- |
| \[0] | uint256 | Balance in Grg. |

### balanceOfGrgVault

```solidity
function balanceOfGrgVault() external view returns (uint256)
```

Returns the entire balance of Grg tokens in the vault.

#### Return Values

| Name | Type    | Description     |
| ---- | ------- | --------------- |
| \[0] | uint256 | Balance in Grg. |

## IStaking

### addPopAddress

```solidity
function addPopAddress(address addr) external
```

Adds a new proof\_of\_performance address.

#### Parameters

| Name | Type    | Description                                        |
| ---- | ------- | -------------------------------------------------- |
| addr | address | Address of proof\_of\_performance contract to add. |

### createStakingPool

```solidity
function createStakingPool(address rigoblockPoolAddress) external returns (bytes32 poolId)
```

Create a new staking pool. The sender will be the staking pal of this pool.

*Note that a staking pal must be payable. When governance updates registry address, pools must be migrated to new registry, or this contract must query from both.*

#### Parameters

| Name                 | Type    | Description                                                                  |
| -------------------- | ------- | ---------------------------------------------------------------------------- |
| rigoblockPoolAddress | address | Adds rigoblock pool to the created staking pool for convenience if non-null. |

#### Return Values

| Name   | Type    | Description                                 |
| ------ | ------- | ------------------------------------------- |
| poolId | bytes32 | The unique pool id generated for this pool. |

### setStakingPalAddress

```solidity
function setStakingPalAddress(bytes32 poolId, address newStakingPalAddress) external
```

Allows the operator to update the staking pal address.

#### Parameters

| Name                 | Type    | Description                     |
| -------------------- | ------- | ------------------------------- |
| poolId               | bytes32 | Unique id of pool.              |
| newStakingPalAddress | address | Address of the new staking pal. |

### decreaseStakingPoolOperatorShare

```solidity
function decreaseStakingPoolOperatorShare(bytes32 poolId, uint32 newOperatorShare) external
```

Decreases the operator share for the given pool (i.e. increases pool rewards for members).

#### Parameters

| Name             | Type    | Description                                                          |
| ---------------- | ------- | -------------------------------------------------------------------- |
| poolId           | bytes32 | Unique Id of pool.                                                   |
| newOperatorShare | uint32  | The newly decreased percentage of any rewards owned by the operator. |

### endEpoch

```solidity
function endEpoch() external returns (uint256 numPoolsToFinalize)
```

Begins a new epoch, preparing the prior one for finalization.

*Throws if not enough time has passed between epochs or if the previous epoch was not fully finalized.*

#### Return Values

| Name               | Type    | Description                      |
| ------------------ | ------- | -------------------------------- |
| numPoolsToFinalize | uint256 | The number of unfinalized pools. |

### finalizePool

```solidity
function finalizePool(bytes32 poolId) external
```

Instantly finalizes a single pool that earned rewards in the previous epoch,

*crediting it rewards for members and withdrawing operator's rewards as GRG. This can be called by internal functions that need to finalize a pool immediately. Does nothing if the pool is already finalized or did not earn rewards in the previous epoch.*

#### Parameters

| Name   | Type    | Description              |
| ------ | ------- | ------------------------ |
| poolId | bytes32 | The pool ID to finalize. |

### init

```solidity
function init() external
```

Initialize storage owned by this contract.

*This function should not be called directly. The StakingProxy contract will call it in `attachStakingContract()`.*

### moveStake

```solidity
function moveStake(struct IStructs.StakeInfo from, struct IStructs.StakeInfo to, uint256 amount) external
```

Moves stake between statuses: 'undelegated' or 'delegated'.

*Delegated stake can also be moved between pools. This change comes into effect next epoch.*

#### Parameters

| Name   | Type                      | Description                  |
| ------ | ------------------------- | ---------------------------- |
| from   | struct IStructs.StakeInfo | Status to move stake out of. |
| to     | struct IStructs.StakeInfo | Status to move stake into.   |
| amount | uint256                   | Amount of stake to move.     |

### creditPopReward

```solidity
function creditPopReward(address poolAccount, uint256 popReward) external payable
```

Credits the value of a pool's pop reward.

*Only a known RigoBlock pop can call this method. See (MixinPopManager).*

#### Parameters

| Name        | Type    | Description                                |
| ----------- | ------- | ------------------------------------------ |
| poolAccount | address | The address of the rigoblock pool account. |
| popReward   | uint256 | The pop reward.                            |

### removePopAddress

```solidity
function removePopAddress(address addr) external
```

Removes an existing proof\_of\_performance address.

#### Parameters

| Name | Type    | Description                                           |
| ---- | ------- | ----------------------------------------------------- |
| addr | address | Address of proof\_of\_performance contract to remove. |

### setParams

```solidity
function setParams(uint256 _epochDurationInSeconds, uint32 _rewardDelegatedStakeWeight, uint256 _minimumPoolStake, uint32 _cobbDouglasAlphaNumerator, uint32 _cobbDouglasAlphaDenominator) external
```

Set all configurable parameters at once.

#### Parameters

| Name                          | Type    | Description                                                     |
| ----------------------------- | ------- | --------------------------------------------------------------- |
| \_epochDurationInSeconds      | uint256 | Minimum seconds between epochs.                                 |
| \_rewardDelegatedStakeWeight  | uint32  | How much delegated stake is weighted vs operator stake, in ppm. |
| \_minimumPoolStake            | uint256 | Minimum amount of stake required in a pool to collect rewards.  |
| \_cobbDouglasAlphaNumerator   | uint32  | Numerator for cobb douglas alpha factor.                        |
| \_cobbDouglasAlphaDenominator | uint32  | Denominator for cobb douglas alpha factor.                      |

### stake

```solidity
function stake(uint256 amount) external
```

Stake GRG tokens. Tokens are deposited into the GRG Vault.

*Unstake to retrieve the GRG. Stake is in the 'Active' status.*

#### Parameters

| Name   | Type    | Description      |
| ------ | ------- | ---------------- |
| amount | uint256 | of GRG to stake. |

### unstake

```solidity
function unstake(uint256 amount) external
```

Unstake. Tokens are withdrawn from the GRG Vault and returned to the staker.

*Stake must be in the 'undelegated' status in both the current and next epoch in order to be unstaked.*

#### Parameters

| Name   | Type    | Description        |
| ------ | ------- | ------------------ |
| amount | uint256 | of GRG to unstake. |

### withdrawDelegatorRewards

```solidity
function withdrawDelegatorRewards(bytes32 poolId) external
```

Withdraws the caller's GRG rewards that have accumulated until the last epoch.

#### Parameters

| Name   | Type    | Description        |
| ------ | ------- | ------------------ |
| poolId | bytes32 | Unique id of pool. |

### computeRewardBalanceOfDelegator

```solidity
function computeRewardBalanceOfDelegator(bytes32 poolId, address member) external view returns (uint256 reward)
```

Computes the reward balance in GRG of a specific member of a pool.

#### Parameters

| Name   | Type    | Description             |
| ------ | ------- | ----------------------- |
| poolId | bytes32 | Unique id of pool.      |
| member | address | The member of the pool. |

#### Return Values

| Name   | Type    | Description     |
| ------ | ------- | --------------- |
| reward | uint256 | Balance in GRG. |

### computeRewardBalanceOfOperator

```solidity
function computeRewardBalanceOfOperator(bytes32 poolId) external view returns (uint256 reward)
```

Computes the reward balance in GRG of the operator of a pool.

#### Parameters

| Name   | Type    | Description        |
| ------ | ------- | ------------------ |
| poolId | bytes32 | Unique id of pool. |

#### Return Values

| Name   | Type    | Description     |
| ------ | ------- | --------------- |
| reward | uint256 | Balance in GRG. |

### getCurrentEpochEarliestEndTimeInSeconds

```solidity
function getCurrentEpochEarliestEndTimeInSeconds() external view returns (uint256)
```

Returns the earliest end time in seconds of this epoch.

*The next epoch can begin once this time is reached. Epoch period = \[startTimeInSeconds..endTimeInSeconds)*

#### Return Values

| Name | Type    | Description      |
| ---- | ------- | ---------------- |
| \[0] | uint256 | Time in seconds. |

### getGlobalStakeByStatus

```solidity
function getGlobalStakeByStatus(enum IStructs.StakeStatus stakeStatus) external view returns (struct IStructs.StoredBalance balance)
```

Gets global stake for a given status.

#### Parameters

| Name        | Type                      | Description              |
| ----------- | ------------------------- | ------------------------ |
| stakeStatus | enum IStructs.StakeStatus | UNDELEGATED or DELEGATED |

#### Return Values

| Name    | Type                          | Description                    |
| ------- | ----------------------------- | ------------------------------ |
| balance | struct IStructs.StoredBalance | Global stake for given status. |

### getOwnerStakeByStatus

```solidity
function getOwnerStakeByStatus(address staker, enum IStructs.StakeStatus stakeStatus) external view returns (struct IStructs.StoredBalance balance)
```

Gets an owner's stake balances by status.

#### Parameters

| Name        | Type                      | Description              |
| ----------- | ------------------------- | ------------------------ |
| staker      | address                   | Owner of stake.          |
| stakeStatus | enum IStructs.StakeStatus | UNDELEGATED or DELEGATED |

#### Return Values

| Name    | Type                          | Description                              |
| ------- | ----------------------------- | ---------------------------------------- |
| balance | struct IStructs.StoredBalance | Owner's stake balances for given status. |

### getTotalStake

```solidity
function getTotalStake(address staker) external view returns (uint256)
```

Returns the total stake for a given staker.

#### Parameters

| Name   | Type    | Description |
| ------ | ------- | ----------- |
| staker | address | of stake.   |

#### Return Values

| Name | Type    | Description                   |
| ---- | ------- | ----------------------------- |
| \[0] | uint256 | Total GRG staked by `staker`. |

### getParams

```solidity
function getParams() external view returns (uint256 _epochDurationInSeconds, uint32 _rewardDelegatedStakeWeight, uint256 _minimumPoolStake, uint32 _cobbDouglasAlphaNumerator, uint32 _cobbDouglasAlphaDenominator)
```

*Retrieves all configurable parameter values.*

#### Return Values

| Name                          | Type    | Description                                                     |
| ----------------------------- | ------- | --------------------------------------------------------------- |
| \_epochDurationInSeconds      | uint256 | Minimum seconds between epochs.                                 |
| \_rewardDelegatedStakeWeight  | uint32  | How much delegated stake is weighted vs operator stake, in ppm. |
| \_minimumPoolStake            | uint256 | Minimum amount of stake required in a pool to collect rewards.  |
| \_cobbDouglasAlphaNumerator   | uint32  | Numerator for cobb douglas alpha factor.                        |
| \_cobbDouglasAlphaDenominator | uint32  | Denominator for cobb douglas alpha factor.                      |

### getStakeDelegatedToPoolByOwner

```solidity
function getStakeDelegatedToPoolByOwner(address staker, bytes32 poolId) external view returns (struct IStructs.StoredBalance balance)
```

Returns stake delegated to pool by staker.

#### Parameters

| Name   | Type    | Description        |
| ------ | ------- | ------------------ |
| staker | address | of stake.          |
| poolId | bytes32 | Unique Id of pool. |

#### Return Values

| Name    | Type                          | Description                        |
| ------- | ----------------------------- | ---------------------------------- |
| balance | struct IStructs.StoredBalance | Stake delegated to pool by staker. |

### getStakingPool

```solidity
function getStakingPool(bytes32 poolId) external view returns (struct IStructs.Pool)
```

Returns a staking pool

#### Parameters

| Name   | Type    | Description        |
| ------ | ------- | ------------------ |
| poolId | bytes32 | Unique id of pool. |

### getStakingPoolStatsThisEpoch

```solidity
function getStakingPoolStatsThisEpoch(bytes32 poolId) external view returns (struct IStructs.PoolStats)
```

Get stats on a staking pool in this epoch.

#### Parameters

| Name   | Type    | Description       |
| ------ | ------- | ----------------- |
| poolId | bytes32 | Pool Id to query. |

#### Return Values

| Name | Type                      | Description                   |
| ---- | ------------------------- | ----------------------------- |
| \[0] | struct IStructs.PoolStats | PoolStats struct for pool id. |

### getTotalStakeDelegatedToPool

```solidity
function getTotalStakeDelegatedToPool(bytes32 poolId) external view returns (struct IStructs.StoredBalance balance)
```

Returns the total stake delegated to a specific staking pool, across all members.

#### Parameters

| Name   | Type    | Description        |
| ------ | ------- | ------------------ |
| poolId | bytes32 | Unique Id of pool. |

#### Return Values

| Name    | Type                          | Description                    |
| ------- | ----------------------------- | ------------------------------ |
| balance | struct IStructs.StoredBalance | Total stake delegated to pool. |

### getGrgContract

```solidity
function getGrgContract() external view returns (contract IRigoToken)
```

An overridable way to access the deployed GRG contract.

*Must be view to allow overrides to access state.*

#### Return Values

| Name | Type                | Description                |
| ---- | ------------------- | -------------------------- |
| \[0] | contract IRigoToken | The GRG contract instance. |

### getGrgVault

```solidity
function getGrgVault() external view returns (contract IGrgVault)
```

An overridable way to access the deployed grgVault.

*Must be view to allow overrides to access state.*

#### Return Values

| Name | Type               | Description             |
| ---- | ------------------ | ----------------------- |
| \[0] | contract IGrgVault | The GRG vault contract. |

### getPoolRegistry

```solidity
function getPoolRegistry() external view returns (contract IPoolRegistry)
```

An overridable way to access the deployed rigoblock pool registry.

*Must be view to allow overrides to access state.*

#### Return Values

| Name | Type                   | Description                 |
| ---- | ---------------------- | --------------------------- |
| \[0] | contract IPoolRegistry | The pool registry contract. |

## IStakingEvents

### Stake

```solidity
event Stake(address staker, uint256 amount)
```

Emitted by MixinStake when GRG is staked.

#### Parameters

| Name   | Type    | Description    |
| ------ | ------- | -------------- |
| staker | address | of GRG.        |
| amount | uint256 | of GRG staked. |

### Unstake

```solidity
event Unstake(address staker, uint256 amount)
```

Emitted by MixinStake when GRG is unstaked.

#### Parameters

| Name   | Type    | Description      |
| ------ | ------- | ---------------- |
| staker | address | of GRG.          |
| amount | uint256 | of GRG unstaked. |

### MoveStake

```solidity
event MoveStake(address staker, uint256 amount, uint8 fromStatus, bytes32 fromPool, uint8 toStatus, bytes32 toPool)
```

Emitted by MixinStake when GRG is unstaked.

#### Parameters

| Name       | Type    | Description      |
| ---------- | ------- | ---------------- |
| staker     | address | of GRG.          |
| amount     | uint256 | of GRG unstaked. |
| fromStatus | uint8   |                  |
| fromPool   | bytes32 |                  |
| toStatus   | uint8   |                  |
| toPool     | bytes32 |                  |

### PopAdded

```solidity
event PopAdded(address exchangeAddress)
```

Emitted by MixinExchangeManager when an exchange is added.

#### Parameters

| Name            | Type    | Description              |
| --------------- | ------- | ------------------------ |
| exchangeAddress | address | Address of new exchange. |

### PopRemoved

```solidity
event PopRemoved(address exchangeAddress)
```

Emitted by MixinExchangeManager when an exchange is removed.

#### Parameters

| Name            | Type    | Description                  |
| --------------- | ------- | ---------------------------- |
| exchangeAddress | address | Address of removed exchange. |

### StakingPoolEarnedRewardsInEpoch

```solidity
event StakingPoolEarnedRewardsInEpoch(uint256 epoch, bytes32 poolId)
```

Emitted by MixinExchangeFees when a pool starts earning rewards in an epoch.

#### Parameters

| Name   | Type    | Description                                 |
| ------ | ------- | ------------------------------------------- |
| epoch  | uint256 | The epoch in which the pool earned rewards. |
| poolId | bytes32 | The ID of the pool.                         |

### EpochEnded

```solidity
event EpochEnded(uint256 epoch, uint256 numPoolsToFinalize, uint256 rewardsAvailable, uint256 totalFeesCollected, uint256 totalWeightedStake)
```

Emitted by MixinFinalizer when an epoch has ended.

#### Parameters

| Name               | Type    | Description                                                               |
| ------------------ | ------- | ------------------------------------------------------------------------- |
| epoch              | uint256 | The epoch that ended.                                                     |
| numPoolsToFinalize | uint256 | Number of pools that earned rewards during `epoch` and must be finalized. |
| rewardsAvailable   | uint256 | Rewards available to all pools that earned rewards during `epoch`.        |
| totalFeesCollected | uint256 | Total fees collected across all pools that earned rewards during `epoch`. |
| totalWeightedStake | uint256 | Total weighted stake across all pools that earned rewards during `epoch`. |

### EpochFinalized

```solidity
event EpochFinalized(uint256 epoch, uint256 rewardsPaid, uint256 rewardsRemaining)
```

Emitted by MixinFinalizer when an epoch is fully finalized.

#### Parameters

| Name             | Type    | Description                       |
| ---------------- | ------- | --------------------------------- |
| epoch            | uint256 | The epoch being finalized.        |
| rewardsPaid      | uint256 | Total amount of rewards paid out. |
| rewardsRemaining | uint256 | Rewards left over.                |

### RewardsPaid

```solidity
event RewardsPaid(uint256 epoch, bytes32 poolId, uint256 operatorReward, uint256 membersReward)
```

Emitted by MixinFinalizer when rewards are paid out to a pool.

#### Parameters

| Name           | Type    | Description                               |
| -------------- | ------- | ----------------------------------------- |
| epoch          | uint256 | The epoch when the rewards were paid out. |
| poolId         | bytes32 | The pool's ID.                            |
| operatorReward | uint256 | Amount of reward paid to pool operator.   |
| membersReward  | uint256 | Amount of reward paid to pool members.    |

### ParamsSet

```solidity
event ParamsSet(uint256 epochDurationInSeconds, uint32 rewardDelegatedStakeWeight, uint256 minimumPoolStake, uint256 cobbDouglasAlphaNumerator, uint256 cobbDouglasAlphaDenominator)
```

Emitted whenever staking parameters are changed via the `setParams()` function.

#### Parameters

| Name                        | Type    | Description                                                     |
| --------------------------- | ------- | --------------------------------------------------------------- |
| epochDurationInSeconds      | uint256 | Minimum seconds between epochs.                                 |
| rewardDelegatedStakeWeight  | uint32  | How much delegated stake is weighted vs operator stake, in ppm. |
| minimumPoolStake            | uint256 | Minimum amount of stake required in a pool to collect rewards.  |
| cobbDouglasAlphaNumerator   | uint256 | Numerator for cobb douglas alpha factor.                        |
| cobbDouglasAlphaDenominator | uint256 | Denominator for cobb douglas alpha factor.                      |

### StakingPoolCreated

```solidity
event StakingPoolCreated(bytes32 poolId, address operator, uint32 operatorShare)
```

Emitted by MixinStakingPool when a new pool is created.

#### Parameters

| Name          | Type    | Description                                         |
| ------------- | ------- | --------------------------------------------------- |
| poolId        | bytes32 | Unique id generated for pool.                       |
| operator      | address | The operator (creator) of pool.                     |
| operatorShare | uint32  | The share of rewards given to the operator, in ppm. |

### RbPoolStakingPoolSet

```solidity
event RbPoolStakingPoolSet(address rbPoolAddress, bytes32 poolId)
```

Emitted by MixinStakingPool when a rigoblock pool is added to its staking pool.

#### Parameters

| Name          | Type    | Description                    |
| ------------- | ------- | ------------------------------ |
| rbPoolAddress | address | Adress of maker added to pool. |
| poolId        | bytes32 | Unique id of pool.             |

### OperatorShareDecreased

```solidity
event OperatorShareDecreased(bytes32 poolId, uint32 oldOperatorShare, uint32 newOperatorShare)
```

Emitted when a staking pool's operator share is decreased.

#### Parameters

| Name             | Type    | Description                                         |
| ---------------- | ------- | --------------------------------------------------- |
| poolId           | bytes32 | Unique Id of pool.                                  |
| oldOperatorShare | uint32  | Previous share of rewards owned by operator.        |
| newOperatorShare | uint32  | Newly decreased share of rewards owned by operator. |

### GrgMintEvent

```solidity
event GrgMintEvent(uint256 grgAmount)
```

Emitted when an inflation mint call is executed successfully.

#### Parameters

| Name      | Type    | Description                                       |
| --------- | ------- | ------------------------------------------------- |
| grgAmount | uint256 | Amount of GRG tokens minted to the staking proxy. |

### CatchStringEvent

```solidity
event CatchStringEvent(string reason)
```

Emitted whenever an inflation mint call is reverted.

#### Parameters

| Name   | Type   | Description                   |
| ------ | ------ | ----------------------------- |
| reason | string | String of the revert message. |

### ReturnDataEvent

```solidity
event ReturnDataEvent(bytes reason)
```

Emitted to catch any other inflation mint call fail.

#### Parameters

| Name   | Type  | Description                               |
| ------ | ----- | ----------------------------------------- |
| reason | bytes | Bytes output of the reverted transaction. |

## IStakingProxy

### StakingContractAttachedToProxy

```solidity
event StakingContractAttachedToProxy(address newStakingContractAddress)
```

Emitted by StakingProxy when a staking contract is attached.

#### Parameters

| Name                      | Type    | Description                                 |
| ------------------------- | ------- | ------------------------------------------- |
| newStakingContractAddress | address | Address of newly attached staking contract. |

### StakingContractDetachedFromProxy

```solidity
event StakingContractDetachedFromProxy()
```

Emitted by StakingProxy when a staking contract is detached.

### attachStakingContract

```solidity
function attachStakingContract(address stakingImplementation) external
```

Attach a staking contract; future calls will be delegated to the staking contract.

*Note that this is callable only by an authorized address.*

#### Parameters

| Name                  | Type    | Description                  |
| --------------------- | ------- | ---------------------------- |
| stakingImplementation | address | Address of staking contract. |

### detachStakingContract

```solidity
function detachStakingContract() external
```

Detach the current staking contract.

*Note that this is callable only by an authorized address.*

### batchExecute

```solidity
function batchExecute(bytes[] data) external returns (bytes[] batchReturnData)
```

Batch executes a series of calls to the staking contract.

#### Parameters

| Name | Type     | Description                                                                             |
| ---- | -------- | --------------------------------------------------------------------------------------- |
| data | bytes\[] | An array of data that encodes a sequence of functions to call in the staking contracts. |

### assertValidStorageParams

```solidity
function assertValidStorageParams() external view
```

Asserts initialziation parameters are correct.

*Asserts that an epoch is between 5 and 30 days long. Asserts that 0 < cobb douglas alpha value <= 1. Asserts that a stake weight is <= 100%. Asserts that pools allow >= 1 maker. Asserts that all addresses are initialized.*

## IStorage

### stakingContract

```solidity
function stakingContract() external view returns (address)
```

Address of staking contract.

#### Return Values

| Name | Type    | Description                                      |
| ---- | ------- | ------------------------------------------------ |
| \[0] | address | stakingContract Address of the staking contract. |

### poolIdByRbPoolAccount

```solidity
function poolIdByRbPoolAccount(address) external view returns (bytes32)
```

Mapping from RigoBlock pool subaccount to pool Id of rigoblock pool

*0 RigoBlock pool subaccount address.*

#### Return Values

| Name | Type    | Description    |
| ---- | ------- | -------------- |
| \[0] | bytes32 | 0 The pool ID. |

### rewardsByPoolId

```solidity
function rewardsByPoolId(bytes32) external view returns (uint256)
```

mapping from pool ID to reward balance of members

*0 Pool ID.*

#### Return Values

| Name | Type    | Description                                         |
| ---- | ------- | --------------------------------------------------- |
| \[0] | uint256 | 0 The total reward balance of members in this pool. |

### currentEpoch

```solidity
function currentEpoch() external view returns (uint256)
```

The current epoch.

#### Return Values

| Name | Type    | Description                                   |
| ---- | ------- | --------------------------------------------- |
| \[0] | uint256 | currentEpoch The number of the current epoch. |

### currentEpochStartTimeInSeconds

```solidity
function currentEpochStartTimeInSeconds() external view returns (uint256)
```

The current epoch start time.

#### Return Values

| Name | Type    | Description                                             |
| ---- | ------- | ------------------------------------------------------- |
| \[0] | uint256 | currentEpochStartTimeInSeconds Timestamp of start time. |

### validPops

```solidity
function validPops(address popAddress) external view returns (bool)
```

Registered RigoBlock Proof\_of\_Performance contracts, capable of paying protocol fees.

*0 The address to check.*

#### Return Values

| Name | Type | Description                                                   |
| ---- | ---- | ------------------------------------------------------------- |
| \[0] | bool | 0 Whether the address is a registered proof\_of\_performance. |

### epochDurationInSeconds

```solidity
function epochDurationInSeconds() external view returns (uint256)
```

Minimum seconds between epochs.

#### Return Values

| Name | Type    | Description                               |
| ---- | ------- | ----------------------------------------- |
| \[0] | uint256 | epochDurationInSeconds Number of seconds. |

### rewardDelegatedStakeWeight

```solidity
function rewardDelegatedStakeWeight() external view returns (uint32)
```

#### Return Values

| Name | Type   | Description                                              |
| ---- | ------ | -------------------------------------------------------- |
| \[0] | uint32 | rewardDelegatedStakeWeight Number in units of a million. |

### minimumPoolStake

```solidity
function minimumPoolStake() external view returns (uint256)
```

Minimum amount of stake required in a pool to collect rewards.

#### Return Values

| Name | Type    | Description                               |
| ---- | ------- | ----------------------------------------- |
| \[0] | uint256 | minimumPoolStake Minimum amount required. |

### cobbDouglasAlphaNumerator

```solidity
function cobbDouglasAlphaNumerator() external view returns (uint32)
```

Numerator for cobb douglas alpha factor.

#### Return Values

| Name | Type   | Description                                        |
| ---- | ------ | -------------------------------------------------- |
| \[0] | uint32 | cobbDouglasAlphaNumerator Number of the numerator. |

### cobbDouglasAlphaDenominator

```solidity
function cobbDouglasAlphaDenominator() external view returns (uint32)
```

Denominator for cobb douglas alpha factor.

#### Return Values

| Name | Type   | Description                                            |
| ---- | ------ | ------------------------------------------------------ |
| \[0] | uint32 | cobbDouglasAlphaDenominator Number of the denominator. |

### poolStatsByEpoch

```solidity
function poolStatsByEpoch(bytes32 key, uint256 epoch) external view returns (uint256 feesCollected, uint256 weightedStake, uint256 membersStake)
```

Stats for each pool that generated fees with sufficient stake to earn rewards.

*See `_minimumPoolStake` in `MixinParams`.*

#### Parameters

| Name  | Type    | Description   |
| ----- | ------- | ------------- |
| key   | bytes32 | Pool ID.      |
| epoch | uint256 | Epoch number. |

#### Return Values

| Name          | Type    | Description                        |
| ------------- | ------- | ---------------------------------- |
| feesCollected | uint256 | Amount of fees collected in epoch. |
| weightedStake | uint256 | Weighted stake per million.        |
| membersStake  | uint256 | Members stake per million.         |

### aggregatedStatsByEpoch

```solidity
function aggregatedStatsByEpoch(uint256 epoch) external view returns (uint256 rewardsAvailable, uint256 numPoolsToFinalize, uint256 totalFeesCollected, uint256 totalWeightedStake, uint256 totalRewardsFinalized)
```

Aggregated stats across all pools that generated fees with sufficient stake to earn rewards.

*See `_minimumPoolStake` in MixinParams.*

#### Parameters

| Name  | Type    | Description   |
| ----- | ------- | ------------- |
| epoch | uint256 | Epoch number. |

#### Return Values

| Name                  | Type    | Description                                                                  |
| --------------------- | ------- | ---------------------------------------------------------------------------- |
| rewardsAvailable      | uint256 | Rewards (GRG) available to the epoch being finalized (the previous epoch).   |
| numPoolsToFinalize    | uint256 | The number of pools that have yet to be finalized through `finalizePools()`. |
| totalFeesCollected    | uint256 | The total fees collected for the epoch being finalized.                      |
| totalWeightedStake    | uint256 | The total fees collected for the epoch being finalized.                      |
| totalRewardsFinalized | uint256 | Amount of rewards that have been paid during finalization.                   |

### grgReservedForPoolRewards

```solidity
function grgReservedForPoolRewards() external view returns (uint256)
```

The GRG balance of this contract that is reserved for pool reward payouts.

#### Return Values

| Name | Type    | Description                                                      |
| ---- | ------- | ---------------------------------------------------------------- |
| \[0] | uint256 | grgReservedForPoolRewards Number of tokens reserved for rewards. |

## IStorageInit

### init

```solidity
function init() external
```

Initialize storage owned by this contract.

## IStructs

### PoolStats

```solidity
struct PoolStats {
  uint256 feesCollected;
  uint256 weightedStake;
  uint256 membersStake;
}
```

### AggregatedStats

```solidity
struct AggregatedStats {
  uint256 rewardsAvailable;
  uint256 numPoolsToFinalize;
  uint256 totalFeesCollected;
  uint256 totalWeightedStake;
  uint256 totalRewardsFinalized;
}
```

### StoredBalance

```solidity
struct StoredBalance {
  uint64 currentEpoch;
  uint96 currentEpochBalance;
  uint96 nextEpochBalance;
}
```

### StakeStatus

```solidity
enum StakeStatus {
  UNDELEGATED,
  DELEGATED
}
```

### StakeInfo

```solidity
struct StakeInfo {
  enum IStructs.StakeStatus status;
  bytes32 poolId;
}
```

### Fraction

```solidity
struct Fraction {
  uint256 numerator;
  uint256 denominator;
}
```

### Pool

```solidity
struct Pool {
  address operator;
  address stakingPal;
  uint32 operatorShare;
  uint32 stakingPalShare;
}
```

## LibCobbDouglas

### cobbDouglas

```solidity
function cobbDouglas(uint256 totalRewards, uint256 fees, uint256 totalFees, uint256 stake, uint256 totalStake, uint32 alphaNumerator, uint32 alphaDenominator) internal pure returns (uint256 rewards)
```

*The cobb-douglas function used to compute fee-based rewards for staking pools in a given epoch. This function does not perform bounds checking on the inputs, but the following conditions need to be true: 0 <= fees / totalFees <= 1 0 <= stake / totalStake <= 1 0 <= alphaNumerator / alphaDenominator <= 1*

#### Parameters

| Name             | Type    | Description                                                |
| ---------------- | ------- | ---------------------------------------------------------- |
| totalRewards     | uint256 | collected over an epoch.                                   |
| fees             | uint256 | Fees attributed to the the staking pool.                   |
| totalFees        | uint256 | Total fees collected across all pools that earned rewards. |
| stake            | uint256 | Stake attributed to the staking pool.                      |
| totalStake       | uint256 | Total stake across all pools that earned rewards.          |
| alphaNumerator   | uint32  | Numerator of `alpha` in the cobb-douglas function.         |
| alphaDenominator | uint32  | Denominator of `alpha` in the cobb-douglas function.       |

#### Return Values

| Name    | Type    | Description                       |
| ------- | ------- | --------------------------------- |
| rewards | uint256 | Rewards owed to the staking pool. |

## LibFixedMath

*Signed, fixed-point, 127-bit precision math library.*

### FIXED\_1

```solidity
int256 FIXED_1
```

### MIN\_FIXED\_VAL

```solidity
int256 MIN_FIXED_VAL
```

### FIXED\_1\_SQUARED

```solidity
int256 FIXED_1_SQUARED
```

### LN\_MAX\_VAL

```solidity
int256 LN_MAX_VAL
```

### LN\_MIN\_VAL

```solidity
int256 LN_MIN_VAL
```

### EXP\_MAX\_VAL

```solidity
int256 EXP_MAX_VAL
```

### EXP\_MIN\_VAL

```solidity
int256 EXP_MIN_VAL
```

### mul

```solidity
function mul(int256 a, int256 b) internal pure returns (int256 c)
```

*Returns the multiplication of two fixed point numbers, reverting on overflow.*

### div

```solidity
function div(int256 a, int256 b) internal pure returns (int256 c)
```

*Returns the division of two fixed point numbers.*

### mulDiv

```solidity
function mulDiv(int256 a, int256 n, int256 d) internal pure returns (int256 c)
```

*Performs (a \* n) / d, without scaling for precision.*

### uintMul

```solidity
function uintMul(int256 f, uint256 u) internal pure returns (uint256)
```

*Returns the unsigned integer result of multiplying a fixed-point number with an integer, reverting if the multiplication overflows. Negative results are clamped to zero.*

### toFixed

```solidity
function toFixed(uint256 n, uint256 d) internal pure returns (int256 f)
```

*Convert unsigned `n` / `d` to a fixed-point number. Reverts if `n` / `d` is too large to fit in a fixed-point number.*

### ln

```solidity
function ln(int256 x) internal pure returns (int256 r)
```

*Get the natural logarithm of a fixed-point number 0 < `x` <= LN\_MAX\_VAL*

### exp

```solidity
function exp(int256 x) internal pure returns (int256 r)
```

*Compute the natural exponent for a fixed-point number EXP\_MIN\_VAL <= `x` <= 1*

### \_mul

```solidity
function _mul(int256 a, int256 b) private pure returns (int256 c)
```

*Returns the multiplication two numbers, reverting on overflow.*

### \_div

```solidity
function _div(int256 a, int256 b) private pure returns (int256 c)
```

*Returns the division of two numbers, reverting on division by zero.*

## LibSafeDowncast

### downcastToUint96

```solidity
function downcastToUint96(uint256 a) internal pure returns (uint96 b)
```

*Safely downcasts to a uint96 Note that this reverts if the input value is too large.*

### downcastToUint64

```solidity
function downcastToUint64(uint256 a) internal pure returns (uint64 b)
```

*Safely downcasts to a uint64 Note that this reverts if the input value is too large.*

## MixinPopManager

### addPopAddress

```solidity
function addPopAddress(address addr) external
```

Adds a new proof\_of\_performance address.

#### Parameters

| Name | Type    | Description                                        |
| ---- | ------- | -------------------------------------------------- |
| addr | address | Address of proof\_of\_performance contract to add. |

### removePopAddress

```solidity
function removePopAddress(address addr) external
```

Removes an existing proof\_of\_performance address.

#### Parameters

| Name | Type    | Description                                           |
| ---- | ------- | ----------------------------------------------------- |
| addr | address | Address of proof\_of\_performance contract to remove. |

## MixinPopRewards

### onlyPop

```solidity
modifier onlyPop()
```

*Asserts that the call is coming from a valid pop.*

### creditPopReward

```solidity
function creditPopReward(address poolAccount, uint256 popReward) external payable
```

Credits the value of a pool's pop reward.

*Only a known RigoBlock pop can call this method. See (MixinPopManager).*

#### Parameters

| Name        | Type    | Description                                |
| ----------- | ------- | ------------------------------------------ |
| poolAccount | address | The address of the rigoblock pool account. |
| popReward   | uint256 | The pop reward.                            |

### getStakingPoolStatsThisEpoch

```solidity
function getStakingPoolStatsThisEpoch(bytes32 poolId) external view returns (struct IStructs.PoolStats)
```

Get stats on a staking pool in this epoch.

#### Parameters

| Name   | Type    | Description       |
| ------ | ------- | ----------------- |
| poolId | bytes32 | Pool Id to query. |

#### Return Values

| Name | Type                      | Description                   |
| ---- | ------------------------- | ----------------------------- |
| \[0] | struct IStructs.PoolStats | PoolStats struct for pool id. |

### \_computeMembersAndWeightedStake

```solidity
function _computeMembersAndWeightedStake(bytes32 poolId, uint256 totalStake) private view returns (uint256 membersStake, uint256 weightedStake)
```

*Computes the members and weighted stake for a pool at the current epoch.*

#### Parameters

| Name       | Type    | Description                           |
| ---------- | ------- | ------------------------------------- |
| poolId     | bytes32 | ID of the pool.                       |
| totalStake | uint256 | Total (unweighted) stake in the pool. |

#### Return Values

| Name          | Type    | Description                     |
| ------------- | ------- | ------------------------------- |
| membersStake  | uint256 | Non-operator stake in the pool. |
| weightedStake | uint256 | Weighted stake of the pool.     |

## MixinStake

### stake

```solidity
function stake(uint256 amount) external
```

Stake GRG tokens. Tokens are deposited into the GRG Vault.

*Unstake to retrieve the GRG. Stake is in the 'Active' status.*

#### Parameters

| Name   | Type    | Description      |
| ------ | ------- | ---------------- |
| amount | uint256 | of GRG to stake. |

### unstake

```solidity
function unstake(uint256 amount) external
```

Unstake. Tokens are withdrawn from the GRG Vault and returned to the staker.

*Stake must be in the 'undelegated' status in both the current and next epoch in order to be unstaked.*

#### Parameters

| Name   | Type    | Description        |
| ------ | ------- | ------------------ |
| amount | uint256 | of GRG to unstake. |

### moveStake

```solidity
function moveStake(struct IStructs.StakeInfo from, struct IStructs.StakeInfo to, uint256 amount) external
```

Moves stake between statuses: 'undelegated' or 'delegated'.

*Delegated stake can also be moved between pools. This change comes into effect next epoch.*

#### Parameters

| Name   | Type                      | Description                  |
| ------ | ------------------------- | ---------------------------- |
| from   | struct IStructs.StakeInfo | Status to move stake out of. |
| to     | struct IStructs.StakeInfo | Status to move stake into.   |
| amount | uint256                   | Amount of stake to move.     |

### \_delegateStake

```solidity
function _delegateStake(bytes32 poolId, address staker, uint256 amount) private
```

*Delegates a owners stake to a staking pool.*

#### Parameters

| Name   | Type    | Description                  |
| ------ | ------- | ---------------------------- |
| poolId | bytes32 | Id of pool to delegate to.   |
| staker | address | Owner who wants to delegate. |
| amount | uint256 | Amount of stake to delegate. |

### \_undelegateStake

```solidity
function _undelegateStake(bytes32 poolId, address staker, uint256 amount) private
```

*Un-Delegates a owners stake from a staking pool.*

#### Parameters

| Name   | Type    | Description                     |
| ------ | ------- | ------------------------------- |
| poolId | bytes32 | Id of pool to un-delegate from. |
| staker | address | Owner who wants to un-delegate. |
| amount | uint256 | Amount of stake to un-delegate. |

## MixinStakeBalances

### getGlobalStakeByStatus

```solidity
function getGlobalStakeByStatus(enum IStructs.StakeStatus stakeStatus) external view returns (struct IStructs.StoredBalance balance)
```

Gets global stake for a given status.

#### Parameters

| Name        | Type                      | Description              |
| ----------- | ------------------------- | ------------------------ |
| stakeStatus | enum IStructs.StakeStatus | UNDELEGATED or DELEGATED |

#### Return Values

| Name    | Type                          | Description                    |
| ------- | ----------------------------- | ------------------------------ |
| balance | struct IStructs.StoredBalance | Global stake for given status. |

### getOwnerStakeByStatus

```solidity
function getOwnerStakeByStatus(address staker, enum IStructs.StakeStatus stakeStatus) external view returns (struct IStructs.StoredBalance balance)
```

Gets an owner's stake balances by status.

#### Parameters

| Name        | Type                      | Description              |
| ----------- | ------------------------- | ------------------------ |
| staker      | address                   | Owner of stake.          |
| stakeStatus | enum IStructs.StakeStatus | UNDELEGATED or DELEGATED |

#### Return Values

| Name    | Type                          | Description                              |
| ------- | ----------------------------- | ---------------------------------------- |
| balance | struct IStructs.StoredBalance | Owner's stake balances for given status. |

### getTotalStake

```solidity
function getTotalStake(address staker) public view returns (uint256)
```

Returns the total stake for a given staker.

#### Parameters

| Name   | Type    | Description |
| ------ | ------- | ----------- |
| staker | address | of stake.   |

#### Return Values

| Name | Type    | Description                   |
| ---- | ------- | ----------------------------- |
| \[0] | uint256 | Total GRG staked by `staker`. |

### getStakeDelegatedToPoolByOwner

```solidity
function getStakeDelegatedToPoolByOwner(address staker, bytes32 poolId) public view returns (struct IStructs.StoredBalance balance)
```

Returns stake delegated to pool by staker.

#### Parameters

| Name   | Type    | Description        |
| ------ | ------- | ------------------ |
| staker | address | of stake.          |
| poolId | bytes32 | Unique Id of pool. |

#### Return Values

| Name    | Type                          | Description                        |
| ------- | ----------------------------- | ---------------------------------- |
| balance | struct IStructs.StoredBalance | Stake delegated to pool by staker. |

### getTotalStakeDelegatedToPool

```solidity
function getTotalStakeDelegatedToPool(bytes32 poolId) public view returns (struct IStructs.StoredBalance balance)
```

Returns the total stake delegated to a specific staking pool, across all members.

#### Parameters

| Name   | Type    | Description        |
| ------ | ------- | ------------------ |
| poolId | bytes32 | Unique Id of pool. |

#### Return Values

| Name    | Type                          | Description                    |
| ------- | ----------------------------- | ------------------------------ |
| balance | struct IStructs.StoredBalance | Total stake delegated to pool. |

## MixinStakeStorage

*This mixin contains logic for managing stake storage.*

### \_moveStake

```solidity
function _moveStake(struct IStructs.StoredBalance fromPtr, struct IStructs.StoredBalance toPtr, uint256 amount) internal
```

*Moves stake between states: 'undelegated' or 'delegated'. This change comes into effect next epoch.*

#### Parameters

| Name    | Type                          | Description                                  |
| ------- | ----------------------------- | -------------------------------------------- |
| fromPtr | struct IStructs.StoredBalance | pointer to storage location of `from` stake. |
| toPtr   | struct IStructs.StoredBalance | pointer to storage location of `to` stake.   |
| amount  | uint256                       | of stake to move.                            |

### \_loadCurrentBalance

```solidity
function _loadCurrentBalance(struct IStructs.StoredBalance balancePtr) internal view returns (struct IStructs.StoredBalance balance)
```

*Loads a balance from storage and updates its fields to reflect values for the current epoch.*

#### Parameters

| Name       | Type                          | Description |
| ---------- | ----------------------------- | ----------- |
| balancePtr | struct IStructs.StoredBalance | to load.    |

#### Return Values

| Name    | Type                          | Description      |
| ------- | ----------------------------- | ---------------- |
| balance | struct IStructs.StoredBalance | current balance. |

### \_increaseCurrentAndNextBalance

```solidity
function _increaseCurrentAndNextBalance(struct IStructs.StoredBalance balancePtr, uint256 amount) internal
```

*Increments both the `current` and `next` fields.*

#### Parameters

| Name       | Type                          | Description                 |
| ---------- | ----------------------------- | --------------------------- |
| balancePtr | struct IStructs.StoredBalance | storage pointer to balance. |
| amount     | uint256                       | to mint.                    |

### \_decreaseCurrentAndNextBalance

```solidity
function _decreaseCurrentAndNextBalance(struct IStructs.StoredBalance balancePtr, uint256 amount) internal
```

*Decrements both the `current` and `next` fields.*

#### Parameters

| Name       | Type                          | Description                 |
| ---------- | ----------------------------- | --------------------------- |
| balancePtr | struct IStructs.StoredBalance | storage pointer to balance. |
| amount     | uint256                       | to mint.                    |

### \_increaseNextBalance

```solidity
function _increaseNextBalance(struct IStructs.StoredBalance balancePtr, uint256 amount) internal
```

*Increments the `next` field (but not the `current` field).*

#### Parameters

| Name       | Type                          | Description                 |
| ---------- | ----------------------------- | --------------------------- |
| balancePtr | struct IStructs.StoredBalance | storage pointer to balance. |
| amount     | uint256                       | to increment by.            |

### \_decreaseNextBalance

```solidity
function _decreaseNextBalance(struct IStructs.StoredBalance balancePtr, uint256 amount) internal
```

*Decrements the `next` field (but not the `current` field).*

#### Parameters

| Name       | Type                          | Description                 |
| ---------- | ----------------------------- | --------------------------- |
| balancePtr | struct IStructs.StoredBalance | storage pointer to balance. |
| amount     | uint256                       | to decrement by.            |

### \_storeBalance

```solidity
function _storeBalance(struct IStructs.StoredBalance balancePtr, struct IStructs.StoredBalance balance) private
```

*Stores a balance in storage.*

#### Parameters

| Name       | Type                          | Description                               |
| ---------- | ----------------------------- | ----------------------------------------- |
| balancePtr | struct IStructs.StoredBalance | points to where `balance` will be stored. |
| balance    | struct IStructs.StoredBalance | to save to storage.                       |

### \_arePointersEqual

```solidity
function _arePointersEqual(struct IStructs.StoredBalance balancePtrA, struct IStructs.StoredBalance balancePtrB) private pure returns (bool areEqual)
```

*Returns true iff storage pointers resolve to same storage location.*

#### Parameters

| Name        | Type                          | Description             |
| ----------- | ----------------------------- | ----------------------- |
| balancePtrA | struct IStructs.StoredBalance | first storage pointer.  |
| balancePtrB | struct IStructs.StoredBalance | second storage pointer. |

#### Return Values

| Name     | Type | Description                  |
| -------- | ---- | ---------------------------- |
| areEqual | bool | true iff pointers are equal. |

## MixinCumulativeRewards

### \_isCumulativeRewardSet

```solidity
function _isCumulativeRewardSet(struct IStructs.Fraction cumulativeReward) internal pure returns (bool)
```

*returns true iff Cumulative Rewards are set*

### \_addCumulativeReward

```solidity
function _addCumulativeReward(bytes32 poolId, uint256 reward, uint256 stake) internal
```

*Sets a pool's cumulative delegator rewards for the current epoch, given the rewards earned and stake from the last epoch, which will be summed with the previous cumulative rewards for this pool. If the last cumulative reward epoch is the current epoch, this is a no-op.*

#### Parameters

| Name   | Type    | Description                                                     |
| ------ | ------- | --------------------------------------------------------------- |
| poolId | bytes32 | The pool ID.                                                    |
| reward | uint256 | The total reward earned by pool delegators from the last epoch. |
| stake  | uint256 | The total delegated stake in the pool in the last epoch.        |

### \_updateCumulativeReward

```solidity
function _updateCumulativeReward(bytes32 poolId) internal
```

*Sets a pool's cumulative delegator rewards for the current epoch, using the last stored cumulative rewards. If we've already set a CR for this epoch, this is a no-op.*

#### Parameters

| Name   | Type    | Description  |
| ------ | ------- | ------------ |
| poolId | bytes32 | The pool ID. |

### \_computeMemberRewardOverInterval

```solidity
function _computeMemberRewardOverInterval(bytes32 poolId, uint256 memberStakeOverInterval, uint256 beginEpoch, uint256 endEpoch) internal view returns (uint256 reward)
```

*Computes a member's reward over a given epoch interval.*

#### Parameters

| Name                    | Type    | Description                                          |
| ----------------------- | ------- | ---------------------------------------------------- |
| poolId                  | bytes32 | Uniqud Id of pool.                                   |
| memberStakeOverInterval | uint256 | Stake delegated to pool by member over the interval. |
| beginEpoch              | uint256 | Beginning of interval.                               |
| endEpoch                | uint256 | End of interval.                                     |

#### Return Values

| Name   | Type    | Description                                              |
| ------ | ------- | -------------------------------------------------------- |
| reward | uint256 | Reward accumulated over interval \[beginEpoch, endEpoch] |

### \_getCumulativeRewardAtEpoch

```solidity
function _getCumulativeRewardAtEpoch(bytes32 poolId, uint256 epoch) private view returns (struct IStructs.Fraction cumulativeReward)
```

*Fetch the cumulative reward for a given epoch. If the corresponding CR does not exist in state, then we backtrack to find its value by querying `epoch-1` and then most recent CR.*

#### Parameters

| Name   | Type    | Description           |
| ------ | ------- | --------------------- |
| poolId | bytes32 | Unique ID of pool.    |
| epoch  | uint256 | The epoch to find the |

#### Return Values

| Name             | Type                     | Description                                    |
| ---------------- | ------------------------ | ---------------------------------------------- |
| cumulativeReward | struct IStructs.Fraction | The cumulative reward for `poolId` at `epoch`. |

## MixinStakingPool

### onlyStakingPoolOperator

```solidity
modifier onlyStakingPoolOperator(bytes32 poolId)
```

*Asserts that the sender is the operator of the input pool.*

#### Parameters

| Name   | Type    | Description                      |
| ------ | ------- | -------------------------------- |
| poolId | bytes32 | Pool sender must be operator of. |

### onlyDelegateCall

```solidity
modifier onlyDelegateCall()
```

### createStakingPool

```solidity
function createStakingPool(address rigoblockPoolAddress) external returns (bytes32 poolId)
```

Create a new staking pool. The sender will be the staking pal of this pool.

*Note that a staking pal must be payable. When governance updates registry address, pools must be migrated to new registry, or this contract must query from both.*

#### Parameters

| Name                 | Type    | Description                                                                  |
| -------------------- | ------- | ---------------------------------------------------------------------------- |
| rigoblockPoolAddress | address | Adds rigoblock pool to the created staking pool for convenience if non-null. |

#### Return Values

| Name   | Type    | Description                                 |
| ------ | ------- | ------------------------------------------- |
| poolId | bytes32 | The unique pool id generated for this pool. |

### setStakingPalAddress

```solidity
function setStakingPalAddress(bytes32 poolId, address newStakingPalAddress) external
```

Allows the operator to update the staking pal address.

#### Parameters

| Name                 | Type    | Description                     |
| -------------------- | ------- | ------------------------------- |
| poolId               | bytes32 | Unique id of pool.              |
| newStakingPalAddress | address | Address of the new staking pal. |

### decreaseStakingPoolOperatorShare

```solidity
function decreaseStakingPoolOperatorShare(bytes32 poolId, uint32 newOperatorShare) external
```

Decreases the operator share for the given pool (i.e. increases pool rewards for members).

#### Parameters

| Name             | Type    | Description                                                          |
| ---------------- | ------- | -------------------------------------------------------------------- |
| poolId           | bytes32 | Unique Id of pool.                                                   |
| newOperatorShare | uint32  | The newly decreased percentage of any rewards owned by the operator. |

### getStakingPool

```solidity
function getStakingPool(bytes32 poolId) public view returns (struct IStructs.Pool)
```

Returns a staking pool

#### Parameters

| Name   | Type    | Description        |
| ------ | ------- | ------------------ |
| poolId | bytes32 | Unique id of pool. |

### \_joinStakingPoolAsRbPoolAccount

```solidity
function _joinStakingPoolAsRbPoolAccount(bytes32 _poold, address _rigoblockPoolAccount) internal
```

*Allows caller to join a staking pool as a rigoblock pool account.*

#### Parameters

| Name                   | Type    | Description                                  |
| ---------------------- | ------- | -------------------------------------------- |
| \_poold                | bytes32 | Id of the pool.                              |
| \_rigoblockPoolAccount | address | Address of pool to be added to staking pool. |

### \_assertStakingPoolExists

```solidity
function _assertStakingPoolExists(bytes32 poolId) internal view
```

*Reverts iff a staking pool does not exist.*

#### Parameters

| Name   | Type    | Description        |
| ------ | ------- | ------------------ |
| poolId | bytes32 | Unique id of pool. |

### \_assertStakingPoolDoesNotExist

```solidity
function _assertStakingPoolDoesNotExist(bytes32 poolId) internal view
```

*Reverts iff a staking pool does exist.*

#### Parameters

| Name   | Type    | Description        |
| ------ | ------- | ------------------ |
| poolId | bytes32 | Unique id of pool. |

### \_assertSenderIsPoolOperator

```solidity
function _assertSenderIsPoolOperator(bytes32 poolId) private view
```

*Asserts that the sender is the operator of the input pool.*

#### Parameters

| Name   | Type    | Description                      |
| ------ | ------- | -------------------------------- |
| poolId | bytes32 | Pool sender must be operator of. |

### \_assertDelegateCall

```solidity
function _assertDelegateCall() private view
```

*Preventing direct calls to this contract where applied.*

### \_assertNewOperatorShare

```solidity
function _assertNewOperatorShare(uint32 currentOperatorShare, uint32 newOperatorShare) private pure
```

*Reverts iff the new operator share is invalid.*

#### Parameters

| Name                 | Type   | Description             |
| -------------------- | ------ | ----------------------- |
| currentOperatorShare | uint32 | Current operator share. |
| newOperatorShare     | uint32 | New operator share.     |

## MixinStakingPoolRewards

### withdrawDelegatorRewards

```solidity
function withdrawDelegatorRewards(bytes32 poolId) external
```

Withdraws the caller's GRG rewards that have accumulated until the last epoch.

#### Parameters

| Name   | Type    | Description        |
| ------ | ------- | ------------------ |
| poolId | bytes32 | Unique id of pool. |

### computeRewardBalanceOfOperator

```solidity
function computeRewardBalanceOfOperator(bytes32 poolId) external view returns (uint256 reward)
```

Computes the reward balance in GRG of the operator of a pool.

#### Parameters

| Name   | Type    | Description        |
| ------ | ------- | ------------------ |
| poolId | bytes32 | Unique id of pool. |

#### Return Values

| Name   | Type    | Description     |
| ------ | ------- | --------------- |
| reward | uint256 | Balance in GRG. |

### computeRewardBalanceOfDelegator

```solidity
function computeRewardBalanceOfDelegator(bytes32 poolId, address member) external view returns (uint256 reward)
```

Computes the reward balance in GRG of a specific member of a pool.

#### Parameters

| Name   | Type    | Description             |
| ------ | ------- | ----------------------- |
| poolId | bytes32 | Unique id of pool.      |
| member | address | The member of the pool. |

#### Return Values

| Name   | Type    | Description     |
| ------ | ------- | --------------- |
| reward | uint256 | Balance in GRG. |

### \_withdrawAndSyncDelegatorRewards

```solidity
function _withdrawAndSyncDelegatorRewards(bytes32 poolId, address member) internal
```

*Syncs rewards for a delegator. This includes withdrawing rewards rewards and adding/removing dependencies on cumulative rewards.*

#### Parameters

| Name   | Type    | Description        |
| ------ | ------- | ------------------ |
| poolId | bytes32 | Unique id of pool. |
| member | address | of the pool.       |

### \_syncPoolRewards

```solidity
function _syncPoolRewards(bytes32 poolId, uint256 reward, uint256 membersStake) internal returns (uint256 operatorReward, uint256 membersReward)
```

*Handles a pool's reward at the current epoch. This will split the reward between the operator and members, depositing them into their respective vaults, and update the accounting needed to allow members to withdraw their individual rewards.*

#### Parameters

| Name         | Type    | Description                                                            |
| ------------ | ------- | ---------------------------------------------------------------------- |
| poolId       | bytes32 | Unique Id of pool.                                                     |
| reward       | uint256 | received by the pool.                                                  |
| membersStake | uint256 | the amount of non-operator delegated stake that will split the reward. |

#### Return Values

| Name           | Type    | Description                                     |
| -------------- | ------- | ----------------------------------------------- |
| operatorReward | uint256 | Portion of `reward` given to the pool operator. |
| membersReward  | uint256 | Portion of `reward` given to the pool members.  |

### \_computePoolRewardsSplit

```solidity
function _computePoolRewardsSplit(uint32 operatorShare, uint256 totalReward, uint256 membersStake) internal pure returns (uint256 operatorReward, uint256 membersReward)
```

*Compute the split of a pool reward between the operator and members based on the `operatorShare` and `membersStake`.*

#### Parameters

| Name          | Type    | Description                                                                                           |
| ------------- | ------- | ----------------------------------------------------------------------------------------------------- |
| operatorShare | uint32  | The fraction of rewards owed to the operator, in PPM.                                                 |
| totalReward   | uint256 | The pool reward.                                                                                      |
| membersStake  | uint256 | The amount of member (non-operator) stake delegated to the pool in the epoch the rewards were earned. |

#### Return Values

| Name           | Type    | Description                                          |
| -------------- | ------- | ---------------------------------------------------- |
| operatorReward | uint256 | Portion of `totalReward` given to the pool operator. |
| membersReward  | uint256 | Portion of `totalReward` given to the pool members.  |

### \_computeDelegatorReward

```solidity
function _computeDelegatorReward(bytes32 poolId, address member, uint256 unfinalizedMembersReward, uint256 unfinalizedMembersStake) private view returns (uint256 reward)
```

*Computes the reward balance in ETH of a specific member of a pool.*

#### Parameters

| Name                     | Type    | Description                                |
| ------------------------ | ------- | ------------------------------------------ |
| poolId                   | bytes32 | Unique id of pool.                         |
| member                   | address | of the pool.                               |
| unfinalizedMembersReward | uint256 | Unfinalized total members reward (if any). |
| unfinalizedMembersStake  | uint256 | Unfinalized total members stake (if any).  |

#### Return Values

| Name   | Type    | Description      |
| ------ | ------- | ---------------- |
| reward | uint256 | Balance in WETH. |

### \_computeUnfinalizedDelegatorReward

```solidity
function _computeUnfinalizedDelegatorReward(struct IStructs.StoredBalance delegatedStake, uint256 currentEpoch_, uint256 unfinalizedMembersReward, uint256 unfinalizedMembersStake) private pure returns (uint256)
```

*Computes the unfinalized rewards earned by a delegator in the last epoch.*

#### Parameters

| Name                     | Type                          | Description                                            |
| ------------------------ | ----------------------------- | ------------------------------------------------------ |
| delegatedStake           | struct IStructs.StoredBalance | Amount of stake delegated to pool by a specific staker |
| currentEpoch\_           | uint256                       | The epoch in which this call is executing              |
| unfinalizedMembersReward | uint256                       | Unfinalized total members reward (if any).             |
| unfinalizedMembersStake  | uint256                       | Unfinalized total members stake (if any).              |

#### Return Values

| Name | Type    | Description             |
| ---- | ------- | ----------------------- |
| \[0] | uint256 | reward Balance in WETH. |

### \_increasePoolRewards

```solidity
function _increasePoolRewards(bytes32 poolId, uint256 amount) private
```

*Increases rewards for a pool.*

#### Parameters

| Name   | Type    | Description                     |
| ------ | ------- | ------------------------------- |
| poolId | bytes32 | Unique id of pool.              |
| amount | uint256 | Amount to increment rewards by. |

### \_decreasePoolRewards

```solidity
function _decreasePoolRewards(bytes32 poolId, uint256 amount) private
```

*Decreases rewards for a pool.*

#### Parameters

| Name   | Type    | Description                     |
| ------ | ------- | ------------------------------- |
| poolId | bytes32 | Unique id of pool.              |
| amount | uint256 | Amount to decrement rewards by. |

## MixinAbstract

*Exposes some internal functions from various contracts to avoid cyclical dependencies.*

### \_getUnfinalizedPoolRewards

```solidity
function _getUnfinalizedPoolRewards(bytes32 poolId) internal view virtual returns (uint256 totalReward, uint256 membersStake)
```

*Computes the reward owed to a pool during finalization. Does nothing if the pool is already finalized.*

#### Parameters

| Name   | Type    | Description    |
| ------ | ------- | -------------- |
| poolId | bytes32 | The pool's ID. |

#### Return Values

| Name         | Type    | Description                                                |
| ------------ | ------- | ---------------------------------------------------------- |
| totalReward  | uint256 | The total reward owed to a pool.                           |
| membersStake | uint256 | The total stake for all non-operator members in this pool. |

### \_assertPoolFinalizedLastEpoch

```solidity
function _assertPoolFinalizedLastEpoch(bytes32 poolId) internal view virtual
```

*Asserts that a pool has been finalized last epoch.*

#### Parameters

| Name   | Type    | Description                                         |
| ------ | ------- | --------------------------------------------------- |
| poolId | bytes32 | The id of the pool that should have been finalized. |

## MixinFinalizer

### endEpoch

```solidity
function endEpoch() external returns (uint256 numPoolsToFinalize)
```

Begins a new epoch, preparing the prior one for finalization.

*Throws if not enough time has passed between epochs or if the previous epoch was not fully finalized.*

#### Return Values

| Name               | Type    | Description                      |
| ------------------ | ------- | -------------------------------- |
| numPoolsToFinalize | uint256 | The number of unfinalized pools. |

### finalizePool

```solidity
function finalizePool(bytes32 poolId) external
```

Instantly finalizes a single pool that earned rewards in the previous epoch,

*crediting it rewards for members and withdrawing operator's rewards as GRG. This can be called by internal functions that need to finalize a pool immediately. Does nothing if the pool is already finalized or did not earn rewards in the previous epoch.*

#### Parameters

| Name   | Type    | Description              |
| ------ | ------- | ------------------------ |
| poolId | bytes32 | The pool ID to finalize. |

### \_getUnfinalizedPoolRewards

```solidity
function _getUnfinalizedPoolRewards(bytes32 poolId) internal view virtual returns (uint256 reward, uint256 membersStake)
```

*Computes the reward owed to a pool during finalization. Does nothing if the pool is already finalized.*

#### Parameters

| Name   | Type    | Description    |
| ------ | ------- | -------------- |
| poolId | bytes32 | The pool's ID. |

#### Return Values

| Name         | Type    | Description                                                |
| ------------ | ------- | ---------------------------------------------------------- |
| reward       | uint256 | The total reward owed to a pool.                           |
| membersStake | uint256 | The total stake for all non-operator members in this pool. |

### \_getAvailableGrgBalance

```solidity
function _getAvailableGrgBalance() internal view returns (uint256 grgBalance)
```

*Returns the GRG balance of this contract, minus any GRG that has already been reserved for rewards.*

### \_assertPoolFinalizedLastEpoch

```solidity
function _assertPoolFinalizedLastEpoch(bytes32 poolId) internal view virtual
```

*Asserts that a pool has been finalized last epoch.*

#### Parameters

| Name   | Type    | Description                                         |
| ------ | ------- | --------------------------------------------------- |
| poolId | bytes32 | The id of the pool that should have been finalized. |

### \_getUnfinalizedPoolRewardsFromPoolStats

```solidity
function _getUnfinalizedPoolRewardsFromPoolStats(struct IStructs.PoolStats poolStats, struct IStructs.AggregatedStats aggregatedStats) private view returns (uint256 rewards)
```

*Computes the reward owed to a pool during finalization.*

#### Parameters

| Name            | Type                            | Description                        |
| --------------- | ------------------------------- | ---------------------------------- |
| poolStats       | struct IStructs.PoolStats       | Stats for a specific pool.         |
| aggregatedStats | struct IStructs.AggregatedStats | Stats aggregated across all pools. |

#### Return Values

| Name    | Type    | Description                             |
| ------- | ------- | --------------------------------------- |
| rewards | uint256 | Unfinalized rewards for the input pool. |

## MixinParams

### setParams

```solidity
function setParams(uint256 _epochDurationInSeconds, uint32 _rewardDelegatedStakeWeight, uint256 _minimumPoolStake, uint32 _cobbDouglasAlphaNumerator, uint32 _cobbDouglasAlphaDenominator) external
```

Set all configurable parameters at once.

#### Parameters

| Name                          | Type    | Description                                                     |
| ----------------------------- | ------- | --------------------------------------------------------------- |
| \_epochDurationInSeconds      | uint256 | Minimum seconds between epochs.                                 |
| \_rewardDelegatedStakeWeight  | uint32  | How much delegated stake is weighted vs operator stake, in ppm. |
| \_minimumPoolStake            | uint256 | Minimum amount of stake required in a pool to collect rewards.  |
| \_cobbDouglasAlphaNumerator   | uint32  | Numerator for cobb douglas alpha factor.                        |
| \_cobbDouglasAlphaDenominator | uint32  | Denominator for cobb douglas alpha factor.                      |

### getParams

```solidity
function getParams() external view returns (uint256 _epochDurationInSeconds, uint32 _rewardDelegatedStakeWeight, uint256 _minimumPoolStake, uint32 _cobbDouglasAlphaNumerator, uint32 _cobbDouglasAlphaDenominator)
```

*Retrieves all configurable parameter values.*

#### Return Values

| Name                          | Type    | Description                                                     |
| ----------------------------- | ------- | --------------------------------------------------------------- |
| \_epochDurationInSeconds      | uint256 | Minimum seconds between epochs.                                 |
| \_rewardDelegatedStakeWeight  | uint32  | How much delegated stake is weighted vs operator stake, in ppm. |
| \_minimumPoolStake            | uint256 | Minimum amount of stake required in a pool to collect rewards.  |
| \_cobbDouglasAlphaNumerator   | uint32  | Numerator for cobb douglas alpha factor.                        |
| \_cobbDouglasAlphaDenominator | uint32  | Denominator for cobb douglas alpha factor.                      |

### \_initMixinParams

```solidity
function _initMixinParams() internal
```

*Initialize storage belonging to this mixin.*

### \_assertParamsNotInitialized

```solidity
function _assertParamsNotInitialized() internal view
```

*Asserts that upgradable storage has not yet been initialized.*

### \_setParams

```solidity
function _setParams(uint256 _epochDurationInSeconds, uint32 _rewardDelegatedStakeWeight, uint256 _minimumPoolStake, uint32 _cobbDouglasAlphaNumerator, uint32 _cobbDouglasAlphaDenominator) private
```

*Set all configurable parameters at once.*

#### Parameters

| Name                          | Type    | Description                                                     |
| ----------------------------- | ------- | --------------------------------------------------------------- |
| \_epochDurationInSeconds      | uint256 | Minimum seconds between epochs.                                 |
| \_rewardDelegatedStakeWeight  | uint32  | How much delegated stake is weighted vs operator stake, in ppm. |
| \_minimumPoolStake            | uint256 | Minimum amount of stake required in a pool to collect rewards.  |
| \_cobbDouglasAlphaNumerator   | uint32  | Numerator for cobb douglas alpha factor.                        |
| \_cobbDouglasAlphaDenominator | uint32  | Denominator for cobb douglas alpha factor.                      |

## MixinScheduler

### getCurrentEpochEarliestEndTimeInSeconds

```solidity
function getCurrentEpochEarliestEndTimeInSeconds() public view returns (uint256)
```

Returns the earliest end time in seconds of this epoch.

*The next epoch can begin once this time is reached. Epoch period = \[startTimeInSeconds..endTimeInSeconds)*

#### Return Values

| Name | Type    | Description      |
| ---- | ------- | ---------------- |
| \[0] | uint256 | Time in seconds. |

### \_initMixinScheduler

```solidity
function _initMixinScheduler() internal
```

*Initializes state owned by this mixin. Fails if state was already initialized.*

### \_goToNextEpoch

```solidity
function _goToNextEpoch() internal
```

*Moves to the next epoch, given the current epoch period has ended. Time intervals that are measured in epochs (like timeLocks) are also incremented, given their periods have ended.*

### \_assertSchedulerNotInitialized

```solidity
function _assertSchedulerNotInitialized() internal view
```

*Assert scheduler state before initializing it. This must be updated for each migration.*


# Governance

Governance contracts include:

* deterministic governance proxy factory
* governance proxy
* governance implementation
* Rigoblock governance strategy

### Factory

<figure><img src="/files/1gc2mpmGodi62TudZLrB" alt=""><figcaption><p>Credits: UML diagram generated with <a href="https://github.com/naddison36/sol2uml">SOL2UML</a></p></figcaption></figure>

### Proxy

<figure><img src="/files/aMhgxcbMYE98O7o3EUb0" alt=""><figcaption><p>Credits: UML diagram generated with <a href="https://github.com/naddison36/sol2uml">SOL2UML</a></p></figcaption></figure>

### Implementation

<figure><img src="/files/ajAW6x1MPaPD7S15ZzlR" alt=""><figcaption><p>Credits: UML diagram generated with <a href="https://github.com/naddison36/sol2uml">SOL2UML</a></p></figcaption></figure>

### Rigoblock Strategy

<figure><img src="/files/d9hVLAf8KgqDgBTdnDuE" alt=""><figcaption><p>Credits: UML diagram generated with <a href="https://github.com/naddison36/sol2uml">SOL2UML</a></p></figcaption></figure>


# Solidity API

## IRigoblockGovernance

## RigoblockGovernance

### constructor

```solidity
constructor() public
```

Constructor has no inputs to guarantee same deterministic address across chains.

*Setting high proposal threshold locks propose action, which also lock vote actions.*

## IGovernanceStrategy

### assertValidInitParams

```solidity
function assertValidInitParams(struct IRigoblockGovernanceFactory.Parameters params) external view
```

Reverts if initialization paramters are incorrect.

*Only used at initialization, as params deleted from factory storage after setup.*

#### Parameters

| Name   | Type                                          | Description                  |
| ------ | --------------------------------------------- | ---------------------------- |
| params | struct IRigoblockGovernanceFactory.Parameters | Tuple of factory parameters. |

### assertValidThresholds

```solidity
function assertValidThresholds(uint256 proposalThreshold, uint256 quorumThreshold) external view
```

Reverts if thresholds are incorrect.

#### Parameters

| Name              | Type    | Description                                         |
| ----------------- | ------- | --------------------------------------------------- |
| proposalThreshold | uint256 | Number of votes required to make a proposal.        |
| quorumThreshold   | uint256 | Number of votes required for a proposal to succeed. |

### getProposalState

```solidity
function getProposalState(struct IGovernanceState.Proposal proposal, uint256 minimumQuorum) external view returns (enum IGovernanceState.ProposalState)
```

Returns the state of a proposal for a required quorum.

#### Parameters

| Name          | Type                             | Description                                      |
| ------------- | -------------------------------- | ------------------------------------------------ |
| proposal      | struct IGovernanceState.Proposal | Tuple of the proposal.                           |
| minimumQuorum | uint256                          | Number of votes required for a proposal to pass. |

#### Return Values

| Name | Type                                | Description                  |
| ---- | ----------------------------------- | ---------------------------- |
| \[0] | enum IGovernanceState.ProposalState | Tuple of the proposal state. |

### votingPeriod

```solidity
function votingPeriod() external view returns (uint256)
```

Return the voting period.

#### Return Values

| Name | Type    | Description                           |
| ---- | ------- | ------------------------------------- |
| \[0] | uint256 | Number of seconds of period duration. |

### votingTimestamps

```solidity
function votingTimestamps() external view returns (uint256 startBlockOrTime, uint256 endBlockOrTime)
```

Returns the voting timestamps.

#### Return Values

| Name             | Type    | Description                     |
| ---------------- | ------- | ------------------------------- |
| startBlockOrTime | uint256 | Timestamp when proposal starts. |
| endBlockOrTime   | uint256 | Timestamp when voting ends.     |

### getVotingPower

```solidity
function getVotingPower(address account) external view returns (uint256)
```

Return a user's voting power.

#### Parameters

| Name    | Type    | Description                 |
| ------- | ------- | --------------------------- |
| account | address | Address to check votes for. |

## IRigoblockGovernanceFactory

### GovernanceCreated

```solidity
event GovernanceCreated(address governance)
```

Emitted when a governance is created.

#### Parameters

| Name       | Type    | Description                      |
| ---------- | ------- | -------------------------------- |
| governance | address | Address of the governance proxy. |

### createGovernance

```solidity
function createGovernance(address implementation, address governanceStrategy, uint256 proposalThreshold, uint256 quorumThreshold, enum IGovernanceState.TimeType timeType, string name) external returns (address governance)
```

Creates a new governance proxy.

#### Parameters

| Name               | Type                           | Description                                           |
| ------------------ | ------------------------------ | ----------------------------------------------------- |
| implementation     | address                        | Address of the governance implementation contract.    |
| governanceStrategy | address                        | Address of the voting strategy.                       |
| proposalThreshold  | uint256                        | Number of votes required for creating a new proposal. |
| quorumThreshold    | uint256                        | Number of votes required for execution.               |
| timeType           | enum IGovernanceState.TimeType | Enum of time type (block number or timestamp).        |
| name               | string                         | Human readable string of the name.                    |

#### Return Values

| Name       | Type    | Description                    |
| ---------- | ------- | ------------------------------ |
| governance | address | Address of the new governance. |

### Parameters

```solidity
struct Parameters {
  address implementation;
  address governanceStrategy;
  uint256 proposalThreshold;
  uint256 quorumThreshold;
  enum IGovernanceState.TimeType timeType;
  string name;
}
```

### parameters

```solidity
function parameters() external view returns (struct IRigoblockGovernanceFactory.Parameters)
```

Returns the governance initialization parameters at proxy deploy.

#### Return Values

| Name | Type                                          | Description                         |
| ---- | --------------------------------------------- | ----------------------------------- |
| \[0] | struct IRigoblockGovernanceFactory.Parameters | Tuple of the governance parameters. |

## IGovernanceEvents

### ProposalCreated

```solidity
event ProposalCreated(address proposer, uint256 proposalId, struct IGovernanceVoting.ProposedAction[] actions, uint256 startBlockOrTime, uint256 endBlockOrTime, string description)
```

Emitted when a new proposal is created.

#### Parameters

| Name             | Type                                       | Description                                                |
| ---------------- | ------------------------------------------ | ---------------------------------------------------------- |
| proposer         | address                                    | Address of the proposer.                                   |
| proposalId       | uint256                                    | Number of the proposal.                                    |
| actions          | struct IGovernanceVoting.ProposedAction\[] | Struct array of actions (targets, datas, values).          |
| startBlockOrTime | uint256                                    | Timestamp in seconds after which proposal can be voted on. |
| endBlockOrTime   | uint256                                    | Timestamp in seconds after which proposal can be executed. |
| description      | string                                     | String description of proposal.                            |

### ProposalExecuted

```solidity
event ProposalExecuted(uint256 proposalId)
```

Emitted when a proposal is executed.

#### Parameters

| Name       | Type    | Description             |
| ---------- | ------- | ----------------------- |
| proposalId | uint256 | Number of the proposal. |

### StrategyUpgraded

```solidity
event StrategyUpgraded(address newStrategy)
```

Emmited when the governance strategy is upgraded.

#### Parameters

| Name        | Type    | Description                           |
| ----------- | ------- | ------------------------------------- |
| newStrategy | address | Address of the new strategy contract. |

### ThresholdsUpdated

```solidity
event ThresholdsUpdated(uint256 proposalThreshold, uint256 quorumThreshold)
```

Emitted when voting thresholds get updated.

*Only governance can update thresholds.*

#### Parameters

| Name              | Type    | Description                                     |
| ----------------- | ------- | ----------------------------------------------- |
| proposalThreshold | uint256 | Number of votes required to add a proposal.     |
| quorumThreshold   | uint256 | Number of votes required to execute a proposal. |

### Upgraded

```solidity
event Upgraded(address newImplementation)
```

Emitted when implementation written to proxy storage.

*Emitted also at first variable initialization.*

#### Parameters

| Name              | Type    | Description                        |
| ----------------- | ------- | ---------------------------------- |
| newImplementation | address | Address of the new implementation. |

### VoteCast

```solidity
event VoteCast(address voter, uint256 proposalId, enum IGovernanceVoting.VoteType voteType, uint256 votingPower)
```

Emitted when a voter votes.

#### Parameters

| Name        | Type                            | Description             |
| ----------- | ------------------------------- | ----------------------- |
| voter       | address                         | Address of the voter.   |
| proposalId  | uint256                         | Number of the proposal. |
| voteType    | enum IGovernanceVoting.VoteType | Number of vote type.    |
| votingPower | uint256                         | Number of votes.        |

## IGovernanceInitializer

### initializeGovernance

```solidity
function initializeGovernance() external
```

Initializes the Rigoblock Governance.

*Params are stored in factory and read from there.*

## IGovernanceState

### ProposalState

```solidity
enum ProposalState {
  Pending,
  Active,
  Canceled,
  Qualified,
  Defeated,
  Succeeded,
  Queued,
  Expired,
  Executed
}
```

### TimeType

```solidity
enum TimeType {
  Blocknumber,
  Timestamp
}
```

### Proposal

```solidity
struct Proposal {
  uint256 actionsLength;
  uint256 startBlockOrTime;
  uint256 endBlockOrTime;
  uint256 votesFor;
  uint256 votesAgainst;
  uint256 votesAbstain;
  bool executed;
}
```

### ProposalWrapper

```solidity
struct ProposalWrapper {
  struct IGovernanceState.Proposal proposal;
  struct IGovernanceVoting.ProposedAction[] proposedAction;
}
```

### getActions

```solidity
function getActions(uint256 proposalId) external view returns (struct IGovernanceVoting.ProposedAction[] proposedActions)
```

Returns the actions proposed for a given proposal.

#### Parameters

| Name       | Type    | Description             |
| ---------- | ------- | ----------------------- |
| proposalId | uint256 | Number of the proposal. |

#### Return Values

| Name            | Type                                       | Description                         |
| --------------- | ------------------------------------------ | ----------------------------------- |
| proposedActions | struct IGovernanceVoting.ProposedAction\[] | Array of tuple of proposed actions. |

### getProposalById

```solidity
function getProposalById(uint256 proposalId) external view returns (struct IGovernanceState.ProposalWrapper proposalWrapper)
```

Returns a proposal for a given id.

#### Parameters

| Name       | Type    | Description                 |
| ---------- | ------- | --------------------------- |
| proposalId | uint256 | The number of the proposal. |

#### Return Values

| Name            | Type                                    | Description                                                |
| --------------- | --------------------------------------- | ---------------------------------------------------------- |
| proposalWrapper | struct IGovernanceState.ProposalWrapper | Tuple wrapper of the proposal and proposed actions tuples. |

### getProposalState

```solidity
function getProposalState(uint256 proposalId) external view returns (enum IGovernanceState.ProposalState)
```

Returns the state of a proposal.

#### Parameters

| Name       | Type    | Description             |
| ---------- | ------- | ----------------------- |
| proposalId | uint256 | Number of the proposal. |

#### Return Values

| Name | Type                                | Description               |
| ---- | ----------------------------------- | ------------------------- |
| \[0] | enum IGovernanceState.ProposalState | Number of proposal state. |

### Receipt

```solidity
struct Receipt {
  bool hasVoted;
  uint96 votes;
  enum IGovernanceVoting.VoteType voteType;
}
```

### getReceipt

```solidity
function getReceipt(uint256 proposalId, address voter) external view returns (struct IGovernanceState.Receipt)
```

Returns the receipt of a voter for a given proposal.

#### Parameters

| Name       | Type    | Description             |
| ---------- | ------- | ----------------------- |
| proposalId | uint256 | Number of the proposal. |
| voter      | address | Address of the voter.   |

#### Return Values

| Name | Type                            | Description             |
| ---- | ------------------------------- | ----------------------- |
| \[0] | struct IGovernanceState.Receipt | Tuple of voter receipt. |

### getVotingPower

```solidity
function getVotingPower(address account) external view returns (uint256 votingPower)
```

Computes the current voting power of the given account.

#### Parameters

| Name    | Type    | Description                 |
| ------- | ------- | --------------------------- |
| account | address | The address of the account. |

#### Return Values

| Name        | Type    | Description                                    |
| ----------- | ------- | ---------------------------------------------- |
| votingPower | uint256 | The current voting power of the given account. |

### GovernanceParameters

```solidity
struct GovernanceParameters {
  address strategy;
  uint256 proposalThreshold;
  uint256 quorumThreshold;
  enum IGovernanceState.TimeType timeType;
}
```

### EnhancedParams

```solidity
struct EnhancedParams {
  struct IGovernanceState.GovernanceParameters params;
  string name;
  string version;
}
```

### governanceParameters

```solidity
function governanceParameters() external view returns (struct IGovernanceState.EnhancedParams)
```

Returns the governance parameters.

#### Return Values

| Name | Type                                   | Description                         |
| ---- | -------------------------------------- | ----------------------------------- |
| \[0] | struct IGovernanceState.EnhancedParams | Tuple of the governance parameters. |

### name

```solidity
function name() external view returns (string)
```

Returns the name of the governace.

#### Return Values

| Name | Type   | Description                        |
| ---- | ------ | ---------------------------------- |
| \[0] | string | Human readable string of the name. |

### proposalCount

```solidity
function proposalCount() external view returns (uint256 count)
```

Returns the total number of proposals.

#### Return Values

| Name  | Type    | Description              |
| ----- | ------- | ------------------------ |
| count | uint256 | The number of proposals. |

### proposals

```solidity
function proposals() external view returns (struct IGovernanceState.ProposalWrapper[] proposalWrapper)
```

Returns all proposals ever made to the governance.

#### Return Values

| Name            | Type                                       | Description                              |
| --------------- | ------------------------------------------ | ---------------------------------------- |
| proposalWrapper | struct IGovernanceState.ProposalWrapper\[] | Tuple array of all governance proposals. |

### votingPeriod

```solidity
function votingPeriod() external view returns (uint256)
```

Returns the voting period.

#### Return Values

| Name | Type    | Description                  |
| ---- | ------- | ---------------------------- |
| \[0] | uint256 | Number of blocks or seconds. |

## IGovernanceUpgrade

### updateThresholds

```solidity
function updateThresholds(uint256 newProposalThreshold, uint256 newQuorumThreshold) external
```

Updates the proposal and quorum thresholds to the given values.

*Only callable by the governance contract itself. Thresholds can only be updated via a successful governance proposal.*

#### Parameters

| Name                 | Type    | Description                               |
| -------------------- | ------- | ----------------------------------------- |
| newProposalThreshold | uint256 | The new value for the proposal threshold. |
| newQuorumThreshold   | uint256 | The new value for the quorum threshold.   |

### upgradeImplementation

```solidity
function upgradeImplementation(address newImplementation) external
```

Updates the governance implementation address.

*Only callable after successful voting.*

#### Parameters

| Name              | Type    | Description                                            |
| ----------------- | ------- | ------------------------------------------------------ |
| newImplementation | address | Address of the new governance implementation contract. |

### upgradeStrategy

```solidity
function upgradeStrategy(address newStrategy) external
```

Updates the governance strategy plugin.

*Only callable by the governance contract itself.*

#### Parameters

| Name        | Type    | Description                           |
| ----------- | ------- | ------------------------------------- |
| newStrategy | address | Address of the new strategy contract. |

## IGovernanceVoting

### VoteType

```solidity
enum VoteType {
  For,
  Against,
  Abstain
}
```

### castVote

```solidity
function castVote(uint256 proposalId, enum IGovernanceVoting.VoteType voteType) external
```

Casts a vote for the given proposal.

*Only callable during the voting period for that proposal. One address can only vote once.*

#### Parameters

| Name       | Type                            | Description                                 |
| ---------- | ------------------------------- | ------------------------------------------- |
| proposalId | uint256                         | The ID of the proposal to vote on.          |
| voteType   | enum IGovernanceVoting.VoteType | Whether to support, not support or abstain. |

### castVoteBySignature

```solidity
function castVoteBySignature(uint256 proposalId, enum IGovernanceVoting.VoteType voteType, uint8 v, bytes32 r, bytes32 s) external
```

Casts a vote for the given proposal, by signature.

*Only callable during the voting period for that proposal. One voter can only vote once.*

#### Parameters

| Name       | Type                            | Description                                 |
| ---------- | ------------------------------- | ------------------------------------------- |
| proposalId | uint256                         | The ID of the proposal to vote on.          |
| voteType   | enum IGovernanceVoting.VoteType | Whether to support, not support or abstain. |
| v          | uint8                           | the v field of the signature.               |
| r          | bytes32                         | the r field of the signature.               |
| s          | bytes32                         | the s field of the signature.               |

### execute

```solidity
function execute(uint256 proposalId) external payable
```

Executes a proposal that has passed and is currently executable.

#### Parameters

| Name       | Type    | Description                        |
| ---------- | ------- | ---------------------------------- |
| proposalId | uint256 | The ID of the proposal to execute. |

### ProposedAction

```solidity
struct ProposedAction {
  address target;
  bytes data;
  uint256 value;
}
```

### propose

```solidity
function propose(struct IGovernanceVoting.ProposedAction[] actions, string description) external returns (uint256 proposalId)
```

Creates a proposal on the the given actions. Must have at least `proposalThreshold`.

*Must have at least `proposalThreshold` of voting power to call this function.*

#### Parameters

| Name        | Type                                       | Description                                                |
| ----------- | ------------------------------------------ | ---------------------------------------------------------- |
| actions     | struct IGovernanceVoting.ProposedAction\[] | The proposed actions. An action specifies a contract call. |
| description | string                                     | A text description for the proposal.                       |

#### Return Values

| Name       | Type    | Description                           |
| ---------- | ------- | ------------------------------------- |
| proposalId | uint256 | The ID of the newly created proposal. |

## MixinAbstract

### \_getProposalCount

```solidity
function _getProposalCount() internal view virtual returns (uint256)
```

### \_getProposalState

```solidity
function _getProposalState(uint256 proposalId) internal view virtual returns (enum IGovernanceState.ProposalState)
```

### \_getVotingPower

```solidity
function _getVotingPower(address account) internal view virtual returns (uint256)
```

## MixinConstants

Constants are copied in the bytecode and not assigned a storage slot, can safely be added to this contract.

### VERSION

```solidity
string VERSION
```

Contract version

### PROPOSAL\_MAX\_OPERATIONS

```solidity
uint256 PROPOSAL_MAX_OPERATIONS
```

Maximum operations per proposal

### DOMAIN\_TYPEHASH

```solidity
bytes32 DOMAIN_TYPEHASH
```

The EIP-712 typehash for the contract's domain

### VOTE\_TYPEHASH

```solidity
bytes32 VOTE_TYPEHASH
```

The EIP-712 typehash for the vote struct

### \_GOVERNANCE\_PARAMS\_SLOT

```solidity
bytes32 _GOVERNANCE_PARAMS_SLOT
```

### \_IMPLEMENTATION\_SLOT

```solidity
bytes32 _IMPLEMENTATION_SLOT
```

### \_NAME\_SLOT

```solidity
bytes32 _NAME_SLOT
```

### \_PROPOSAL\_SLOT

```solidity
bytes32 _PROPOSAL_SLOT
```

### \_PROPOSAL\_COUNT\_SLOT

```solidity
bytes32 _PROPOSAL_COUNT_SLOT
```

### \_PROPOSED\_ACTION\_SLOT

```solidity
bytes32 _PROPOSED_ACTION_SLOT
```

### \_RECEIPT\_SLOT

```solidity
bytes32 _RECEIPT_SLOT
```

## MixinImmutables

Immutables are copied in the bytecode and not assigned a storage slot

*New immutables can safely be added to this contract without ordering.*

### constructor

```solidity
constructor() internal
```

## MixinInitializer

### onlyUninitialized

```solidity
modifier onlyUninitialized()
```

### initializeGovernance

```solidity
function initializeGovernance() external
```

Initializes the Rigoblock Governance.

*Params are stored in factory and read from there.*

## MixinState

### getActions

```solidity
function getActions(uint256 proposalId) external view returns (struct IGovernanceVoting.ProposedAction[] proposedActions)
```

Returns the actions proposed for a given proposal.

#### Parameters

| Name       | Type    | Description             |
| ---------- | ------- | ----------------------- |
| proposalId | uint256 | Number of the proposal. |

#### Return Values

| Name            | Type                                       | Description                         |
| --------------- | ------------------------------------------ | ----------------------------------- |
| proposedActions | struct IGovernanceVoting.ProposedAction\[] | Array of tuple of proposed actions. |

### getProposalState

```solidity
function getProposalState(uint256 proposalId) external view returns (enum IGovernanceState.ProposalState)
```

Returns the state of a proposal.

#### Parameters

| Name       | Type    | Description             |
| ---------- | ------- | ----------------------- |
| proposalId | uint256 | Number of the proposal. |

#### Return Values

| Name | Type                                | Description               |
| ---- | ----------------------------------- | ------------------------- |
| \[0] | enum IGovernanceState.ProposalState | Number of proposal state. |

### getReceipt

```solidity
function getReceipt(uint256 proposalId, address voter) external view returns (struct IGovernanceState.Receipt)
```

Returns the receipt of a voter for a given proposal.

#### Parameters

| Name       | Type    | Description             |
| ---------- | ------- | ----------------------- |
| proposalId | uint256 | Number of the proposal. |
| voter      | address | Address of the voter.   |

#### Return Values

| Name | Type                            | Description             |
| ---- | ------------------------------- | ----------------------- |
| \[0] | struct IGovernanceState.Receipt | Tuple of voter receipt. |

### getVotingPower

```solidity
function getVotingPower(address account) external view returns (uint256)
```

Computes the current voting power of the given account.

#### Parameters

| Name    | Type    | Description                 |
| ------- | ------- | --------------------------- |
| account | address | The address of the account. |

#### Return Values

| Name | Type    | Description |
| ---- | ------- | ----------- |
| \[0] | uint256 |             |

### governanceParameters

```solidity
function governanceParameters() external view returns (struct IGovernanceState.EnhancedParams)
```

Returns the governance parameters.

#### Return Values

| Name | Type                                   | Description                         |
| ---- | -------------------------------------- | ----------------------------------- |
| \[0] | struct IGovernanceState.EnhancedParams | Tuple of the governance parameters. |

### name

```solidity
function name() external view returns (string)
```

Returns the name of the governace.

#### Return Values

| Name | Type   | Description                        |
| ---- | ------ | ---------------------------------- |
| \[0] | string | Human readable string of the name. |

### proposalCount

```solidity
function proposalCount() external view returns (uint256 count)
```

Returns the total number of proposals.

#### Return Values

| Name  | Type    | Description              |
| ----- | ------- | ------------------------ |
| count | uint256 | The number of proposals. |

### proposals

```solidity
function proposals() external view returns (struct IGovernanceState.ProposalWrapper[] proposalWrapper)
```

Returns all proposals ever made to the governance.

#### Return Values

| Name            | Type                                       | Description                              |
| --------------- | ------------------------------------------ | ---------------------------------------- |
| proposalWrapper | struct IGovernanceState.ProposalWrapper\[] | Tuple array of all governance proposals. |

### votingPeriod

```solidity
function votingPeriod() external view returns (uint256)
```

Returns the voting period.

#### Return Values

| Name | Type    | Description                  |
| ---- | ------- | ---------------------------- |
| \[0] | uint256 | Number of blocks or seconds. |

### getProposalById

```solidity
function getProposalById(uint256 proposalId) public view returns (struct IGovernanceState.ProposalWrapper proposalWrapper)
```

Returns a proposal for a given id.

#### Parameters

| Name       | Type    | Description                 |
| ---------- | ------- | --------------------------- |
| proposalId | uint256 | The number of the proposal. |

#### Return Values

| Name            | Type                                    | Description                                                |
| --------------- | --------------------------------------- | ---------------------------------------------------------- |
| proposalWrapper | struct IGovernanceState.ProposalWrapper | Tuple wrapper of the proposal and proposed actions tuples. |

### \_getProposalCount

```solidity
function _getProposalCount() internal view returns (uint256 count)
```

### \_getProposalState

```solidity
function _getProposalState(uint256 proposalId) internal view returns (enum IGovernanceState.ProposalState)
```

### \_getVotingPower

```solidity
function _getVotingPower(address account) internal view returns (uint256)
```

## MixinStorage

### constructor

```solidity
constructor() internal
```

### \_governanceParameters

```solidity
function _governanceParameters() internal pure returns (struct IGovernanceState.GovernanceParameters s)
```

### AddressSlot

```solidity
struct AddressSlot {
  address value;
}
```

### \_implementation

```solidity
function _implementation() internal pure returns (struct MixinStorage.AddressSlot s)
```

### StringSlot

```solidity
struct StringSlot {
  string value;
}
```

### \_name

```solidity
function _name() internal pure returns (struct MixinStorage.StringSlot s)
```

### ParamsWrapper

```solidity
struct ParamsWrapper {
  struct IGovernanceState.GovernanceParameters governanceParameters;
}
```

### \_paramsWrapper

```solidity
function _paramsWrapper() internal pure returns (struct MixinStorage.ParamsWrapper s)
```

### UintSlot

```solidity
struct UintSlot {
  uint256 value;
}
```

### \_proposalCount

```solidity
function _proposalCount() internal pure returns (struct MixinStorage.UintSlot s)
```

### ProposalByIndex

```solidity
struct ProposalByIndex {
  mapping(uint256 => struct IGovernanceState.Proposal) proposalById;
}
```

### \_proposal

```solidity
function _proposal() internal pure returns (struct MixinStorage.ProposalByIndex s)
```

### ActionByIndex

```solidity
struct ActionByIndex {
  mapping(uint256 => mapping(uint256 => struct IGovernanceVoting.ProposedAction)) proposedActionbyIndex;
}
```

### \_proposedAction

```solidity
function _proposedAction() internal pure returns (struct MixinStorage.ActionByIndex s)
```

### UserReceipt

```solidity
struct UserReceipt {
  mapping(uint256 => mapping(address => struct IGovernanceState.Receipt)) userReceiptByProposal;
}
```

### \_receipt

```solidity
function _receipt() internal pure returns (struct MixinStorage.UserReceipt s)
```

## MixinUpgrade

### onlyGovernance

```solidity
modifier onlyGovernance()
```

### updateThresholds

```solidity
function updateThresholds(uint256 newProposalThreshold, uint256 newQuorumThreshold) external
```

Updates the proposal and quorum thresholds to the given values.

*Only callable by the governance contract itself. Thresholds can only be updated via a successful governance proposal.*

#### Parameters

| Name                 | Type    | Description                               |
| -------------------- | ------- | ----------------------------------------- |
| newProposalThreshold | uint256 | The new value for the proposal threshold. |
| newQuorumThreshold   | uint256 | The new value for the quorum threshold.   |

### upgradeImplementation

```solidity
function upgradeImplementation(address newImplementation) external
```

Updates the governance implementation address.

*Only callable after successful voting.*

#### Parameters

| Name              | Type    | Description                                            |
| ----------------- | ------- | ------------------------------------------------------ |
| newImplementation | address | Address of the new governance implementation contract. |

### upgradeStrategy

```solidity
function upgradeStrategy(address newStrategy) external
```

Updates the governance strategy plugin.

*Only callable by the governance contract itself.*

#### Parameters

| Name        | Type    | Description                           |
| ----------- | ------- | ------------------------------------- |
| newStrategy | address | Address of the new strategy contract. |

### \_isContract

```solidity
function _isContract(address target) private view returns (bool)
```

*Returns whether an address is a contract.*

#### Return Values

| Name | Type | Description                   |
| ---- | ---- | ----------------------------- |
| \[0] | bool | Bool target address has code. |

## MixinVoting

### propose

```solidity
function propose(struct IGovernanceVoting.ProposedAction[] actions, string description) external returns (uint256 proposalId)
```

Creates a proposal on the the given actions. Must have at least `proposalThreshold`.

*Must have at least `proposalThreshold` of voting power to call this function.*

#### Parameters

| Name        | Type                                       | Description                                                |
| ----------- | ------------------------------------------ | ---------------------------------------------------------- |
| actions     | struct IGovernanceVoting.ProposedAction\[] | The proposed actions. An action specifies a contract call. |
| description | string                                     | A text description for the proposal.                       |

#### Return Values

| Name       | Type    | Description                           |
| ---------- | ------- | ------------------------------------- |
| proposalId | uint256 | The ID of the newly created proposal. |

### castVote

```solidity
function castVote(uint256 proposalId, enum IGovernanceVoting.VoteType voteType) external
```

Casts a vote for the given proposal.

*Only callable during the voting period for that proposal. One address can only vote once.*

#### Parameters

| Name       | Type                            | Description                                 |
| ---------- | ------------------------------- | ------------------------------------------- |
| proposalId | uint256                         | The ID of the proposal to vote on.          |
| voteType   | enum IGovernanceVoting.VoteType | Whether to support, not support or abstain. |

### castVoteBySignature

```solidity
function castVoteBySignature(uint256 proposalId, enum IGovernanceVoting.VoteType voteType, uint8 v, bytes32 r, bytes32 s) external
```

Casts a vote for the given proposal, by signature.

*Only callable during the voting period for that proposal. One voter can only vote once.*

#### Parameters

| Name       | Type                            | Description                                 |
| ---------- | ------------------------------- | ------------------------------------------- |
| proposalId | uint256                         | The ID of the proposal to vote on.          |
| voteType   | enum IGovernanceVoting.VoteType | Whether to support, not support or abstain. |
| v          | uint8                           | the v field of the signature.               |
| r          | bytes32                         | the r field of the signature.               |
| s          | bytes32                         | the s field of the signature.               |

### execute

```solidity
function execute(uint256 proposalId) external payable
```

Executes a proposal that has passed and is currently executable.

#### Parameters

| Name       | Type    | Description                        |
| ---------- | ------- | ---------------------------------- |
| proposalId | uint256 | The ID of the proposal to execute. |

### \_castVote

```solidity
function _castVote(address voter, uint256 proposalId, enum IGovernanceVoting.VoteType voteType) private
```

Casts a vote for the given proposal.

*Only callable during the voting period for that proposal.*

## RigoblockGovernanceFactory

### \_parameters

```solidity
struct IRigoblockGovernanceFactory.Parameters _parameters
```

### createGovernance

```solidity
function createGovernance(address implementation, address governanceStrategy, uint256 proposalThreshold, uint256 quorumThreshold, enum IGovernanceState.TimeType timeType, string name) external returns (address governance)
```

Creates a new governance proxy.

#### Parameters

| Name               | Type                           | Description                                           |
| ------------------ | ------------------------------ | ----------------------------------------------------- |
| implementation     | address                        | Address of the governance implementation contract.    |
| governanceStrategy | address                        | Address of the voting strategy.                       |
| proposalThreshold  | uint256                        | Number of votes required for creating a new proposal. |
| quorumThreshold    | uint256                        | Number of votes required for execution.               |
| timeType           | enum IGovernanceState.TimeType | Enum of time type (block number or timestamp).        |
| name               | string                         | Human readable string of the name.                    |

#### Return Values

| Name       | Type    | Description                    |
| ---------- | ------- | ------------------------------ |
| governance | address | Address of the new governance. |

### parameters

```solidity
function parameters() external view returns (struct IRigoblockGovernanceFactory.Parameters)
```

Returns the governance initialization parameters at proxy deploy.

#### Return Values

| Name | Type                                          | Description                         |
| ---- | --------------------------------------------- | ----------------------------------- |
| \[0] | struct IRigoblockGovernanceFactory.Parameters | Tuple of the governance parameters. |

### \_isContract

```solidity
function _isContract(address target) private view returns (bool)
```

*Returns whether an address is a contract.*

#### Return Values

| Name | Type | Description                   |
| ---- | ---- | ----------------------------- |
| \[0] | bool | Bool target address has code. |

## RigoblockGovernanceProxy

### Upgraded

```solidity
event Upgraded(address newImplementation)
```

Emitted when implementation written to proxy storage.

*Emitted also at first variable initialization.*

#### Parameters

| Name              | Type    | Description                        |
| ----------------- | ------- | ---------------------------------- |
| newImplementation | address | Address of the new implementation. |

### \_IMPLEMENTATION\_SLOT

```solidity
bytes32 _IMPLEMENTATION_SLOT
```

### constructor

```solidity
constructor() public payable
```

Sets address of implementation contract.

### fallback

```solidity
fallback() external payable
```

Fallback function forwards all transactions and returns all received return data.

### receive

```solidity
receive() external payable
```

Allows this contract to receive ether.

### ImplementationSlot

```solidity
struct ImplementationSlot {
  address implementation;
}
```

### \_getImplementation

```solidity
function _getImplementation() private pure returns (struct RigoblockGovernanceProxy.ImplementationSlot s)
```

Method to read/write from/to implementation slot.

#### Return Values

| Name | Type                                               | Description                                    |
| ---- | -------------------------------------------------- | ---------------------------------------------- |
| s    | struct RigoblockGovernanceProxy.ImplementationSlot | Storage slot of the governance implementation. |

## RigoblockGovernanceStrategy

### \_stakingProxy

```solidity
address _stakingProxy
```

### \_votingPeriod

```solidity
uint256 _votingPeriod
```

### constructor

```solidity
constructor(address stakingProxy) public
```

### assertValidInitParams

```solidity
function assertValidInitParams(struct IRigoblockGovernanceFactory.Parameters params) external view
```

Reverts if initialization paramters are incorrect.

*Only used at initialization, as params deleted from factory storage after setup.*

#### Parameters

| Name   | Type                                          | Description                  |
| ------ | --------------------------------------------- | ---------------------------- |
| params | struct IRigoblockGovernanceFactory.Parameters | Tuple of factory parameters. |

### assertValidThresholds

```solidity
function assertValidThresholds(uint256 proposalThreshold, uint256 quorumThreshold) public view
```

Reverts if thresholds are incorrect.

#### Parameters

| Name              | Type    | Description                                         |
| ----------------- | ------- | --------------------------------------------------- |
| proposalThreshold | uint256 | Number of votes required to make a proposal.        |
| quorumThreshold   | uint256 | Number of votes required for a proposal to succeed. |

### getProposalState

```solidity
function getProposalState(struct IGovernanceState.Proposal proposal, uint256 minimumQuorum) external view returns (enum IGovernanceState.ProposalState)
```

Returns the state of a proposal for a required quorum.

#### Parameters

| Name          | Type                             | Description                                      |
| ------------- | -------------------------------- | ------------------------------------------------ |
| proposal      | struct IGovernanceState.Proposal | Tuple of the proposal.                           |
| minimumQuorum | uint256                          | Number of votes required for a proposal to pass. |

#### Return Values

| Name | Type                                | Description                  |
| ---- | ----------------------------------- | ---------------------------- |
| \[0] | enum IGovernanceState.ProposalState | Tuple of the proposal state. |

### \_qualifiedConsensus

```solidity
function _qualifiedConsensus(struct IGovernanceState.Proposal proposal, uint256 minimumQuorum) private view returns (bool)
```

### getVotingPower

```solidity
function getVotingPower(address account) public view returns (uint256)
```

Return a user's voting power.

#### Parameters

| Name    | Type    | Description                 |
| ------- | ------- | --------------------------- |
| account | address | Address to check votes for. |

### votingPeriod

```solidity
function votingPeriod() public view returns (uint256)
```

Return the voting period.

#### Return Values

| Name | Type    | Description                           |
| ---- | ------- | ------------------------------------- |
| \[0] | uint256 | Number of seconds of period duration. |

### votingTimestamps

```solidity
function votingTimestamps() public view returns (uint256 startBlockOrTime, uint256 endBlockOrTime)
```

Returns the voting timestamps.

#### Return Values

| Name             | Type    | Description                     |
| ---------------- | ------- | ------------------------------- |
| startBlockOrTime | uint256 | Timestamp when proposal starts. |
| endBlockOrTime   | uint256 | Timestamp when voting ends.     |

### \_assertValidProposalThreshold

```solidity
function _assertValidProposalThreshold(uint256 proposalThreshold) private view
```

### \_assertValidQuorumThreshold

```solidity
function _assertValidQuorumThreshold(uint256 quorumThreshold) private view
```

### \_getStakingProxy

```solidity
function _getStakingProxy() private view returns (address)
```

It is more gas efficient at deploy to reading immutable from internal method.


# x402 v2 Payment Flow

1. Make a request → server responds `402 Payment Required` and may include a `PAYMENT-REQUIRED` header describing accepted payment requirements
2. Create the payment payload for USDC on Base (chain 8453), typically with `@x402/core`
3. Retry with the `X-Payment` header → receive structured data; successful 2xx responses may include a `PAYMENT-RESPONSE` settlement receipt

**Use the** [**@x402/core**](https://www.npmjs.com/package/@x402/core) **SDK** — it handles payment flow automatically.

**Payment:** USDC on Base (eip155:8453) — CDP facilitator at api.cdp.coinbase.com

**Integration guide & agent-to-agent architecture:** <https://github.com/RigoBlock/agentic-operator/blob/main/AGENTS.md>

**Supported chains:** Ethereum (1), Base (8453), Arbitrum (42161), Optimism (10), Polygon (137), BNB (56), Unichain (130)


# Quotes

DEX price quotes — no wallet or vault context required

## Get DEX swap quote

> Returns a swap quote sourced from Uniswap liquidity for a given token pair and amount on any of the 7 supported chains. No vault, wallet, or operator context required — any agent can call this endpoint with a $0.0020 USDC payment.\
> \
> \*\*Price:\*\* $0.0020 USDC per request (x402, eip155:8453)\
> \
> \*\*Typical use:\*\* Price discovery, trade sizing, yield comparison, arbitrage detection.\
> \
> \*\*Example:\*\* \`GET /api/quote?sell=ETH\&buy=USDC\&amount=1\&chain=base\`

```json
{"openapi":"3.1.0","info":{"title":"Rigoblock","version":"1.0.0"},"tags":[{"name":"Quotes","description":"DEX price quotes — no wallet or vault context required"}],"servers":[{"url":"https://trader.rigoblock.com","description":"Production"}],"security":[{"x402":[]}],"components":{"securitySchemes":{"x402":{"type":"apiKey","in":"header","name":"X-Payment","description":"x402 payment header. Flow:\n1. Make the request without this header → receive `402 Payment Required` and, for protected routes, a `PAYMENT-REQUIRED` header describing accepted payment requirements\n2. Create the x402 payment payload for USDC on Base (chain 8453), typically via `@x402/core` and the CDP facilitator at `api.cdp.coinbase.com`\n3. Retry the request with this header set to the encoded payment payload\n\nSuccessful 2xx responses may include a `PAYMENT-RESPONSE` settlement receipt. See https://github.com/rigoblock/agentic-operator/blob/main/AGENTS.md for full integration."}},"schemas":{"QuoteResponse":{"type":"object","description":"Best swap quote across 150+ liquidity sources (0x default) or Uniswap V2/V3/V4","properties":{"sellToken":{"type":"string","description":"Address of the token being sold"},"buyToken":{"type":"string","description":"Address of the token being bought"},"sellAmount":{"type":"string","description":"Sell amount in token base units (wei)"},"buyAmount":{"type":"string","description":"Buy amount in token base units"},"price":{"type":"string","description":"Exchange rate (buy per sell)"},"source":{"type":"string","description":"DEX source routing the quote"},"chain":{"type":"string","description":"Chain the quote is valid on"},"calldata":{"type":"string","description":"Encoded calldata for on-chain execution"},"to":{"type":"string","description":"Contract address to send the swap transaction to"},"value":{"type":"string","description":"ETH value to attach (for native token swaps)"},"gasEstimate":{"type":"string","description":"Estimated gas units for the transaction"}}},"ErrorResponse":{"type":"object","properties":{"error":{"type":"string"},"message":{"type":"string"}}},"X402PaymentRequired":{"type":"object","description":"Standard x402 payment challenge","properties":{"x402Version":{"type":"integer"},"error":{"type":"string"},"accepts":{"type":"array","items":{"type":"object","properties":{"scheme":{"type":"string"},"network":{"type":"string"},"maxAmountRequired":{"type":"string"},"resource":{"type":"string"},"description":{"type":"string"},"mimeType":{"type":"string"},"payTo":{"type":"string","description":"USDC recipient address on Base"},"maxTimeoutSeconds":{"type":"integer"},"asset":{"type":"string","description":"USDC contract address on Base"},"extra":{"type":"object","properties":{"name":{"type":"string"},"version":{"type":"string"}}}}}}}}}},"paths":{"/api/quote":{"get":{"operationId":"getDexQuote","summary":"Get DEX swap quote","description":"Returns a swap quote sourced from Uniswap liquidity for a given token pair and amount on any of the 7 supported chains. No vault, wallet, or operator context required — any agent can call this endpoint with a $0.0020 USDC payment.\n\n**Price:** $0.0020 USDC per request (x402, eip155:8453)\n\n**Typical use:** Price discovery, trade sizing, yield comparison, arbitrage detection.\n\n**Example:** `GET /api/quote?sell=ETH&buy=USDC&amount=1&chain=base`","tags":["Quotes"],"parameters":[{"name":"sell","in":"query","required":true,"description":"Token to sell — ticker symbol (e.g. `ETH`) or ERC-20 contract address.","schema":{"type":"string"}},{"name":"buy","in":"query","required":true,"description":"Token to buy — ticker symbol (e.g. `USDC`) or ERC-20 contract address.","schema":{"type":"string"}},{"name":"amount","in":"query","required":true,"description":"Human-readable amount of the sell token (e.g. `1` for 1 ETH).","schema":{"type":"string"}},{"name":"chain","in":"query","required":false,"description":"Target chain. Accepts chain name or chain ID.","schema":{"type":"string","default":"base","enum":["base","arbitrum","ethereum","optimism","polygon","bsc","unichain"]}}],"responses":{"200":{"description":"Successful quote response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/QuoteResponse"}}}},"400":{"description":"Bad request — missing or invalid parameters","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"402":{"description":"Payment required (x402). Pay in USDC on Base and retry with `X-Payment` header.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/X402PaymentRequired"}}}}}}}}}
```

## Uniswap Trading API quote with oracle enrichment

> Proxies to the Uniswap Trading API \`/quote\` endpoint and enriches the response with on-chain BackgeoOracle spot-price metadata. Returns the upstream response verbatim plus \`priceFeedExists\`, \`deltaBps\`, and \`oracleAmount\`.\
> \
> \*\*Price:\*\* $0.0021 USDC per request (x402 exact scheme, eip155:8453)\
> \
> \*\*Request body:\*\* Identical to the Uniswap Trading API \`/quote\` endpoint. All request body fields are forwarded verbatim to Uniswap.

```json
{"openapi":"3.1.0","info":{"title":"Rigoblock","version":"1.0.0"},"tags":[{"name":"Quotes","description":"DEX price quotes — no wallet or vault context required"}],"servers":[{"url":"https://trader.rigoblock.com","description":"Production"}],"security":[{"x402":[]}],"components":{"securitySchemes":{"x402":{"type":"apiKey","in":"header","name":"X-Payment","description":"x402 payment header. Flow:\n1. Make the request without this header → receive `402 Payment Required` and, for protected routes, a `PAYMENT-REQUIRED` header describing accepted payment requirements\n2. Create the x402 payment payload for USDC on Base (chain 8453), typically via `@x402/core` and the CDP facilitator at `api.cdp.coinbase.com`\n3. Retry the request with this header set to the encoded payment payload\n\nSuccessful 2xx responses may include a `PAYMENT-RESPONSE` settlement receipt. See https://github.com/rigoblock/agentic-operator/blob/main/AGENTS.md for full integration."}},"schemas":{"OracleEnrichment":{"type":"object","description":"On-chain oracle spot-price metadata appended to DEX API responses","properties":{"priceFeedExists":{"type":"boolean","description":"Whether both tokens have an active BackgeoOracle price feed"},"deltaBps":{"type":"integer","description":"Divergence between DEX expected output and oracle spot price, in basis points. Positive = DEX gives less than oracle. Negative = DEX gives more."},"oracleAmount":{"type":"string","description":"Expected output amount from oracle spot price, in base units (wei/smallest token unit)"}}},"ErrorResponse":{"type":"object","properties":{"error":{"type":"string"},"message":{"type":"string"}}},"X402PaymentRequired":{"type":"object","description":"Standard x402 payment challenge","properties":{"x402Version":{"type":"integer"},"error":{"type":"string"},"accepts":{"type":"array","items":{"type":"object","properties":{"scheme":{"type":"string"},"network":{"type":"string"},"maxAmountRequired":{"type":"string"},"resource":{"type":"string"},"description":{"type":"string"},"mimeType":{"type":"string"},"payTo":{"type":"string","description":"USDC recipient address on Base"},"maxTimeoutSeconds":{"type":"integer"},"asset":{"type":"string","description":"USDC contract address on Base"},"extra":{"type":"object","properties":{"name":{"type":"string"},"version":{"type":"string"}}}}}}}}}},"paths":{"/api/quote/uniswap":{"post":{"operationId":"getUniswapQuote","summary":"Uniswap Trading API quote with oracle enrichment","description":"Proxies to the Uniswap Trading API `/quote` endpoint and enriches the response with on-chain BackgeoOracle spot-price metadata. Returns the upstream response verbatim plus `priceFeedExists`, `deltaBps`, and `oracleAmount`.\n\n**Price:** $0.0021 USDC per request (x402 exact scheme, eip155:8453)\n\n**Request body:** Identical to the Uniswap Trading API `/quote` endpoint. All request body fields are forwarded verbatim to Uniswap.","tags":["Quotes"],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["type","amount","tokenIn","tokenOut","tokenInChainId","tokenOutChainId"],"properties":{"type":{"type":"string","description":"Quote type: EXACT_INPUT or EXACT_OUTPUT"},"amount":{"type":"string","description":"Amount in base units"},"tokenIn":{"type":"string","description":"Token to sell (address or symbol). Use 0x0000...0000 for native ETH."},"tokenOut":{"type":"string","description":"Token to buy (address or symbol)"},"tokenInChainId":{"type":"integer","description":"Chain ID for input token"},"tokenOutChainId":{"type":"integer","description":"Chain ID for output token"},"swapper":{"type":"string","description":"Address of the swapper (vault address)"},"slippageTolerance":{"type":"number","description":"Maximum slippage tolerance in percent"},"routingPreference":{"type":"string","description":"Routing preference: CLASSIC, BEST_PRICE, FASTEST, or BEST_PRICE_V2"},"protocols":{"type":"array","items":{"type":"string"},"description":"List of protocols to include (e.g. V2, V3)"}}}}}},"responses":{"200":{"description":"Successful quote with oracle enrichment","content":{"application/json":{"schema":{"allOf":[{"type":"object","description":"Uniswap Trading API quote response"},{"$ref":"#/components/schemas/OracleEnrichment"}]}}}},"400":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized — x402 payment or browser session required","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"402":{"description":"Payment required (x402)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/X402PaymentRequired"}}}}}}}}}
```

## 0x API quote with oracle enrichment

> Proxies to the 0x API v2 \`/swap/allowance-holder/quote\` endpoint and enriches the response with on-chain BackgeoOracle spot-price metadata. Returns the upstream response verbatim plus \`priceFeedExists\`, \`deltaBps\`, and \`oracleAmount\`.\
> \
> \*\*Price:\*\* $0.0022 USDC per request (x402 exact scheme, eip155:8453)\
> \
> \*\*Query parameters:\*\* Identical to the 0x API. All query parameters are forwarded verbatim to 0x.

```json
{"openapi":"3.1.0","info":{"title":"Rigoblock","version":"1.0.0"},"tags":[{"name":"Quotes","description":"DEX price quotes — no wallet or vault context required"}],"servers":[{"url":"https://trader.rigoblock.com","description":"Production"}],"security":[{"x402":[]}],"components":{"securitySchemes":{"x402":{"type":"apiKey","in":"header","name":"X-Payment","description":"x402 payment header. Flow:\n1. Make the request without this header → receive `402 Payment Required` and, for protected routes, a `PAYMENT-REQUIRED` header describing accepted payment requirements\n2. Create the x402 payment payload for USDC on Base (chain 8453), typically via `@x402/core` and the CDP facilitator at `api.cdp.coinbase.com`\n3. Retry the request with this header set to the encoded payment payload\n\nSuccessful 2xx responses may include a `PAYMENT-RESPONSE` settlement receipt. See https://github.com/rigoblock/agentic-operator/blob/main/AGENTS.md for full integration."}},"schemas":{"OracleEnrichment":{"type":"object","description":"On-chain oracle spot-price metadata appended to DEX API responses","properties":{"priceFeedExists":{"type":"boolean","description":"Whether both tokens have an active BackgeoOracle price feed"},"deltaBps":{"type":"integer","description":"Divergence between DEX expected output and oracle spot price, in basis points. Positive = DEX gives less than oracle. Negative = DEX gives more."},"oracleAmount":{"type":"string","description":"Expected output amount from oracle spot price, in base units (wei/smallest token unit)"}}},"ErrorResponse":{"type":"object","properties":{"error":{"type":"string"},"message":{"type":"string"}}},"X402PaymentRequired":{"type":"object","description":"Standard x402 payment challenge","properties":{"x402Version":{"type":"integer"},"error":{"type":"string"},"accepts":{"type":"array","items":{"type":"object","properties":{"scheme":{"type":"string"},"network":{"type":"string"},"maxAmountRequired":{"type":"string"},"resource":{"type":"string"},"description":{"type":"string"},"mimeType":{"type":"string"},"payTo":{"type":"string","description":"USDC recipient address on Base"},"maxTimeoutSeconds":{"type":"integer"},"asset":{"type":"string","description":"USDC contract address on Base"},"extra":{"type":"object","properties":{"name":{"type":"string"},"version":{"type":"string"}}}}}}}}}},"paths":{"/api/quote/0x":{"get":{"operationId":"get0xQuote","summary":"0x API quote with oracle enrichment","description":"Proxies to the 0x API v2 `/swap/allowance-holder/quote` endpoint and enriches the response with on-chain BackgeoOracle spot-price metadata. Returns the upstream response verbatim plus `priceFeedExists`, `deltaBps`, and `oracleAmount`.\n\n**Price:** $0.0022 USDC per request (x402 exact scheme, eip155:8453)\n\n**Query parameters:** Identical to the 0x API. All query parameters are forwarded verbatim to 0x.","tags":["Quotes"],"parameters":[{"name":"chainId","in":"query","required":true,"description":"Chain ID","schema":{"type":"integer"}},{"name":"sellToken","in":"query","required":true,"description":"Token to sell (address or symbol)","schema":{"type":"string"}},{"name":"buyToken","in":"query","required":true,"description":"Token to buy (address or symbol)","schema":{"type":"string"}},{"name":"sellAmount","in":"query","required":false,"description":"Amount to sell in base units (exact-input). Either sellAmount or buyAmount must be provided.","schema":{"type":"string"}},{"name":"buyAmount","in":"query","required":false,"description":"Amount to buy in base units (exact-output). Either sellAmount or buyAmount must be provided.","schema":{"type":"string"}},{"name":"taker","in":"query","required":false,"description":"Address of the taker (vault address)","schema":{"type":"string"}},{"name":"slippageBps","in":"query","required":false,"description":"Maximum slippage tolerance in basis points (100 = 1%)","schema":{"type":"integer"}}],"responses":{"200":{"description":"Successful quote with oracle enrichment","content":{"application/json":{"schema":{"allOf":[{"type":"object","description":"0x API quote response"},{"$ref":"#/components/schemas/OracleEnrichment"}]}}}},"400":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized — x402 payment or browser session required","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"402":{"description":"Payment required (x402)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/X402PaymentRequired"}}}}}}}}}
```


# Agent

AI-powered DeFi agent interface — natural language to calldata

## AI-powered DeFi agent chat

> Natural language DeFi interface. Send a message describing a trading intent and receive unsigned swap calldata, position summaries, bridge transactions, or market analysis. The agent internally uses Kimi K2.7 Code for reasoning and tool calling.\
> \
> \*\*Price:\*\* up to $0.10 USDC per request (x402 \`upto\` scheme, eip155:8453) — billed by actual inference cost, typical $0.003–$0.015\
> \
> \*\*Supported operations (one per request):\*\*\
> \- Swap tokens via Uniswap v4 or 0x aggregator\
> \- Bridge tokens cross-chain via Across Protocol\
> \- Add/remove Uniswap v4 LP positions\
> \- Open/close GMX perpetual positions\
> \- Stake/unstake GRG governance tokens\
> \- Deploy and fund Rigoblock smart pool vaults\
> \- Query vault NAV, token balances, active positions\
> \- Create/manage automated trading strategies\
> \- Schedule TWAP orders (time-weighted average price execution)\
> \
> \*\*Execution modes:\*\*\
> \- manual (default): Returns unsigned calldata — operator signs and broadcasts\
> \- delegated: Agent wallet executes on-chain directly (requires operator auth + on-chain delegation)\
> \
> \*\*Safety:\*\* Every transaction passes NAV shield (≤10% loss), Swap Shield (oracle price check), 7-point execution validation, and on-chain selector whitelist.

```json
{"openapi":"3.1.0","info":{"title":"Rigoblock","version":"1.0.0"},"tags":[{"name":"Agent","description":"AI-powered DeFi agent interface — natural language to calldata"}],"servers":[{"url":"https://trader.rigoblock.com","description":"Production"}],"security":[{"x402":[]}],"components":{"securitySchemes":{"x402":{"type":"apiKey","in":"header","name":"X-Payment","description":"x402 payment header. Flow:\n1. Make the request without this header → receive `402 Payment Required` and, for protected routes, a `PAYMENT-REQUIRED` header describing accepted payment requirements\n2. Create the x402 payment payload for USDC on Base (chain 8453), typically via `@x402/core` and the CDP facilitator at `api.cdp.coinbase.com`\n3. Retry the request with this header set to the encoded payment payload\n\nSuccessful 2xx responses may include a `PAYMENT-RESPONSE` settlement receipt. See https://github.com/rigoblock/agentic-operator/blob/main/AGENTS.md for full integration."}},"schemas":{"ChatRequest":{"type":"object","required":["messages"],"properties":{"messages":{"type":"array","description":"Conversation history in OpenAI message format","items":{"type":"object","required":["role","content"],"properties":{"role":{"type":"string","enum":["user","assistant","system"]},"content":{"type":"string"}}}},"vaultAddress":{"type":"string","description":"RigoBlock vault (smart pool) address for vault-scoped operations"},"contextDocs":{"type":"array","description":"Optional request-scoped context snippets (for example markdown excerpts) injected into the model prompt for this request.","items":{"type":"string"}},"chain":{"type":"string","description":"Target chain context","default":"base","enum":["base","arbitrum","ethereum","optimism","polygon","bsc","unichain"]}}},"ChatResponse":{"type":"object","properties":{"message":{"type":"string","description":"AI-generated response text"},"reasoning":{"type":"string","description":"Reasoning trace from the model, when available."},"modelsUsed":{"type":"array","description":"Ordered list of model identifiers that contributed to this output.","items":{"type":"string"}},"finalModel":{"type":"string","description":"Model that authored the final natural-language output (or 'tooling' when output is tool-native)."},"action":{"type":"object","description":"Executable on-chain action, if applicable","properties":{"type":{"type":"string","enum":["swap","position","analysis"],"description":"Action type"},"to":{"type":"string","description":"Contract address"},"calldata":{"type":"string","description":"Encoded transaction calldata"},"value":{"type":"string","description":"ETH value to attach"},"gasEstimate":{"type":"string","description":"Estimated gas"}}}}},"ErrorResponse":{"type":"object","properties":{"error":{"type":"string"},"message":{"type":"string"}}},"X402PaymentRequired":{"type":"object","description":"Standard x402 payment challenge","properties":{"x402Version":{"type":"integer"},"error":{"type":"string"},"accepts":{"type":"array","items":{"type":"object","properties":{"scheme":{"type":"string"},"network":{"type":"string"},"maxAmountRequired":{"type":"string"},"resource":{"type":"string"},"description":{"type":"string"},"mimeType":{"type":"string"},"payTo":{"type":"string","description":"USDC recipient address on Base"},"maxTimeoutSeconds":{"type":"integer"},"asset":{"type":"string","description":"USDC contract address on Base"},"extra":{"type":"object","properties":{"name":{"type":"string"},"version":{"type":"string"}}}}}}}}}},"paths":{"/api/chat":{"post":{"operationId":"agentChat","summary":"AI-powered DeFi agent chat","description":"Natural language DeFi interface. Send a message describing a trading intent and receive unsigned swap calldata, position summaries, bridge transactions, or market analysis. The agent internally uses Kimi K2.7 Code for reasoning and tool calling.\n\n**Price:** up to $0.10 USDC per request (x402 `upto` scheme, eip155:8453) — billed by actual inference cost, typical $0.003–$0.015\n\n**Supported operations (one per request):**\n- Swap tokens via Uniswap v4 or 0x aggregator\n- Bridge tokens cross-chain via Across Protocol\n- Add/remove Uniswap v4 LP positions\n- Open/close GMX perpetual positions\n- Stake/unstake GRG governance tokens\n- Deploy and fund Rigoblock smart pool vaults\n- Query vault NAV, token balances, active positions\n- Create/manage automated trading strategies\n- Schedule TWAP orders (time-weighted average price execution)\n\n**Execution modes:**\n- manual (default): Returns unsigned calldata — operator signs and broadcasts\n- delegated: Agent wallet executes on-chain directly (requires operator auth + on-chain delegation)\n\n**Safety:** Every transaction passes NAV shield (≤10% loss), Swap Shield (oracle price check), 7-point execution validation, and on-chain selector whitelist.","tags":["Agent"],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatRequest"}}}},"responses":{"200":{"description":"AI response with DeFi action or analysis","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatResponse"}}}},"400":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"402":{"description":"Payment required (x402). Pay in USDC on Base and retry with `X-Payment` header.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/X402PaymentRequired"}}}}}}}}}
```


# Tools

Direct tool invocation without LLM overhead — structured input/output

## List all available DeFi tools with schemas

> Returns a machine-readable catalog of every direct-invocation tool: names, descriptions, parameter schemas, categories, and access requirements.\
> \
> Autonomous agents should call this endpoint first to discover what operations are available and what arguments each tool expects. The response includes full JSON-Schema parameter definitions compatible with OpenAI function calling.\
> \
> \*\*Price:\*\* $0.0024 USDC per request (x402, eip155:8453)

```json
{"openapi":"3.1.0","info":{"title":"Rigoblock","version":"1.0.0"},"tags":[{"name":"Tools","description":"Direct tool invocation without LLM overhead — structured input/output"}],"servers":[{"url":"https://trader.rigoblock.com","description":"Production"}],"security":[{"x402":[]}],"components":{"securitySchemes":{"x402":{"type":"apiKey","in":"header","name":"X-Payment","description":"x402 payment header. Flow:\n1. Make the request without this header → receive `402 Payment Required` and, for protected routes, a `PAYMENT-REQUIRED` header describing accepted payment requirements\n2. Create the x402 payment payload for USDC on Base (chain 8453), typically via `@x402/core` and the CDP facilitator at `api.cdp.coinbase.com`\n3. Retry the request with this header set to the encoded payment payload\n\nSuccessful 2xx responses may include a `PAYMENT-RESPONSE` settlement receipt. See https://github.com/rigoblock/agentic-operator/blob/main/AGENTS.md for full integration."}},"schemas":{"ToolCatalogResponse":{"type":"object","required":["description","usage","price","toolCount","tools"],"properties":{"description":{"type":"string"},"usage":{"type":"string"},"price":{"type":"string"},"toolCount":{"type":"integer","description":"Total number of tools in the catalog"},"tools":{"type":"array","items":{"$ref":"#/components/schemas/ToolDefinition"}}}},"ToolDefinition":{"type":"object","description":"OpenAI-compatible function schema for a single DeFi tool","required":["name","description","category","parameters","requiresOperatorAuth","readOnly"],"properties":{"name":{"type":"string","description":"Canonical tool name used in POST /api/tools?toolName={name}"},"description":{"type":"string","description":"What the tool does and when to use it"},"category":{"type":"string","description":"Functional group","enum":["Spot Trading","Vault Info","GMX Perpetuals","Uniswap v4 LP","Cross-Chain","GRG Staking","Vault Management","Delegation","TWAP Orders","NAV Sync","Operator Settings","Oracle","Strategy","Other"]},"parameters":{"type":"object","description":"JSON Schema for the tool's arguments object"},"requiresOperatorAuth":{"type":"boolean","description":"If true, the tool can only be invoked when the request includes a valid operator signature"},"readOnly":{"type":"boolean","description":"If true, the tool only reads data and never produces transaction calldata"}}},"ErrorResponse":{"type":"object","properties":{"error":{"type":"string"},"message":{"type":"string"}}},"X402PaymentRequired":{"type":"object","description":"Standard x402 payment challenge","properties":{"x402Version":{"type":"integer"},"error":{"type":"string"},"accepts":{"type":"array","items":{"type":"object","properties":{"scheme":{"type":"string"},"network":{"type":"string"},"maxAmountRequired":{"type":"string"},"resource":{"type":"string"},"description":{"type":"string"},"mimeType":{"type":"string"},"payTo":{"type":"string","description":"USDC recipient address on Base"},"maxTimeoutSeconds":{"type":"integer"},"asset":{"type":"string","description":"USDC contract address on Base"},"extra":{"type":"object","properties":{"name":{"type":"string"},"version":{"type":"string"}}}}}}}}}},"paths":{"/api/tools":{"get":{"operationId":"listTools","summary":"List all available DeFi tools with schemas","description":"Returns a machine-readable catalog of every direct-invocation tool: names, descriptions, parameter schemas, categories, and access requirements.\n\nAutonomous agents should call this endpoint first to discover what operations are available and what arguments each tool expects. The response includes full JSON-Schema parameter definitions compatible with OpenAI function calling.\n\n**Price:** $0.0024 USDC per request (x402, eip155:8453)","tags":["Tools"],"responses":{"200":{"description":"Tool catalog with full schemas","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ToolCatalogResponse"}}}},"401":{"description":"Authentication required","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"402":{"description":"x402 payment required","content":{"application/json":{"schema":{"$ref":"#/components/schemas/X402PaymentRequired"}}}}}}}}}
```

## Invoke a DeFi tool directly

> Direct tool invocation without LLM overhead. Useful when you know exactly which operation to perform and want structured input/output without natural language parsing. Each call is atomic.\
> \
> \*\*Discover schemas first:\*\* Call \`GET /api/tools\` to retrieve the full catalog with parameter schemas for every tool.\
> \
> \*\*Price:\*\* $0.0025 USDC per request (x402, eip155:8453)\
> \
> \*\*Read-only tools:\*\*\
> \`get\_swap\_quote\`, \`get\_vault\_info\`, \`get\_token\_balance\`, \`get\_pool\_info\`, \`get\_lp\_positions\`, \`gmx\_get\_positions\`, \`gmx\_get\_markets\`, \`check\_delegation\_status\`, \`get\_crosschain\_quote\`, \`get\_aggregated\_nav\`, \`get\_rebalance\_plan\`, \`verify\_bridge\_arrival\`, \`list\_twap\_orders\`, \`list\_nav\_syncs\`, \`list\_strategies\`, \`switch\_chain\`\
> \
> \*\*State-changing tools:\*\*\
> \`build\_vault\_swap\`, \`add\_liquidity\`, \`remove\_liquidity\`, \`collect\_lp\_fees\`, \`burn\_position\`, \`gmx\_increase\_position\`, \`gmx\_decrease\_position\`, \`gmx\_cancel\_order\`, \`gmx\_update\_order\`, \`gmx\_claim\_funding\_fees\`, \`crosschain\_transfer\`, \`crosschain\_sync\`, \`grg\_stake\`, \`grg\_unstake\`, \`grg\_undelegate\_stake\`, \`grg\_end\_epoch\`, \`grg\_claim\_rewards\`, \`deploy\_smart\_pool\`, \`fund\_pool\`, \`create\_twap\_order\`, \`cancel\_twap\_order\`, \`create\_nav\_sync\`, \`cancel\_nav\_sync\`\
> \
> \*\*Operator-scoped tools (require operatorVerified):\*\*\
> \`setup\_delegation\`, \`revoke\_delegation\`, \`revoke\_selectors\`, \`list\_strategies\`, \`set\_default\_slippage\`, \`set\_swap\_shield\_tolerance\`, \`enable\_swap\_shield\`\
> \
> \*\*Oracle tools:\*\*\
> \`refresh\_oracle\_feed\`\
> \
> \*\*Orchestration pattern:\*\* External agents compose atomic operations from this endpoint into multi-step strategies. Each call returns either a result (reads) or unsigned calldata (writes). The full safety stack (NAV shield, Swap Shield, slippage protection) applies to all write operations.

```json
{"openapi":"3.1.0","info":{"title":"Rigoblock","version":"1.0.0"},"tags":[{"name":"Tools","description":"Direct tool invocation without LLM overhead — structured input/output"}],"servers":[{"url":"https://trader.rigoblock.com","description":"Production"}],"security":[{"x402":[]}],"components":{"securitySchemes":{"x402":{"type":"apiKey","in":"header","name":"X-Payment","description":"x402 payment header. Flow:\n1. Make the request without this header → receive `402 Payment Required` and, for protected routes, a `PAYMENT-REQUIRED` header describing accepted payment requirements\n2. Create the x402 payment payload for USDC on Base (chain 8453), typically via `@x402/core` and the CDP facilitator at `api.cdp.coinbase.com`\n3. Retry the request with this header set to the encoded payment payload\n\nSuccessful 2xx responses may include a `PAYMENT-RESPONSE` settlement receipt. See https://github.com/rigoblock/agentic-operator/blob/main/AGENTS.md for full integration."}},"schemas":{"ErrorResponse":{"type":"object","properties":{"error":{"type":"string"},"message":{"type":"string"}}},"X402PaymentRequired":{"type":"object","description":"Standard x402 payment challenge","properties":{"x402Version":{"type":"integer"},"error":{"type":"string"},"accepts":{"type":"array","items":{"type":"object","properties":{"scheme":{"type":"string"},"network":{"type":"string"},"maxAmountRequired":{"type":"string"},"resource":{"type":"string"},"description":{"type":"string"},"mimeType":{"type":"string"},"payTo":{"type":"string","description":"USDC recipient address on Base"},"maxTimeoutSeconds":{"type":"integer"},"asset":{"type":"string","description":"USDC contract address on Base"},"extra":{"type":"object","properties":{"name":{"type":"string"},"version":{"type":"string"}}}}}}}}}},"paths":{"/api/tools":{"post":{"operationId":"invokeTool","summary":"Invoke a DeFi tool directly","description":"Direct tool invocation without LLM overhead. Useful when you know exactly which operation to perform and want structured input/output without natural language parsing. Each call is atomic.\n\n**Discover schemas first:** Call `GET /api/tools` to retrieve the full catalog with parameter schemas for every tool.\n\n**Price:** $0.0025 USDC per request (x402, eip155:8453)\n\n**Read-only tools:**\n`get_swap_quote`, `get_vault_info`, `get_token_balance`, `get_pool_info`, `get_lp_positions`, `gmx_get_positions`, `gmx_get_markets`, `check_delegation_status`, `get_crosschain_quote`, `get_aggregated_nav`, `get_rebalance_plan`, `verify_bridge_arrival`, `list_twap_orders`, `list_nav_syncs`, `list_strategies`, `switch_chain`\n\n**State-changing tools:**\n`build_vault_swap`, `add_liquidity`, `remove_liquidity`, `collect_lp_fees`, `burn_position`, `gmx_increase_position`, `gmx_decrease_position`, `gmx_cancel_order`, `gmx_update_order`, `gmx_claim_funding_fees`, `crosschain_transfer`, `crosschain_sync`, `grg_stake`, `grg_unstake`, `grg_undelegate_stake`, `grg_end_epoch`, `grg_claim_rewards`, `deploy_smart_pool`, `fund_pool`, `create_twap_order`, `cancel_twap_order`, `create_nav_sync`, `cancel_nav_sync`\n\n**Operator-scoped tools (require operatorVerified):**\n`setup_delegation`, `revoke_delegation`, `revoke_selectors`, `list_strategies`, `set_default_slippage`, `set_swap_shield_tolerance`, `enable_swap_shield`\n\n**Oracle tools:**\n`refresh_oracle_feed`\n\n**Orchestration pattern:** External agents compose atomic operations from this endpoint into multi-step strategies. Each call returns either a result (reads) or unsigned calldata (writes). The full safety stack (NAV shield, Swap Shield, slippage protection) applies to all write operations.","tags":["Tools"],"parameters":[{"name":"toolName","in":"query","required":true,"description":"Tool name to invoke","schema":{"type":"string","enum":["get_swap_quote","build_vault_swap","get_vault_info","get_token_balance","switch_chain","gmx_increase_position","gmx_decrease_position","gmx_get_positions","gmx_cancel_order","gmx_update_order","gmx_claim_funding_fees","gmx_get_markets","setup_delegation","revoke_delegation","check_delegation_status","deploy_smart_pool","fund_pool","crosschain_transfer","crosschain_sync","get_crosschain_quote","get_aggregated_nav","get_rebalance_plan","list_strategies","get_pool_info","add_liquidity","remove_liquidity","get_lp_positions","collect_lp_fees","burn_position","grg_stake","grg_unstake","grg_undelegate_stake","grg_end_epoch","grg_claim_rewards","revoke_selectors","verify_bridge_arrival","set_default_slippage","set_swap_shield_tolerance","enable_swap_shield","create_twap_order","cancel_twap_order","list_twap_orders","create_nav_sync","list_nav_syncs","cancel_nav_sync","refresh_oracle_feed"]}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["arguments"],"properties":{"arguments":{"type":"object","description":"Tool-specific arguments. For swap tools, provide `tokenIn`, `tokenOut`, and either `amountIn` or `amountOut`. Other tools use different argument shapes.","additionalProperties":true},"chainId":{"type":"integer","description":"EVM chain ID","default":8453,"enum":[1,10,56,137,130,8453,42161]},"vaultAddress":{"type":"string","description":"Rigoblock vault address (required for vault-specific tools)"},"operatorAddress":{"type":"string","description":"Vault owner address (required for vault-action tools in delegated mode)"},"authSignature":{"type":"string","description":"EIP-191 signature by operatorAddress over the auth message (required for vault-action tools)"},"authTimestamp":{"type":"integer","description":"Unix timestamp (ms) when authSignature was created. Valid for 24 hours."}}}}}},"responses":{"200":{"description":"Tool result","content":{"application/json":{"schema":{"type":"object","properties":{"tool":{"type":"string","description":"Canonical tool name that handled the request"},"message":{"type":"string","description":"Human-readable tool result"},"transaction":{"type":"object","description":"Unsigned transaction payload for state-changing tools"},"chainSwitch":{"type":"integer","description":"Suggested chain switch, when the tool resolved to a different chain"},"suggestions":{"type":"array","items":{"type":"string"}}}}}}},"400":{"description":"Bad request — missing or invalid arguments","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Operator authentication required for this tool","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"402":{"description":"x402 payment required","headers":{"PAYMENT-REQUIRED":{"description":"Base64-encoded payment requirements","schema":{"type":"string"}}},"content":{"application/json":{"schema":{"$ref":"#/components/schemas/X402PaymentRequired"}}}},"404":{"description":"Unknown tool name","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}}}}
```


# Operator Settings

Operator-scoped safety settings — requires vault ownership proof, bypasses the LLM

## Set default slippage tolerance

> Operator-only endpoint to set the default slippage tolerance (0.1%–5%). Does not involve the chat LLM; the UI settings panel calls this directly.

```json
{"openapi":"3.1.0","info":{"title":"Rigoblock","version":"1.0.0"},"tags":[{"name":"Operator Settings","description":"Operator-scoped safety settings — requires vault ownership proof, bypasses the LLM"}],"servers":[{"url":"https://trader.rigoblock.com","description":"Production"}],"paths":{"/api/settings/slippage":{"post":{"operationId":"setSlippage","summary":"Set default slippage tolerance","description":"Operator-only endpoint to set the default slippage tolerance (0.1%–5%). Does not involve the chat LLM; the UI settings panel calls this directly.","tags":["Operator Settings"],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/OperatorSettingsRequest"}}}},"responses":{"200":{"description":"Slippage updated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SettingsResponse"}}}},"400":{"description":"Invalid request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized"}}}}},"components":{"schemas":{"OperatorSettingsRequest":{"type":"object","required":["vaultAddress","chainId","operatorAddress","authSignature","authTimestamp"],"properties":{"vaultAddress":{"type":"string","description":"Vault contract address"},"chainId":{"type":"integer","description":"Chain ID where the vault exists"},"operatorAddress":{"type":"string","description":"Vault owner address"},"authSignature":{"type":"string","description":"EIP-191 signature of the auth message"},"authTimestamp":{"type":"integer","description":"Timestamp included in the signed auth message"},"slippage":{"type":"string","description":"Slippage value (e.g. '0.5%', '50bps', or '0.5')"},"tolerance":{"type":"string","description":"Swap Shield tolerance percentage (e.g. '30%')"},"threshold":{"type":"string","description":"NAV Shield threshold percentage (e.g. '15%')"},"reset":{"type":"boolean","description":"When true, reset the setting to its default value"}}},"SettingsResponse":{"type":"object","properties":{"ok":{"type":"boolean"},"message":{"type":"string"}}},"ErrorResponse":{"type":"object","properties":{"error":{"type":"string"},"message":{"type":"string"}}}}}}
```

## Set or reset Swap Shield tolerance

> Operator-only endpoint to temporarily raise the Swap Shield tolerance (up to 50% for 10 minutes) or reset it to the default 5%. Does not involve the chat LLM.

```json
{"openapi":"3.1.0","info":{"title":"Rigoblock","version":"1.0.0"},"tags":[{"name":"Operator Settings","description":"Operator-scoped safety settings — requires vault ownership proof, bypasses the LLM"}],"servers":[{"url":"https://trader.rigoblock.com","description":"Production"}],"paths":{"/api/settings/swap-shield":{"post":{"operationId":"setSwapShieldTolerance","summary":"Set or reset Swap Shield tolerance","description":"Operator-only endpoint to temporarily raise the Swap Shield tolerance (up to 50% for 10 minutes) or reset it to the default 5%. Does not involve the chat LLM.","tags":["Operator Settings"],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/OperatorSettingsRequest"}}}},"responses":{"200":{"description":"Swap Shield tolerance updated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SettingsResponse"}}}},"400":{"description":"Invalid request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized"}}}}},"components":{"schemas":{"OperatorSettingsRequest":{"type":"object","required":["vaultAddress","chainId","operatorAddress","authSignature","authTimestamp"],"properties":{"vaultAddress":{"type":"string","description":"Vault contract address"},"chainId":{"type":"integer","description":"Chain ID where the vault exists"},"operatorAddress":{"type":"string","description":"Vault owner address"},"authSignature":{"type":"string","description":"EIP-191 signature of the auth message"},"authTimestamp":{"type":"integer","description":"Timestamp included in the signed auth message"},"slippage":{"type":"string","description":"Slippage value (e.g. '0.5%', '50bps', or '0.5')"},"tolerance":{"type":"string","description":"Swap Shield tolerance percentage (e.g. '30%')"},"threshold":{"type":"string","description":"NAV Shield threshold percentage (e.g. '15%')"},"reset":{"type":"boolean","description":"When true, reset the setting to its default value"}}},"SettingsResponse":{"type":"object","properties":{"ok":{"type":"boolean"},"message":{"type":"string"}}},"ErrorResponse":{"type":"object","properties":{"error":{"type":"string"},"message":{"type":"string"}}}}}}
```

## Set or reset NAV Shield threshold

> Operator-only endpoint to set the NAV Shield maximum loss threshold (1%–100%) or reset it to the default 10%. Does not involve the chat LLM.

```json
{"openapi":"3.1.0","info":{"title":"Rigoblock","version":"1.0.0"},"tags":[{"name":"Operator Settings","description":"Operator-scoped safety settings — requires vault ownership proof, bypasses the LLM"}],"servers":[{"url":"https://trader.rigoblock.com","description":"Production"}],"paths":{"/api/settings/nav-shield":{"post":{"operationId":"setNavShieldThreshold","summary":"Set or reset NAV Shield threshold","description":"Operator-only endpoint to set the NAV Shield maximum loss threshold (1%–100%) or reset it to the default 10%. Does not involve the chat LLM.","tags":["Operator Settings"],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/OperatorSettingsRequest"}}}},"responses":{"200":{"description":"NAV Shield threshold updated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SettingsResponse"}}}},"400":{"description":"Invalid request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized"}}}}},"components":{"schemas":{"OperatorSettingsRequest":{"type":"object","required":["vaultAddress","chainId","operatorAddress","authSignature","authTimestamp"],"properties":{"vaultAddress":{"type":"string","description":"Vault contract address"},"chainId":{"type":"integer","description":"Chain ID where the vault exists"},"operatorAddress":{"type":"string","description":"Vault owner address"},"authSignature":{"type":"string","description":"EIP-191 signature of the auth message"},"authTimestamp":{"type":"integer","description":"Timestamp included in the signed auth message"},"slippage":{"type":"string","description":"Slippage value (e.g. '0.5%', '50bps', or '0.5')"},"tolerance":{"type":"string","description":"Swap Shield tolerance percentage (e.g. '30%')"},"threshold":{"type":"string","description":"NAV Shield threshold percentage (e.g. '15%')"},"reset":{"type":"boolean","description":"When true, reset the setting to its default value"}}},"SettingsResponse":{"type":"object","properties":{"ok":{"type":"boolean"},"message":{"type":"string"}}},"ErrorResponse":{"type":"object","properties":{"error":{"type":"string"},"message":{"type":"string"}}}}}}
```

## Get execution mode preference

> Returns the operator's current auto-execute preference (autonomous or confirm). Shared between the web UI and Telegram.

```json
{"openapi":"3.1.0","info":{"title":"Rigoblock","version":"1.0.0"},"tags":[{"name":"Operator Settings","description":"Operator-scoped safety settings — requires vault ownership proof, bypasses the LLM"}],"servers":[{"url":"https://trader.rigoblock.com","description":"Production"}],"paths":{"/api/settings/exec-mode":{"get":{"operationId":"getExecMode","summary":"Get execution mode preference","description":"Returns the operator's current auto-execute preference (autonomous or confirm). Shared between the web UI and Telegram.","tags":["Operator Settings"],"parameters":[{"name":"vaultAddress","in":"query","required":true,"schema":{"type":"string"}},{"name":"chainId","in":"query","required":true,"schema":{"type":"integer"}},{"name":"operatorAddress","in":"query","required":true,"schema":{"type":"string"}},{"name":"authSignature","in":"query","required":true,"schema":{"type":"string"}},{"name":"authTimestamp","in":"query","required":true,"schema":{"type":"integer"}}],"responses":{"200":{"description":"Current execution mode preference","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExecModeResponse"}}}},"400":{"description":"Invalid request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized"}}}}},"components":{"schemas":{"ExecModeResponse":{"type":"object","properties":{"ok":{"type":"boolean"},"mode":{"type":"string","enum":["autonomous","confirm"]}}},"ErrorResponse":{"type":"object","properties":{"error":{"type":"string"},"message":{"type":"string"}}}}}}
```

## Set execution mode preference

> Sets whether the operator's trades execute immediately (autonomous) or require confirmation (confirm). Shared between the web UI and Telegram.

```json
{"openapi":"3.1.0","info":{"title":"Rigoblock","version":"1.0.0"},"tags":[{"name":"Operator Settings","description":"Operator-scoped safety settings — requires vault ownership proof, bypasses the LLM"}],"servers":[{"url":"https://trader.rigoblock.com","description":"Production"}],"paths":{"/api/settings/exec-mode":{"post":{"operationId":"setExecMode","summary":"Set execution mode preference","description":"Sets whether the operator's trades execute immediately (autonomous) or require confirmation (confirm). Shared between the web UI and Telegram.","tags":["Operator Settings"],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExecModeRequest"}}}},"responses":{"200":{"description":"Execution mode preference updated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExecModeResponse"}}}},"400":{"description":"Invalid request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized"}}}}},"components":{"schemas":{"ExecModeRequest":{"type":"object","required":["vaultAddress","chainId","operatorAddress","authSignature","authTimestamp","mode"],"properties":{"vaultAddress":{"type":"string","description":"Vault contract address"},"chainId":{"type":"integer","description":"Chain ID where the vault exists"},"operatorAddress":{"type":"string","description":"Vault owner address"},"authSignature":{"type":"string","description":"EIP-191 signature of the auth message"},"authTimestamp":{"type":"integer","description":"Timestamp included in the signed auth message"},"mode":{"type":"string","enum":["autonomous","confirm"],"description":"Autonomous executes trades immediately; confirm requires an explicit approval"}}},"ExecModeResponse":{"type":"object","properties":{"ok":{"type":"boolean"},"mode":{"type":"string","enum":["autonomous","confirm"]}}},"ErrorResponse":{"type":"object","properties":{"error":{"type":"string"},"message":{"type":"string"}}}}}}
```


# Models

## The QuoteResponse object

```json
{"openapi":"3.1.0","info":{"title":"Rigoblock","version":"1.0.0"},"components":{"schemas":{"QuoteResponse":{"type":"object","description":"Best swap quote across 150+ liquidity sources (0x default) or Uniswap V2/V3/V4","properties":{"sellToken":{"type":"string","description":"Address of the token being sold"},"buyToken":{"type":"string","description":"Address of the token being bought"},"sellAmount":{"type":"string","description":"Sell amount in token base units (wei)"},"buyAmount":{"type":"string","description":"Buy amount in token base units"},"price":{"type":"string","description":"Exchange rate (buy per sell)"},"source":{"type":"string","description":"DEX source routing the quote"},"chain":{"type":"string","description":"Chain the quote is valid on"},"calldata":{"type":"string","description":"Encoded calldata for on-chain execution"},"to":{"type":"string","description":"Contract address to send the swap transaction to"},"value":{"type":"string","description":"ETH value to attach (for native token swaps)"},"gasEstimate":{"type":"string","description":"Estimated gas units for the transaction"}}}}}}
```

## The ChatRequest object

```json
{"openapi":"3.1.0","info":{"title":"Rigoblock","version":"1.0.0"},"components":{"schemas":{"ChatRequest":{"type":"object","required":["messages"],"properties":{"messages":{"type":"array","description":"Conversation history in OpenAI message format","items":{"type":"object","required":["role","content"],"properties":{"role":{"type":"string","enum":["user","assistant","system"]},"content":{"type":"string"}}}},"vaultAddress":{"type":"string","description":"RigoBlock vault (smart pool) address for vault-scoped operations"},"contextDocs":{"type":"array","description":"Optional request-scoped context snippets (for example markdown excerpts) injected into the model prompt for this request.","items":{"type":"string"}},"chain":{"type":"string","description":"Target chain context","default":"base","enum":["base","arbitrum","ethereum","optimism","polygon","bsc","unichain"]}}}}}}
```

## The ChatResponse object

```json
{"openapi":"3.1.0","info":{"title":"Rigoblock","version":"1.0.0"},"components":{"schemas":{"ChatResponse":{"type":"object","properties":{"message":{"type":"string","description":"AI-generated response text"},"reasoning":{"type":"string","description":"Reasoning trace from the model, when available."},"modelsUsed":{"type":"array","description":"Ordered list of model identifiers that contributed to this output.","items":{"type":"string"}},"finalModel":{"type":"string","description":"Model that authored the final natural-language output (or 'tooling' when output is tool-native)."},"action":{"type":"object","description":"Executable on-chain action, if applicable","properties":{"type":{"type":"string","enum":["swap","position","analysis"],"description":"Action type"},"to":{"type":"string","description":"Contract address"},"calldata":{"type":"string","description":"Encoded transaction calldata"},"value":{"type":"string","description":"ETH value to attach"},"gasEstimate":{"type":"string","description":"Estimated gas"}}}}}}}}
```

## The X402PaymentRequired object

```json
{"openapi":"3.1.0","info":{"title":"Rigoblock","version":"1.0.0"},"components":{"schemas":{"X402PaymentRequired":{"type":"object","description":"Standard x402 payment challenge","properties":{"x402Version":{"type":"integer"},"error":{"type":"string"},"accepts":{"type":"array","items":{"type":"object","properties":{"scheme":{"type":"string"},"network":{"type":"string"},"maxAmountRequired":{"type":"string"},"resource":{"type":"string"},"description":{"type":"string"},"mimeType":{"type":"string"},"payTo":{"type":"string","description":"USDC recipient address on Base"},"maxTimeoutSeconds":{"type":"integer"},"asset":{"type":"string","description":"USDC contract address on Base"},"extra":{"type":"object","properties":{"name":{"type":"string"},"version":{"type":"string"}}}}}}}}}}}
```

## The ToolDefinition object

```json
{"openapi":"3.1.0","info":{"title":"Rigoblock","version":"1.0.0"},"components":{"schemas":{"ToolDefinition":{"type":"object","description":"OpenAI-compatible function schema for a single DeFi tool","required":["name","description","category","parameters","requiresOperatorAuth","readOnly"],"properties":{"name":{"type":"string","description":"Canonical tool name used in POST /api/tools?toolName={name}"},"description":{"type":"string","description":"What the tool does and when to use it"},"category":{"type":"string","description":"Functional group","enum":["Spot Trading","Vault Info","GMX Perpetuals","Uniswap v4 LP","Cross-Chain","GRG Staking","Vault Management","Delegation","TWAP Orders","NAV Sync","Operator Settings","Oracle","Strategy","Other"]},"parameters":{"type":"object","description":"JSON Schema for the tool's arguments object"},"requiresOperatorAuth":{"type":"boolean","description":"If true, the tool can only be invoked when the request includes a valid operator signature"},"readOnly":{"type":"boolean","description":"If true, the tool only reads data and never produces transaction calldata"}}}}}}
```

## The ToolCatalogResponse object

```json
{"openapi":"3.1.0","info":{"title":"Rigoblock","version":"1.0.0"},"components":{"schemas":{"ToolCatalogResponse":{"type":"object","required":["description","usage","price","toolCount","tools"],"properties":{"description":{"type":"string"},"usage":{"type":"string"},"price":{"type":"string"},"toolCount":{"type":"integer","description":"Total number of tools in the catalog"},"tools":{"type":"array","items":{"$ref":"#/components/schemas/ToolDefinition"}}}},"ToolDefinition":{"type":"object","description":"OpenAI-compatible function schema for a single DeFi tool","required":["name","description","category","parameters","requiresOperatorAuth","readOnly"],"properties":{"name":{"type":"string","description":"Canonical tool name used in POST /api/tools?toolName={name}"},"description":{"type":"string","description":"What the tool does and when to use it"},"category":{"type":"string","description":"Functional group","enum":["Spot Trading","Vault Info","GMX Perpetuals","Uniswap v4 LP","Cross-Chain","GRG Staking","Vault Management","Delegation","TWAP Orders","NAV Sync","Operator Settings","Oracle","Strategy","Other"]},"parameters":{"type":"object","description":"JSON Schema for the tool's arguments object"},"requiresOperatorAuth":{"type":"boolean","description":"If true, the tool can only be invoked when the request includes a valid operator signature"},"readOnly":{"type":"boolean","description":"If true, the tool only reads data and never produces transaction calldata"}}}}}}
```

## The OracleEnrichment object

```json
{"openapi":"3.1.0","info":{"title":"Rigoblock","version":"1.0.0"},"components":{"schemas":{"OracleEnrichment":{"type":"object","description":"On-chain oracle spot-price metadata appended to DEX API responses","properties":{"priceFeedExists":{"type":"boolean","description":"Whether both tokens have an active BackgeoOracle price feed"},"deltaBps":{"type":"integer","description":"Divergence between DEX expected output and oracle spot price, in basis points. Positive = DEX gives less than oracle. Negative = DEX gives more."},"oracleAmount":{"type":"string","description":"Expected output amount from oracle spot price, in base units (wei/smallest token unit)"}}}}}}
```

## The OperatorSettingsRequest object

```json
{"openapi":"3.1.0","info":{"title":"Rigoblock","version":"1.0.0"},"components":{"schemas":{"OperatorSettingsRequest":{"type":"object","required":["vaultAddress","chainId","operatorAddress","authSignature","authTimestamp"],"properties":{"vaultAddress":{"type":"string","description":"Vault contract address"},"chainId":{"type":"integer","description":"Chain ID where the vault exists"},"operatorAddress":{"type":"string","description":"Vault owner address"},"authSignature":{"type":"string","description":"EIP-191 signature of the auth message"},"authTimestamp":{"type":"integer","description":"Timestamp included in the signed auth message"},"slippage":{"type":"string","description":"Slippage value (e.g. '0.5%', '50bps', or '0.5')"},"tolerance":{"type":"string","description":"Swap Shield tolerance percentage (e.g. '30%')"},"threshold":{"type":"string","description":"NAV Shield threshold percentage (e.g. '15%')"},"reset":{"type":"boolean","description":"When true, reset the setting to its default value"}}}}}}
```

## The ExecModeRequest object

```json
{"openapi":"3.1.0","info":{"title":"Rigoblock","version":"1.0.0"},"components":{"schemas":{"ExecModeRequest":{"type":"object","required":["vaultAddress","chainId","operatorAddress","authSignature","authTimestamp","mode"],"properties":{"vaultAddress":{"type":"string","description":"Vault contract address"},"chainId":{"type":"integer","description":"Chain ID where the vault exists"},"operatorAddress":{"type":"string","description":"Vault owner address"},"authSignature":{"type":"string","description":"EIP-191 signature of the auth message"},"authTimestamp":{"type":"integer","description":"Timestamp included in the signed auth message"},"mode":{"type":"string","enum":["autonomous","confirm"],"description":"Autonomous executes trades immediately; confirm requires an explicit approval"}}}}}}
```

## The ExecModeResponse object

```json
{"openapi":"3.1.0","info":{"title":"Rigoblock","version":"1.0.0"},"components":{"schemas":{"ExecModeResponse":{"type":"object","properties":{"ok":{"type":"boolean"},"mode":{"type":"string","enum":["autonomous","confirm"]}}}}}}
```

## The SettingsResponse object

```json
{"openapi":"3.1.0","info":{"title":"Rigoblock","version":"1.0.0"},"components":{"schemas":{"SettingsResponse":{"type":"object","properties":{"ok":{"type":"boolean"},"message":{"type":"string"}}}}}}
```

## The ErrorResponse object

```json
{"openapi":"3.1.0","info":{"title":"Rigoblock","version":"1.0.0"},"components":{"schemas":{"ErrorResponse":{"type":"object","properties":{"error":{"type":"string"},"message":{"type":"string"}}}}}}
```


# Solidity API Reference


# Protocol


# IRigoblockV3Pool

## IRigoblockV3Pool


# ISmartPool

## ISmartPool


# SmartPool

## SmartPool

### constructor

```solidity
constructor(address authority, address extensionsMap, address tokenJar) public
```

Owner is initialized to 0 to lock owner actions in this implementation. Kyc provider set as will effectively lock direct mint/burn actions. ExtensionsMap validation is performed in MixinImmutables constructor.


# Core


# Actions


# MixinActions

## MixinActions

### BaseTokenBalance

```solidity
error BaseTokenBalance()
```

### NativeCurrencyNotAccepted

```solidity
error NativeCurrencyNotAccepted()
```

### PoolAmountSmallerThanMinimum

```solidity
error PoolAmountSmallerThanMinimum(uint16 minimumOrderDivisor)
```

### PoolBurnNotEnough

```solidity
error PoolBurnNotEnough()
```

### PoolBurnNullAmount

```solidity
error PoolBurnNullAmount()
```

### PoolBurnOutputAmount

```solidity
error PoolBurnOutputAmount()
```

### PoolCallerNotWhitelisted

```solidity
error PoolCallerNotWhitelisted()
```

### PoolMinimumPeriodNotEnough

```solidity
error PoolMinimumPeriodNotEnough()
```

### PoolMintAmountIn

```solidity
error PoolMintAmountIn()
```

### PoolMintInvalidRecipient

```solidity
error PoolMintInvalidRecipient()
```

### PoolMintOutputAmount

```solidity
error PoolMintOutputAmount()
```

### PoolTokenNotActive

```solidity
error PoolTokenNotActive()
```

### InvalidOperator

```solidity
error InvalidOperator()
```

### PoolMintTokenNotActive

```solidity
error PoolMintTokenNotActive()
```

### mint

```solidity
function mint(address recipient, uint256 amountIn, uint256 amountOutMin) external payable returns (uint256 recipientAmount)
```

Allows a user to mint pool tokens on behalf of an address.

#### Parameters

| Name         | Type    | Description                                                         |
| ------------ | ------- | ------------------------------------------------------------------- |
| recipient    | address | Address receiving the tokens.                                       |
| amountIn     | uint256 | Amount of base tokens.                                              |
| amountOutMin | uint256 | Minimum amount to be received, prevents pool operator frontrunning. |

#### Return Values

| Name            | Type    | Description                           |
| --------------- | ------- | ------------------------------------- |
| recipientAmount | uint256 | Number of tokens minted to recipient. |

### mintWithToken

```solidity
function mintWithToken(address recipient, uint256 amountIn, uint256 amountOutMin, address tokenIn) external payable returns (uint256 recipientAmount)
```

Allows a user to mint pool tokens on behalf of an address using a desired token.

*The token must be vault-owned, i.e. in the active token list, after operator action.*

#### Parameters

| Name         | Type    | Description                                                         |
| ------------ | ------- | ------------------------------------------------------------------- |
| recipient    | address | Address receiving the tokens.                                       |
| amountIn     | uint256 | Amount of base tokens.                                              |
| amountOutMin | uint256 | Minimum amount to be received, prevents pool operator frontrunning. |
| tokenIn      | address |                                                                     |

#### Return Values

| Name            | Type    | Description                           |
| --------------- | ------- | ------------------------------------- |
| recipientAmount | uint256 | Number of tokens minted to recipient. |

### burn

```solidity
function burn(uint256 amountIn, uint256 amountOutMin) external returns (uint256 netRevenue)
```

Allows a pool holder to burn pool tokens.

#### Parameters

| Name         | Type    | Description                                                         |
| ------------ | ------- | ------------------------------------------------------------------- |
| amountIn     | uint256 | Number of tokens to burn.                                           |
| amountOutMin | uint256 | Minimum amount to be received, prevents pool operator frontrunning. |

#### Return Values

| Name       | Type    | Description                      |
| ---------- | ------- | -------------------------------- |
| netRevenue | uint256 | Net amount of burnt pool tokens. |

### burnForToken

```solidity
function burnForToken(uint256 amountIn, uint256 amountOutMin, address tokenOut) external returns (uint256 netRevenue)
```

Allows a pool holder to burn pool tokens and receive a token other than base token.

*The method is a fallback for when the vault does not hold enough base token, reverts otherwise.*

#### Parameters

| Name         | Type    | Description                                                         |
| ------------ | ------- | ------------------------------------------------------------------- |
| amountIn     | uint256 | Number of tokens to burn.                                           |
| amountOutMin | uint256 | Minimum amount to be received, prevents pool operator frontrunning. |
| tokenOut     | address | The token to be received in exchange for pool tokens.               |

#### Return Values

| Name       | Type    | Description                      |
| ---------- | ------- | -------------------------------- |
| netRevenue | uint256 | Net amount of burnt pool tokens. |

### updateUnitaryValue

```solidity
function updateUnitaryValue() external returns (struct NetAssetsValue navParams)
```

Allows anyone to store an up-to-date pool price.

*Reentrancy protection provided by calling functions (mint, burn, depositV3, donate)*

#### Return Values

| Name      | Type                  | Description                                                     |
| --------- | --------------------- | --------------------------------------------------------------- |
| navParams | struct NetAssetsValue | Tuple of unitary value, net total value, net total liabilities. |

### setOperator

```solidity
function setOperator(address operator, bool approved) external returns (bool)
```

Sets or removes an operator for the caller.

#### Parameters

| Name     | Type    | Description                  |
| -------- | ------- | ---------------------------- |
| operator | address | The address of the operator. |
| approved | bool    | The approval status.         |

#### Return Values

| Name | Type | Description        |
| ---- | ---- | ------------------ |
| \[0] | bool | bool True, always. |

### decimals

```solidity
function decimals() public view virtual returns (uint8)
```

Returns token decimals.

#### Return Values

| Name | Type  | Description               |
| ---- | ----- | ------------------------- |
| \[0] | uint8 | Uint8 number of decimals. |

### isOperator

```solidity
function isOperator(address holder, address operator) public view virtual returns (bool approved)
```

#### Parameters

| Name     | Type    | Description                  |
| -------- | ------- | ---------------------------- |
| holder   | address | The address of the holder.   |
| operator | address | The address of the operator. |

#### Return Values

| Name     | Type | Description          |
| -------- | ---- | -------------------- |
| approved | bool | The approval status. |

### \_updateNav

```solidity
function _updateNav() internal virtual returns (struct NavComponents)
```

### \_getFeeCollector

```solidity
function _getFeeCollector() internal view virtual returns (address)
```

### \_getMinPeriod

```solidity
function _getMinPeriod() internal view virtual returns (uint48)
```

### \_getSpread

```solidity
function _getSpread() internal view virtual returns (uint16)
```

\_Returns the spread, or *MAX\_SPREAD if not set*

### \_getTokenJar

```solidity
function _getTokenJar() internal view virtual returns (address)
```


# MixinOwnerActions

## MixinOwnerActions

### PoolCallerIsNotOwner

```solidity
error PoolCallerIsNotOwner()
```

### PoolFeeBiggerThanMax

```solidity
error PoolFeeBiggerThanMax(uint16 maxFee)
```

### PoolInputIsNotContract

```solidity
error PoolInputIsNotContract()
```

### OwnerActionInputIsSameAsCurrent

```solidity
error OwnerActionInputIsSameAsCurrent()
```

### PoolLockupPeriodInvalid

```solidity
error PoolLockupPeriodInvalid(uint48 minimum, uint48 maximum)
```

### PoolNullOwnerInput

```solidity
error PoolNullOwnerInput()
```

### PoolSpreadInvalid

```solidity
error PoolSpreadInvalid(uint16 maxSpread)
```

### onlyOwner

```solidity
modifier onlyOwner()
```

### changeFeeCollector

```solidity
function changeFeeCollector(address feeCollector) external
```

Allows owner to decide where to receive the fee.

#### Parameters

| Name         | Type    | Description                  |
| ------------ | ------- | ---------------------------- |
| feeCollector | address | Address of the fee receiver. |

### changeMinPeriod

```solidity
function changeMinPeriod(uint48 minPeriod) external
```

Allows pool owner to change the minimum holding period.

*Minimum period is always at least 10 to prevent flash txs.*

#### Parameters

| Name      | Type   | Description      |
| --------- | ------ | ---------------- |
| minPeriod | uint48 | Time in seconds. |

### changeSpread

```solidity
function changeSpread(uint16 newSpread) external
```

Allows pool owner to change the mint/burn spread.

#### Parameters

| Name      | Type   | Description                                 |
| --------- | ------ | ------------------------------------------- |
| newSpread | uint16 | Number between 0 and 1000, in basis points. |

### purgeInactiveTokensAndApps

```solidity
function purgeInactiveTokensAndApps() external
```

Allows the owner to remove all inactive token and applications.

*This is the only endpoint that has access to removing a token from the active tokens tuple. Used to reduce cost of mint/burn as more tokens are traded, and allow lower gas for hft.*

### revokeAllDelegations

```solidity
function revokeAllDelegations(address delegated) external
```

Revokes all selector delegations for a given address in a single call.

*Useful when a delegated wallet is compromised.*

#### Parameters

| Name      | Type    | Description                                     |
| --------- | ------- | ----------------------------------------------- |
| delegated | address | Address whose full delegation is to be revoked. |

### revokeAllDelegationsForSelector

```solidity
function revokeAllDelegationsForSelector(bytes4 selector) external
```

Revokes all address delegations for a given selector in a single call.

*Useful when an adapter is being replaced by governance and stale delegates should be cleaned.*

#### Parameters

| Name     | Type   | Description                                           |
| -------- | ------ | ----------------------------------------------------- |
| selector | bytes4 | Selector whose full delegation list is to be cleared. |

### setAcceptableMintToken

```solidity
function setAcceptableMintToken(address token, bool isAccepted) external
```

Allows the owner to set acceptable mint tokens other than the base token.

#### Parameters

| Name       | Type    | Description                                                                   |
| ---------- | ------- | ----------------------------------------------------------------------------- |
| token      | address | Address of the target token.                                                  |
| isAccepted | bool    | Boolean to indicate whether the token is to be added or removed from storage. |

### setKycProvider

```solidity
function setKycProvider(address kycProvider) external
```

Allows pool owner to set/update the user whitelist contract.

*Kyc provider can be set to null, removing user whitelist requirement.*

#### Parameters

| Name        | Type    | Description                  |
| ----------- | ------- | ---------------------------- |
| kycProvider | address | Address if the kyc provider. |

### setOwner

```solidity
function setOwner(address newOwner) external
```

Allows pool owner to set a new owner address.

*Method restricted to owner.*

#### Parameters

| Name     | Type    | Description               |
| -------- | ------- | ------------------------- |
| newOwner | address | Address of the new owner. |

### setTransactionFee

```solidity
function setTransactionFee(uint16 transactionFee) external
```

Allows pool owner to set the transaction fee.

#### Parameters

| Name           | Type   | Description                                   |
| -------------- | ------ | --------------------------------------------- |
| transactionFee | uint16 | Value of the transaction fee in basis points. |

### updateDelegation

```solidity
function updateDelegation(struct Delegation[] delegations) external
```

Allows pool owner to batch grant or revoke delegated adapter write access.

*Each entry independently adds or removes one (selector, address) pair. Emits DelegationUpdated only for entries that change storage (idempotent operations emit no event).*

#### Parameters

| Name        | Type                 | Description                              |
| ----------- | -------------------- | ---------------------------------------- |
| delegations | struct Delegation\[] | Array of delegation operations to apply. |


# Immutable


# MixinConstants

## MixinConstants

Constants are copied in the bytecode and not assigned a storage slot, can safely be added to this contract.

*Inheriting from interface is required as we override public variables.*

### VERSION

```solidity
string VERSION
```

Returns a string of the pool version.

#### Return Values

| Name | Type | Description |
| ---- | ---- | ----------- |

### \_ACCEPTED\_TOKENS\_SLOT

```solidity
bytes32 _ACCEPTED_TOKENS_SLOT
```

### \_APPLICATIONS\_SLOT

```solidity
bytes32 _APPLICATIONS_SLOT
```

### \_OPERATOR\_BOOLEAN\_SLOT

```solidity
bytes32 _OPERATOR_BOOLEAN_SLOT
```

### \_POOL\_ACCOUNTS\_SLOT

```solidity
bytes32 _POOL_ACCOUNTS_SLOT
```

### \_POOL\_INIT\_SLOT

```solidity
bytes32 _POOL_INIT_SLOT
```

### \_POOL\_TOKENS\_SLOT

```solidity
bytes32 _POOL_TOKENS_SLOT
```

### \_POOL\_VARIABLES\_SLOT

```solidity
bytes32 _POOL_VARIABLES_SLOT
```

### \_TOKEN\_REGISTRY\_SLOT

```solidity
bytes32 _TOKEN_REGISTRY_SLOT
```

### \_UNIV4\_TOKEN\_IDS\_SLOT

```solidity
bytes32 _UNIV4_TOKEN_IDS_SLOT
```

### \_VIRTUAL\_SUPPLY\_SLOT

```solidity
bytes32 _VIRTUAL_SUPPLY_SLOT
```

### \_DELEGATION\_SLOT

```solidity
bytes32 _DELEGATION_SLOT
```

### \_GMX\_CALLBACK\_SLOT

```solidity
bytes32 _GMX_CALLBACK_SLOT
```

### \_ZERO\_ADDRESS

```solidity
address _ZERO_ADDRESS
```

### \_BASE\_TOKEN\_FLAG

```solidity
address _BASE_TOKEN_FLAG
```

### \_FEE\_BASE

```solidity
uint16 _FEE_BASE
```

### \_MAX\_SPREAD

```solidity
uint16 _MAX_SPREAD
```

### \_DEFAULT\_SPREAD

```solidity
uint16 _DEFAULT_SPREAD
```

### \_MAX\_TRANSACTION\_FEE

```solidity
uint16 _MAX_TRANSACTION_FEE
```

### \_MINIMUM\_ORDER\_DIVISOR

```solidity
uint16 _MINIMUM_ORDER_DIVISOR
```

### \_SPREAD\_BASE

```solidity
uint16 _SPREAD_BASE
```

### \_MAX\_LOCKUP

```solidity
uint48 _MAX_LOCKUP
```

### \_MIN\_LOCKUP

```solidity
uint48 _MIN_LOCKUP
```


# MixinImmutables

## MixinImmutables

Immutables are not assigned a storage slot, can be safely added to this contract.

### InvalidAuthorityInput

```solidity
error InvalidAuthorityInput()
```

### InvalidExtensionsMapInput

```solidity
error InvalidExtensionsMapInput()
```

### authority

```solidity
address authority
```

Returns the address of the authority contract.

#### Return Values

| Name | Type | Description |
| ---- | ---- | ----------- |

### wrappedNative

```solidity
address wrappedNative
```

Returns the address of the WETH9 contract.

*Used to convert WETH balances to ETH without executing an oracle call.*

#### Return Values

| Name | Type | Description |
| ---- | ---- | ----------- |

### tokenJar

```solidity
address tokenJar
```

Returns the address of the Rigoblock token jar contract.

*Used to transfer protocol fees to the buy-back-and-burn contract.*

#### Return Values

| Name | Type | Description |
| ---- | ---- | ----------- |

### \_implementation

```solidity
address _implementation
```

### \_extensionsMap

```solidity
contract IExtensionsMap _extensionsMap
```

### constructor

```solidity
constructor(address _authority, address extensionsMap, address _tokenJar) internal
```

The ExtensionsMap interface is required to implement the expected methods as sanity check.


# MixinStorage

## MixinStorage

Storage slots must be preserved to prevent storage clashing.

*Pool storage is not sequential: each variable is wrapped into a struct which is assigned a storage slot.*

### constructor

```solidity
constructor() internal
```

### Accounts

```solidity
struct Accounts {
  mapping(address => struct ISmartPoolState.UserAccount) userAccounts;
}
```

### accounts

```solidity
function accounts() internal pure returns (struct MixinStorage.Accounts s)
```

### pool

```solidity
function pool() internal pure returns (struct Pool s)
```

### PoolWrapper

Pool initialization struct wrapper.

*Allows initializing pool as struct for better readability.*

#### Parameters

| Name | Type | Description |
| ---- | ---- | ----------- |

```solidity
struct PoolWrapper {
  struct Pool pool;
}
```

### poolWrapper

```solidity
function poolWrapper() internal pure returns (struct MixinStorage.PoolWrapper s)
```

### poolParams

```solidity
function poolParams() internal pure returns (struct ISmartPoolState.PoolParams s)
```

### poolTokens

```solidity
function poolTokens() internal pure returns (struct ISmartPoolState.PoolTokens s)
```

### activeTokensSet

```solidity
function activeTokensSet() internal pure returns (struct AddressSet s)
```

### activeApplications

```solidity
function activeApplications() internal pure returns (struct ApplicationsSlot s)
```

### Operator

```solidity
struct Operator {
  mapping(address => mapping(address => bool)) isApproved;
}
```

### operators

```solidity
function operators() internal pure returns (struct MixinStorage.Operator s)
```

### delegation

```solidity
function delegation() internal pure returns (struct DelegationData s)
```

### acceptedTokensSet

```solidity
function acceptedTokensSet() internal pure returns (struct AddressSet s)
```


# State


# MixinPoolState

## MixinPoolState

### balanceOf

```solidity
function balanceOf(address who) external view returns (uint256)
```

Returns token balance for an address.

#### Parameters

| Name | Type    | Description                   |
| ---- | ------- | ----------------------------- |
| who  | address | Address to query balance for. |

#### Return Values

| Name | Type    | Description           |
| ---- | ------- | --------------------- |
| \[0] | uint256 | Number of units held. |

### getAcceptedMintTokens

```solidity
function getAcceptedMintTokens() external view returns (address[] tokens)
```

Returns the list of accepted mint tokens.

#### Return Values

| Name   | Type       | Description               |
| ------ | ---------- | ------------------------- |
| tokens | address\[] | Array of token addresses. |

### getActiveApplications

```solidity
function getActiveApplications() external view returns (uint256 packedApplications)
```

Returns the active application flags.

*Grg staking is always queried regardless of the active bit.*

#### Return Values

| Name               | Type    | Description                                  |
| ------------------ | ------- | -------------------------------------------- |
| packedApplications | uint256 | Packed value of bitmap encoded active flags. |

### getActiveTokens

```solidity
function getActiveTokens() external view returns (struct ISmartPoolState.ActiveTokens tokens)
```

Returns the list of active tokens and the base token.

*Base token is always active.*

#### Return Values

| Name   | Type                                | Description                                 |
| ------ | ----------------------------------- | ------------------------------------------- |
| tokens | struct ISmartPoolState.ActiveTokens | Tuple of active tokens list and base token. |

### getPoolStorage

```solidity
function getPoolStorage() external view returns (struct ISmartPoolState.ReturnedPool poolInitParams, struct ISmartPoolState.PoolParams poolVariables, struct ISmartPoolState.PoolTokens poolTokensInfo)
```

Returns the aggregate pool generic storage.

#### Return Values

| Name           | Type                                | Description                           |
| -------------- | ----------------------------------- | ------------------------------------- |
| poolInitParams | struct ISmartPoolState.ReturnedPool | The pool's initialization parameters. |
| poolVariables  | struct ISmartPoolState.PoolParams   | The pool's variables.                 |
| poolTokensInfo | struct ISmartPoolState.PoolTokens   | The pool's tokens info.               |

### getUserAccount

```solidity
function getUserAccount(address who) external view returns (struct ISmartPoolState.UserAccount)
```

Returns a pool holder's account struct.

#### Return Values

| Name | Type                               | Description         |
| ---- | ---------------------------------- | ------------------- |
| \[0] | struct ISmartPoolState.UserAccount | UserAccount struct. |

### name

```solidity
function name() external view returns (string)
```

Returns a string of the pool name.

*Name maximum length 31 bytes.*

#### Return Values

| Name | Type   | Description         |
| ---- | ------ | ------------------- |
| \[0] | string | String of the name. |

### owner

```solidity
function owner() external view returns (address)
```

Returns the address of the owner.

#### Return Values

| Name | Type    | Description           |
| ---- | ------- | --------------------- |
| \[0] | address | Address of the owner. |

### totalSupply

```solidity
function totalSupply() external view returns (uint256)
```

Returns the total amount of issued tokens for this pool.

#### Return Values

| Name | Type    | Description                    |
| ---- | ------- | ------------------------------ |
| \[0] | uint256 | Number of total issued tokens. |

### decimals

```solidity
function decimals() public view returns (uint8)
```

### getPool

```solidity
function getPool() public view returns (struct ISmartPoolState.ReturnedPool)
```

Returns the struct containing pool initialization parameters.

*Symbol is stored as bytes8 but returned as string in the returned struct, unlocked is omitted as alwasy true.*

#### Return Values

| Name | Type                                | Description          |
| ---- | ----------------------------------- | -------------------- |
| \[0] | struct ISmartPoolState.ReturnedPool | ReturnedPool struct. |

### getPoolParams

```solidity
function getPoolParams() public view returns (struct ISmartPoolState.PoolParams)
```

Returns the struct compaining pool parameters.

#### Return Values

| Name | Type                              | Description        |
| ---- | --------------------------------- | ------------------ |
| \[0] | struct ISmartPoolState.PoolParams | PoolParams struct. |

### getPoolTokens

```solidity
function getPoolTokens() public view returns (struct ISmartPoolState.PoolTokens)
```

Returns the struct containing pool tokens info. Unitary value is the last stored unitary value.

#### Return Values

| Name | Type                              | Description        |
| ---- | --------------------------------- | ------------------ |
| \[0] | struct ISmartPoolState.PoolTokens | PoolTokens struct. |

### symbol

```solidity
function symbol() public view returns (string)
```

Returns a string of the pool symbol.

#### Return Values

| Name | Type   | Description           |
| ---- | ------ | --------------------- |
| \[0] | string | String of the symbol. |

### isOperator

```solidity
function isOperator(address holder, address operator) public view returns (bool)
```

### getDelegatedAddresses

```solidity
function getDelegatedAddresses(bytes4 selector) external view returns (address[])
```

Returns all addresses currently granted delegated write access to a selector.

#### Parameters

| Name     | Type   | Description                             |
| -------- | ------ | --------------------------------------- |
| selector | bytes4 | The adapter function selector to query. |

#### Return Values

| Name | Type       | Description |
| ---- | ---------- | ----------- |
| \[0] | address\[] |             |

### getDelegatedSelectors

```solidity
function getDelegatedSelectors(address delegated) external view returns (bytes4[])
```

Returns all selectors currently delegated to an address.

#### Parameters

| Name      | Type    | Description           |
| --------- | ------- | --------------------- |
| delegated | address | The address to query. |

#### Return Values

| Name | Type      | Description |
| ---- | --------- | ----------- |
| \[0] | bytes4\[] |             |

### \_getActiveApplications

```solidity
function _getActiveApplications() internal view returns (uint256)
```

virtual methods

### \_getFeeCollector

```solidity
function _getFeeCollector() internal view returns (address)
```

### \_getMinPeriod

```solidity
function _getMinPeriod() internal view returns (uint48)
```

### \_getSpread

```solidity
function _getSpread() internal view returns (uint16)
```

\_Returns the spread, or *MAX\_SPREAD if not set*

### \_getTokenJar

```solidity
function _getTokenJar() internal view returns (address)
```


# MixinPoolValue

## MixinPoolValue

A contract that retrieves smart pool token balances and computes their base token value.

### BaseTokenPriceFeedError

```solidity
error BaseTokenPriceFeedError()
```

### \_updateNav

```solidity
function _updateNav() internal returns (struct NavComponents components)
```

Uses transient storage to keep track of unique token balances.

*With null total supply a pool will return the last stored value.*

### \_getActiveApplications

```solidity
function _getActiveApplications() internal view virtual returns (uint256)
```

virtual methods


# MixinStorageAccessible

## MixinStorageAccessible

See <https://github.com/gnosis/util-contracts/blob/bb5fe5fb5df6d8400998094fb1b32a178a47c3a1/contracts/StorageAccessible.sol>

### getStorageAt

```solidity
function getStorageAt(uint256 offset, uint256 length) public view returns (bytes)
```

Reads `length` bytes of storage in the currents contract.

#### Parameters

| Name   | Type    | Description                                                                    |
| ------ | ------- | ------------------------------------------------------------------------------ |
| offset | uint256 | - the offset in the current contract's storage in words to start reading from. |
| length | uint256 | - the number of words (32 bytes) of data to read.                              |

#### Return Values

| Name | Type  | Description                               |
| ---- | ----- | ----------------------------------------- |
| \[0] | bytes | Bytes string of the bytes that were read. |

### getStorageSlotsAt

```solidity
function getStorageSlotsAt(uint256[] slots) public view returns (bytes)
```

Reads bytes of storage at different storage locations.

*Returns a string with values regarless of where they are stored, i.e. variable, mapping or struct.*

#### Parameters

| Name  | Type       | Description                               |
| ----- | ---------- | ----------------------------------------- |
| slots | uint256\[] | The array of storage slots to query into. |

#### Return Values

| Name | Type  | Description                                                   |
| ---- | ----- | ------------------------------------------------------------- |
| \[0] | bytes | Bytes string composite of different storage locations' value. |


# Sys


# MixinAbstract

## MixinAbstract

This contract makes it easy for clients to track ERC20.

### transfer

```solidity
function transfer(address to, uint256 value) external returns (bool success)
```

*Non-implemented ERC20 method.*

### transferFrom

```solidity
function transferFrom(address from, address to, uint256 value) external returns (bool success)
```

*Non-implemented ERC20 method.*

### approve

```solidity
function approve(address spender, uint256 value) external returns (bool success)
```

*Non-implemented ERC20 method.*

### allowance

```solidity
function allowance(address owner, address spender) external view returns (uint256)
```

*Non-implemented ERC20 method.*




---

[Next Page](/llms-full.txt/1)

