# Glossary Source: https://tech.ramses.xyz/concepts/glossary ## Automated Market Maker An automated market maker is a smart contract on a supported EVM network that holds liquidity reserves. Users trade against those reserves at prices determined by the pool's rules. Depending on pool configuration, liquidity providers may receive swap fees, emissions, or both. ## Asset While a digital asset can take many forms, Ramses pools pair ERC20 tokens. Concentrated-liquidity positions are represented as ERC721 NFTs, while DLMM positions are represented as fungible balances for individual bin IDs. ## Active Bin The DLMM bin at the current pool price. It may contain both token X and token Y. A swap changes the active bin when it exhausts available liquidity and crosses to another non-empty bin. ## Bin A discrete DLMM price point with its own token reserves and fungible LP share supply. ## Bin Step The geometric price difference between adjacent DLMM bins, expressed in basis points. `binStep = 1` means `0.01%`. ## Concentrated Liquidity Liquidity that is allocated within a determined price range. ## Constant Product Formula A reserve relationship used by volatile Ramses Legacy pools: `x * y = k`. Ramses stable pools, concentrated-liquidity pools, and DLMM bins use different mathematics. ## Composition Fee A DLMM fee charged when liquidity is added to the active bin in a ratio that differs from the bin's current composition. The deposit performs an implicit composition swap. ## Core Smart contracts that are considered foundational, and are essential for Ramses to exist. Upgrading to a new version of core would require deploying an entirely new set of smart contracts on supported networks and would be considered a new version of the Ramses Protocol. ## DLMM Discrete Liquidity Market Maker. A pool model that divides a geometric price grid into fixed-price bins and tracks LP ownership separately for each bin. ## DLMM Token The ERC1155-like per-bin share accounting embedded in a `DLMMPool`. It supports batched balances, transfers, and approvals but intentionally omits ERC1155 receiver callbacks and token URIs. ## ERC20 ERC20 tokens are fungible tokens on supported blockchain networks. Ramses expects standard transfer semantics; fee-on-transfer, rebasing, and other non-standard behavior requires separate [integration review](/concepts/protocol/integration-issues). ## Factory A smart contract that deploys pool contracts. The same ERC20 pair can have multiple pools distinguished by tick spacing, fee configuration, or DLMM bin step. ## Flash Swap A trade that uses the tokens purchased before paying for them. ## Invariant A mathematical relationship or state constraint preserved by a pool. Legacy volatile pools use the constant-product relationship `x * y = k`; concentrated-liquidity and DLMM pools use different model-specific accounting. ## Liquidity Provider / "LP" A liquidity provider is someone who deposits ERC20 tokens into a given liquidity pool. LPs take on price and smart-contract risk and may earn LP-retained fees, emissions, or both according to active liquidity and pool configuration. ## Liquidity Digital assets that are stored in a Ramses pool contract, and are able to be traded against by traders. ## Mid Price The price between the available buy and sell prices. In Ramses Legacy pools, it is derived from reserves; in concentrated-liquidity pools, from the current square-root price and tick; in DLMM pools, from the active bin ID and bin step. ## Observation An instance of historical price and liquidity data of a given pair. ## Pair A smart contract deployed from a Ramses v1 or v2 factory contract that enables trading between two ERC20 tokens. Pair contracts are now called Pools in v3. ## Periphery External smart contracts that are useful, but not required for Ramses to exist. New periphery contracts can always be deployed without migrating liquidity. ## Pool A contract that pairs two ERC20 assets. Concentrated-liquidity pools may differ by tick spacing, while DLMM pools may differ by bin step, even for the same token pair. ## Position An owner's liquidity in a pool. A concentrated-liquidity position is defined by lower and upper ticks and represented as an NFT. A DLMM position is the collection of the owner's per-bin share balances. ## Price Impact The difference between the mid-price and the execution price **caused by trade size relative to available liquidity**. Its mechanics depend on the pool's curve, active ranges, or discrete bin grid. ## Protocol Fees The configured portion of fees routed out of LP accounting to the protocol fee collector. The collector sends them to treasury or, for a live gauged pool, to its voter distribution path. ## Range An interval over which liquidity is allocated. Concentrated-liquidity ranges use lower and upper ticks; DLMM ranges use selected bin IDs. ## Range Order An approximation of a limit order, in which a single asset is provided as liquidity across a specified range, and is continuously swapped to the destination address as the spot price crosses the range. ## Reserves The liquidity available within a pair. This was more commonly referenced before concentrated liquidity was introduced. ## Slippage The total difference between the expected price at the time of submitting a transaction and the actual execution price, which may include price impact and other market movements that occur before the transaction is mined. ## Spot Price The current price of a token relative to another within a given pair. ## Swap Fees Fees charged during swaps. Their destination depends on pool type and configuration: they may remain with LPs, route to protocol treasury, or route to voters. ## Tick Interval The price space between two nearest ticks. ## Tick The boundaries between discrete areas in price space. ## x(3,3) A governance model built around converting RAM into xRAM, staking that xRAM in `VoteModule`, and using the resulting balance to direct weekly emissions. The current Ramses contracts are address-based and do not use veNFT voting. ## xRAM The transfer-restricted ERC20 governance token minted by `XRam.sol`. Users convert RAM into xRAM, then stake xRAM in `VoteModule` to obtain voting power for `Voter`. ## HyperRAM The ERC4626 liquid governance wrapper minted by `R33.sol`. The contract source is named `R33`, while the token it mints is `hyperRAM`, backed by xRAM staked in `VoteModule`. ## HyperEVM The EVM-compatible execution layer of Hyperliquid. Ramses contracts are deployed here. Note: HyperEVM is separate from HyperCore (the L1 for Hyperliquid Perps). ## Governance-Adjustable Fees Ramses concentrated-liquidity pools allow governance to adjust swap fees per pool via `factory.setFee(pool, fee)`. DLMM pools use separate static and variable fee parameters; their variable component responds on-chain as swaps move across bins. ## Variable Fee The dynamic component of a DLMM swap fee. It rises with the pool's on-chain volatility accumulator and bin step, then decays according to configured filter, decay, and reduction parameters. ## MEV (Maximal Extractable Value) Value extracted by transaction ordering. Ramses captures MEV through arbitrage mechanisms that execute during swaps, returning value to the protocol rather than external searchers. ## Gauge A reward contract associated with a pool. For CL pools, Ramses uses non-custodial gauges: the pool position remains an NFT, while emissions and reward eligibility are coordinated through the gauge, voter, and position-manager stack. ## Emissions RAM tokens minted by `Minter`, routed into `Voter`, and then distributed to gauges according to the vote weights recorded for that weekly period. # Concepts Overview Source: https://tech.ramses.xyz/concepts/overview # Ramses Concepts This section explains the on-chain mechanics that show up throughout the Ramses contracts, API, and integration guides. ## What is Ramses? Ramses is a multi-pool DEX with: * Weekly period-based liquidity accounting * Discrete-liquidity pools built from fixed-price bins * Gauge-directed emissions * Protocol-fee routing to treasury and voter markets * An address-based governance stack built around `xRAM`, `VoteModule`, `Voter`, and `AccessHub` * A liquid governance wrapper exposed through `R33` / `hyperRAM` ## Core Mechanics ### 1. Concentrated liquidity with weekly accounting Ramses extends Uniswap V3-style pools with weekly accounting that is later used by gauges and reward distributors. * [Learn about Concentrated Liquidity →](./protocol/concentrated-liquidity) ### 2. DLMM liquidity bins DLMM pools place liquidity into discrete, fixed-price bins. LP ownership is tracked as a fungible share balance for each bin rather than as one range NFT. * [Learn about DLMM & Liquidity Bins →](./protocol/dlmm) ### 3. Non-custodial gauge rewards CL positions can earn rewards without moving the underlying pool liquidity into a separate staking contract. * [Learn about the Protocol →](./ramses-protocol) ### 4. xRAM governance stack The current governance model is address-based: * `XRam.sol` converts RAM into transfer-restricted `xRAM` * `VoteModule.sol` holds staked xRAM and exposes voting power * `Voter.sol` stores votes for the next weekly period * `FeeDistributor.sol` pays rewards to voter addresses based on periodized vote weight * [Learn about Token Contracts & Emissions →](./tokenomics) ### 5. Liquid governance wrapper `R33.sol` is the vault contract for the liquid governance wrapper. The token it mints is `hyperRAM`, an ERC4626 share token backed by xRAM staked in `VoteModule`. * [Learn about Token Contracts & Emissions →](./tokenomics) ### 6. Governance routing through AccessHub Operational changes across pools, gauges, xRAM, fee routing, and vault automation are coordinated through `AccessHub`. * [Learn about the Contract Architecture →](../contracts/overview) ## Key Concepts to Understand | Concept | Description | Learn More | | -------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------- | | **Concentrated Liquidity** | Providing liquidity inside custom price ranges | [Guide](./protocol/concentrated-liquidity) | | **DLMM** | Providing per-bin liquidity on a discrete geometric price grid | [Guide](./protocol/dlmm) | | **Weekly Periods** | Contract time is tracked as `block.timestamp / 1 weeks` | [Guide](./tokenomics#weekly-periods) | | **GaugeV3** | CL emissions distribution for active pools | [Guide](./tokenomics#fee-routing-and-incentives) | | **xRAM** | Transfer-restricted governance token created from RAM | [Guide](./tokenomics#xram) | | **VoteModule** | Contract that holds staked xRAM and exposes voting power | [Guide](./tokenomics#votemodule) | | **Voter** | Tracks votes, gauges, emissions, and claims | [Guide](./tokenomics#voter-and-weekly-periods) | | **hyperRAM** | ERC4626 liquid wrapper minted by `R33.sol` | [Guide](./tokenomics#r33--hyperram) | | **AccessHub** | Role, multisig, and timelock control layer | [Guide](../contracts/reference/governance/AccessHub) | | **API** | Indexed and on-chain data surface for pools and protocol metrics | [Guide](/users-api-reference/overview) | ## Getting Started ### For Traders 1. Understand [concentrated liquidity and swaps](./protocol/concentrated-liquidity) 2. Understand [DLMM bins and dynamic fees](./protocol/dlmm) 3. Learn [pool fee behavior and pool selection](./protocol/fees) 4. Explore [pool and route concepts](./protocol/swaps) ### For Liquidity Providers 1. Learn [how active ranges work](./protocol/concentrated-liquidity) 2. Learn [how per-bin DLMM positions work](./protocol/dlmm) 3. Understand [weekly reward accounting](./tokenomics#voter-and-weekly-periods) 4. Review the [contracts overview](../contracts/overview) ### For Governance Participants 1. Learn [how RAM, xRAM, VoteModule, and Voter fit together](./tokenomics) 2. Review [xRAM conversion and exit semantics](./tokenomics#xram) 3. Read [the Voter reference](../contracts/reference/governance/Voter) ### For Developers and Integrators 1. Review the [contracts overview](../contracts/overview) 2. Follow the [DLMM integration guide](../contracts/guides/dlmm/integration) 3. Use the [REST API overview](/users-api-reference/overview) 4. Explore the [contract references](../contracts/reference/overview) 5. Follow the [local environment guide](../contracts/guides/local-environment) ## Additional Resources * [Ramses V3 Contracts Repository](https://github.com/RamsesExchange/ramses-v3-contracts) * [ConsenSys Diligence Audit](https://diligence.security/audits/2024/08/ramses-v3/) * [Cantina / Spearbit Audit](https://cantina.xyz/portfolio/ramses-exchange) * [Code4rena Audit Report](https://code4rena.com/reports/2024-10-ramses-exchange) * [Contract Addresses](https://docs.ramses.xyz/pages/contract-addresses) * [Research Papers](./research) ## Community and Support * [Official Documentation](https://docs.ramses.xyz) * [Discord Community](https://discord.gg/ramses) * [Twitter/X](https://twitter.com/RamsesExchange) * [GitHub](https://github.com/RamsesExchange) # Concentrated Liquidity & Period-Based Accounting Source: https://tech.ramses.xyz/concepts/protocol/concentrated-liquidity
*** Ramses implements concentrated liquidity based on Uniswap V3's core math, but extends it with: * **Period-based accounting system** for weekly reward distribution * **Governance-adjustable fees** decoupled from tick spacing * **Gauge-integrated emission tracking** at the protocol core * **Competitive farming** where in-range, active liquidity earns more ## Concentrated Liquidity Overview Ramses V3 uses concentrated liquidity (as introduced in Uniswap V3), where LPs allocate capital within custom price ranges rather than across the full curve. A position is **in-range** when the current tick falls between its `tickLower` and `tickUpper` — only in-range positions earn swap fees and gauge rewards. ## Ticks and Price Discretization ### Tick Basics **Ticks** partition continuous price space into discrete boundaries: * Each tick represents a **0.01% price change** * Formula: `price = 1.0001^tick` * Example: tick 0 = price 1.0, tick 100 = price 1.01005 ### Tick Spacing **Tick spacing** determines minimum distance between usable ticks: | Tick Spacing | Min Price Movement | Use Case | | ------------ | ------------------ | ------------------------------ | | 1 | 0.01% | Ultra-stable pairs (USDC/USDT) | | 10 | 0.10% | Correlated assets (ETH/stETH) | | 60 | 0.60% | Standard pairs (ETH/USDC) | | 200 | 2.00% | High-volatility pairs | **Why tick spacing matters**: * Tighter spacing = more granular positioning * Wider spacing = fewer active ticks, lower gas costs * Matched to expected volatility and pool characteristics ### Tick Crossing When the price crosses a tick boundary: 1. Contract **switches to new tick interval** 2. **Activates/deactivates** liquidity at that tick 3. **Gas cost increases** for the transaction that crosses the tick 4. **Updates tick state** for fee accrual and period tracking ## Period-Based Accounting System This is the most significant difference from Uniswap V3. Ramses implements **weekly period-based accounting** to enable fair gauge reward distribution based on time-weighted active liquidity. ### The Problem with Snapshot-Based Rewards Traditional liquidity mining uses snapshots: * "You have X liquidity at snapshot time = Y% of rewards" * Incentivizes gaming: Add liquidity before snapshot, remove after * Ignores actual contribution over time ### The Ramses Solution: periodSecondsInside Ramses tracks **how long each position was in-range** during each weekly period: ```solidity theme={null} periodSecondsInside = seconds the position was active (in-range) during the week ``` **Formula**: ``` Position Reward = (position.periodSecondsInside / pool.totalPeriodSecondsInside) × weeklyEmissions ``` ### Technical Implementation Ramses extends Uniswap V3's tick accounting with additional period tracking: **Standard Uniswap V3** (Tick.sol): ```solidity theme={null} struct Info { uint128 liquidityGross; int128 liquidityNet; uint256 feeGrowthOutside0X128; uint256 feeGrowthOutside1X128; int56 tickCumulativeOutside; uint160 secondsPerLiquidityOutsideX128; uint32 secondsOutside; } ``` **Ramses V3 Addition** (Tick.sol + Position.sol): ```solidity theme={null} struct Info { // ... standard fields above ... // Period-based tracking uint256 periodSecondsPerLiquidityOutsideX128; // SPL for current period mapping(uint256 => uint256) periodSecondsPerLiquidityOutsideBeforeX128; // Historical periods } ``` ### Period Transitions Every **Thursday 00:00 UTC**, a new period begins: 1. **Snapshot current state**: Record `secondsPerLiquidity` for all active ticks 2. **Initialize new period**: Reset period counters 3. **Calculate rewards**: Previous period's `periodSecondsInside` determines reward share 4. **Distribute emissions**: Gauges distribute to positions based on their period contribution ### Debt Accounting To prevent reward gaming, Ramses tracks **debt** for positions that modify liquidity mid-period: ```solidity theme={null} // When adding liquidity mid-period position.periodSecondsInsideDebt += newLiquidity × secondsElapsedThisPeriod // When calculating rewards effectivePeriodSecondsInside = raw - debt ``` This prevents: * Adding liquidity just before epoch flip for free rewards * Counting partial-period liquidity as if it existed the entire week ## Competitive Farming Model Ramses incentivizes **capital efficiency** through competitive rewards: ### Proximity Bonus Positions closer to current price earn more per unit liquidity: ``` ETH/USDC pool at $3,000 Position A: $2,950 - $3,050 (100 ticks wide, surrounds price) Position B: $2,500 - $3,500 (1000 ticks wide) Position A earns MORE rewards per ETH despite same liquidity amount ``` **Why**: Position A provides liquidity where it's most needed (near current price) ### In-Range Requirement Only **active liquidity** earns rewards: * Price in range: Accruing `periodSecondsInside` ✓ * Price out of range: `periodSecondsInside` frozen ✗ **Strategy**: LPs must actively manage positions to keep them in-range ## Integration Considerations ### For Integrators 1. **Query position status**: ```solidity theme={null} (uint256 tokensOwed0, uint256 tokensOwed1) = pool.positions(positionKey); ``` 2. **Calculate periodSecondsInside** (complex, see Position.sol): ```solidity theme={null} // Requires tick data, period boundaries, and position info // Best practice: Use view functions from GaugeV3 contract uint256 earned = gauge.earned(tokenId); ``` 3. **Monitor tick crossings** via events: ```solidity theme={null} event Swap(...); event Mint(...); event Burn(...); ``` ### Gas Considerations Period-based accounting adds minor gas overhead: * **Tick crossing**: +\~5,000 gas for period updates * **Position operations**: +\~10,000 gas for debt accounting * **Reward claims**: Similar to standard V3 **Optimization**: Batch operations when possible (multi-position management, claim + collect combos) ## Additional Resources * [Fees](/concepts/protocol/fees) * [Token Contracts & Tokenomics](/concepts/tokenomics) * [Uniswap V3 Whitepaper](https://uniswap.org/whitepaper-v3.pdf) - Core math and design * [ConsenSys Diligence Audit](https://diligence.security/audits/2024/08/ramses-v3/) - Period accounting analysis *** [^1]: **Tick interval** refers to the area of price space between two nearest active ticks. # DLMM & Liquidity Bins Source: https://tech.ramses.xyz/concepts/protocol/dlmm Discrete price bins, per-bin LP shares, dynamic fees, and Ramses fee and reward routing. # Discrete Liquidity Market Maker Ramses DLMM pools divide price space into discrete **bins**. Each bin has one fixed price and its own reserves. Swaps consume liquidity at the active bin's price and move to the next non-empty bin when that liquidity is exhausted. This differs from Ramses concentrated-liquidity pools: | | Concentrated liquidity | DLMM | | --------------------- | --------------------------------- | -------------------------------------------- | | Price unit | Tick interval | Bin | | Price inside the unit | Moves along the pool curve | Fixed | | LP position | ERC721 position over a tick range | Multi-token balance for each bin ID | | LP fee accounting | Claimable fees | Fees retained for LPs remain in bin reserves | | Trader fee | Pool-level fee set by governance | Base fee plus an on-chain variable fee | At the [Robinhood snapshot at block 22,674,244](/contracts/reference/dlmm/deployments), DLMM is fee-only, the factory is not connected to `Voter`, and sampled pools do not have rewarder hooks. The rewarder and 100%-to-voters flow described below are optional protocol architecture. ## Bins and the price grid Each pool has an immutable `binStep`, expressed in basis points. One basis point is `0.01%`, so `binStep = 1` creates a `0.01%` geometric step between adjacent bins. For bin ID `id`: ```text theme={null} price(id) = (1 + binStep / 10,000)^(id - 2^23) ``` The contracts represent this price as an unsigned 128.128 fixed-point number. Use `getPriceFromId()` and `getIdFromPrice()` rather than reimplementing the fixed-point math unless exact parity has been tested. Inside one bin, liquidity follows a constant-sum relationship: ```text theme={null} L = price × amountX + amountY ``` The active bin may contain both assets. Relative to the pool's actual `tokenX` and `tokenY` ordering: * Bins below the active ID may contain only `tokenY` * The active bin may contain both `tokenX` and `tokenY` * Bins above the active ID may contain only `tokenX` Always read `getTokenX()` and `getTokenY()` from the pool. Display order in an interface is not a substitute for contract order. ## Swaps and price impact A swap executes against the active bin and then traverses the pool's sparse tree of non-empty bins. * Execution within one bin has no curve-driven price movement * Crossing `N` bin IDs changes the execution price by `N` geometric steps; sparse traversal may skip empty bins * A large trade can cross many bins, so its average execution price can differ materially from the starting price * A swap reverts if the selected route cannot completely satisfy the requested amount Direct pool swaps expect input tokens to have already been transferred and do not expose caller-facing deadline or minimum-output protection. Users and integrators should normally use `DLMMRouter`. ## LP positions `DLMMPool` inherits an ERC1155-like multi-token implementation: * Each bin ID is a separate fungible LP share * `balanceOf(owner, binId)` returns an owner's share balance in that bin * `totalSupply(binId)` returns all shares issued for that bin * `balanceOfBatch()` reads multiple owner/bin pairs * `approveForAll()` authorizes a router or manager to burn or transfer bin shares The token intentionally does not implement ERC1155 receiver callbacks or token URIs. Integrations should use the exposed `DLMMToken` interface instead of assuming complete ERC1155 behavior. When liquidity is removed, each bin returns `tokenX` and `tokenY` pro rata to the shares burned. LP swap fees retained by the pool increase bin reserves and therefore increase the redemption value of those shares. There is no separate LP fee claim for that retained portion. ## Adding liquidity The router accepts independent token distributions across signed offsets from the pool's active bin at execution: ```text theme={null} depositBinId = liveActiveId + deltaId ``` When constructing the transaction, read the pool's active ID, use it as `activeIdDesired`, and calculate: ```text theme={null} deltaId = desiredBinIdAtQuote - activeIdDesired ``` The router checks that `liveActiveId` remains within `idSlippage` of `activeIdDesired`, but it uses `liveActiveId` to calculate the actual deposit bins. If the active ID moves within the permitted range, the entire distribution moves with it. Set `idSlippage = 0` when absolute bin placement is required. `distributionX` and `distributionY` use `1e18`-scaled weights. Sum a token's array to `1e18` to allocate its full supplied amount. A sum below `1e18` leaves the remainder for `refundTo`; over-allocation can revert and should be rejected by the integration. Important safeguards: * Read the active ID immediately before constructing the transaction * Set `idSlippage`, token minimums, and a deadline * Set `to` to the router caller; the public add-liquidity functions reject any other LP recipient * Set `refundTo` deliberately; unused amounts are returned there, which may differ from the LP recipient `to` * Expect a composition fee when adding an imbalanced amount to the active bin, because the pool performs an implicit composition swap * Estimate gas and batch very wide distributions ## Swap fees The trader-paid DLMM fee is: ```text theme={null} totalFee = baseFee + variableFee ``` The static component is: ```text theme={null} baseFee = baseFactor × binStep × 1e10 ``` where `1e18` represents `100%`. In basis points: ```text theme={null} baseFeeBps = baseFactor × binStep / 10,000 ``` The variable component rises quadratically with the volatility accumulator and `binStep`. The accumulator increases when on-chain swaps move across bins, decays according to the pool's filter and decay settings, and is capped by `maxVolatilityAccumulator`. The variable fee does not observe CEX prices or off-chain volatility. It reacts only after DLMM swaps move through the on-chain price grid. The main fee parameters are: | Parameter | Purpose | | -------------------------- | ---------------------------------------------------- | | `baseFactor` | Static fee multiplier | | `filterPeriod` | Minimum interval before reference state refreshes | | `decayPeriod` | Time after which the volatility reference resets | | `reductionFactor` | Fraction of volatility retained during partial decay | | `variableFeeControl` | Sensitivity of the variable fee | | `maxVolatilityAccumulator` | Cap on the dynamic response | | `protocolShare` | Portion of swap fees routed out of LP reserves | The total trader fee is capped at `10%`. `protocolShare` changes where the collected fee goes; it does not add another fee to the trade. ## Fee and reward routing Ramses' Robinhood product policy distinguishes fee-only and gauged DLMM pools: | Pool state | LP share of swap fees | Protocol/voter share | LP emissions | | ------------------------------------ | --------------------: | ---------------------------------------------: | -------------------------- | | Robinhood fee-only / ungauged policy | 95% | 5% to protocol treasury | None | | Gauged policy | 0% | 100% to the pool's `FeeDistributor` for voters | RAM through `DLMMRewarder` | For an ungauged pool, the protocol portion collected by `DLMMFeeCollector` goes to treasury. The 100%-to-voters gauged policy requires the collector's independently mutable `treasuryFees` value to be zero; otherwise that configured skim goes to treasury before the remainder reaches `FeeDistributor`. Because fee parameters and protocol share are governance-configurable, integrations must read `getStaticFeeParameters()` from the pool instead of inferring the split from a label. ## Rewarder hooks and anti-JIT behavior The optional `DLMMRewarder` is a pool hook and the DLMM equivalent of an emission target: * `Voter` sends RAM emissions to the rewarder * The rewarder distributes RAM over a configurable band of at most 11 bins around the active bin * Rewards are weighted by liquidity valued at the active-bin price, then divided among each bin's share holders * Claims are made by the owner for their own address When the rewarder hook is linked: * Minting to a different recipient requires an authorized manager * All LP-share batch transfers are disabled while the rewarder is linked * Burning liquidity remains available * Recently modified liquidity may forfeit only newly accrued rewards during the anti-JIT cooldown; LP principal is not seized Rewarder implementations are upgradeable through their beacon. Pool contracts are deterministic immutable clones; changing the factory's pool implementation affects future pools rather than existing pool clones. ## Integration checklist 1. Discover pools through `DLMMFactory`; do not manufacture pool addresses from UI data. 2. Confirm the pool's actual token order, active ID, bin step, static fee parameters, and hook state. 3. Quote the full amount and reject partial quotes where `amountInLeft` or `amountOutLeft` is non-zero. 4. Use router deadlines, minimum amounts, and active-ID slippage. 5. Index per-bin balances and `TransferBatch`, `DepositedToBins`, `WithdrawnFromBins`, and `Swap` events. 6. Treat hooks and fee settings as mutable governance-controlled state. 7. Do not assume the generated HyperEVM API Reference indexes Robinhood DLMM data. ## Additional resources * [DLMM Integration Guide](/contracts/guides/dlmm/integration) * [DLMM Contract Architecture](/contracts/reference/dlmm/overview) * [Robinhood DLMM Deployments](/contracts/reference/dlmm/deployments) * [Fees](/concepts/protocol/fees) # Fees Source: https://tech.ramses.xyz/concepts/protocol/fees Concentrated-liquidity and DLMM trader fees, LP accounting, and protocol routing. # Fee Architecture Ramses uses two distinct fee models: * Concentrated-liquidity pools have a pool-level fee set by governance * DLMM pools combine a base fee with a variable fee driven by on-chain bin movement For concentrated liquidity, Ramses decouples tick spacing from fees. Each tick spacing has a default initial fee, but governance can adjust an individual pool through `factory.setFee(pool, newFee)`. DLMM uses a separate parameter set described below. ## Concentrated-Liquidity Fee Model ### How Fees Are Set Concentrated-liquidity fees are **not determined by an on-chain algorithm during swaps**. Instead: 1. Each tick spacing has a **default initial fee** set in the factory's `tickSpacingInitialFee` mapping 2. When a pool is created, it inherits the initial fee for its tick spacing 3. Governance can **adjust any pool's fee** at any time via `RamsesV3Factory.setFee(pool, fee)` 4. The pool stores its current fee and applies it to all swaps ```solidity theme={null} // Factory sets the fee for a specific pool (governance only) function setFee(address _pool, uint24 _fee) external; // Pool stores and exposes its fee function fee() external view returns (uint24); ``` ### Default Tick Spacing / Fee Mapping | Tick Spacing | Default Fee | Min Price Movement | Typical Use Case | Example Pairs | | ------------ | ------------- | ------------------ | ------------------- | ---------------------------- | | **1** | 0.01% (100) | 0.01% | Ultra-stable | Stablecoin pairs (USDC/USDT) | | **5** | 0.025% (250) | 0.05% | Highly correlated | Pegged assets | | **10** | 0.05% (500) | 0.10% | Correlated assets | ETH/wstETH, BTC/WBTC | | **50** | 0.30% (3000) | 0.50% | Standard volatility | Most token pairs | | **100** | 1.00% (10000) | 1.00% | Higher volatility | Less liquid pairs | | **200** | 2.00% (20000) | 2.00% | High volatility | Exotic/new tokens | Fees are denominated in parts per million (1/1,000,000). For example, `100` = 0.01%, `3000` = 0.30%. ## DLMM Fee Model DLMM charges: ```text theme={null} totalFee = baseFee + variableFee ``` The base fee is: ```text theme={null} baseFee = baseFactor × binStep × 1e10 ``` where `1e18` represents 100%. Expressed in basis points: ```text theme={null} baseFeeBps = baseFactor × binStep / 10,000 ``` The variable fee rises quadratically with `volatilityAccumulator × binStep`. The accumulator increases when swaps move across bins and decays according to: | Parameter | Purpose | | -------------------------- | ----------------------------------------------------------- | | `filterPeriod` | Controls when the reference bin and volatility may refresh | | `decayPeriod` | Resets the volatility reference after sufficient inactivity | | `reductionFactor` | Retains a fraction of volatility during partial decay | | `variableFeeControl` | Scales the variable fee response | | `maxVolatilityAccumulator` | Caps that response | The fee observes on-chain DLMM activity only. It does not read CEX prices or an external volatility oracle. Total trader fees are capped at `10%`. Governance can update presets for future pools and static parameters on an existing pool. Integrators should quote against live pool state rather than reproduce the fee algorithm from stale configuration. ## Concentrated-Liquidity Fee Distribution ### LP Fee Collection Swap fees are distributed **pro-rata to all in-range liquidity** at the time of the swap: * **In-Range Positions**: Positions where `tickLower ≤ currentTick < tickUpper` earn fees * **Out-of-Range Positions**: Positions outside the active price earn **0 fees** * **Fee Accrual**: Fees accumulate continuously as long as a position remains in-range * **Manual Collection**: LPs must call `collect()` to claim accumulated fees (not auto-compounded) ```solidity theme={null} // Collect accumulated fees for a position (via pool directly) function collect( address recipient, uint256 index, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); ``` ### Protocol Fee Split (feeProtocol) The `feeProtocol` setting determines what percentage of swap fees are routed to the protocol (FeeCollector) vs staying with LPs. It is also denominated in parts per million (1/1,000,000). Ramses uses these target configurations: #### Gauged policy (0% to LPs, 100% to voters) The gauged policy uses `feeProtocol = 1,000,000` so all swap fees enter `FeeCollector`, plus `treasuryFees = 0` so the collector forwards that entire amount to the pool's `FeeDistributor` for xRAM voters. LPs receive emissions from the gauge instead of swap fees. Gauge association alone is not proof that both values are set. Voter and governance synchronization paths can update them independently, so integrations must read the pool and collector state. #### Fee-only policy (95% to LPs, 5% to treasury) The default fee-only policy uses `feeProtocol = 50,000` (5%). This means: * **95%** of swap fees go to LPs (collected via `pool.collect()`) * **5%** goes to the FeeCollector, which sends it to the treasury (since there's no gauge/FeeDistributor) ### Fee Flow ``` Swap → Pool Collects Fee (per pool.fee()) ↓ Split Based on feeProtocol Setting ↓ Gauged policy (feeProtocol = 1,000,000; treasuryFees = 0): └─→ 100% → FeeCollector → FeeDistributor → xRAM Voters claim Fee-only policy (feeProtocol = 50,000): ├─→ 95% → LPs (collected via pool.collect()) └─→ 5% → FeeCollector → Treasury (no FeeDistributor exists) ``` If `treasuryFees` is non-zero, the collector diverts that configured share before notifying the `FeeDistributor`. ## DLMM Fee Distribution For DLMM, `protocolShare` is measured out of `10,000` and applies to the swap fee: ```text theme={null} protocol amount = total swap fee × protocolShare / 10,000 ``` The remainder stays in bin reserves. It therefore compounds into the redemption value of per-bin LP shares rather than becoming a separately claimable balance. Ramses' Robinhood product policy is: | Pool state | LP share | Protocol/voter share | | ----------------------------- | -------: | ----------------------: | | Robinhood fee-only / ungauged | 95% | 5% to protocol treasury | | Gauged policy | 0% | 100% to voters | The optional gauged path replaces LP swap-fee retention with RAM emissions distributed by `DLMMRewarder` to eligible bins. Reaching the stated 100%-to-voters policy also requires `DLMMFeeCollector.treasuryFees = 0`; that collector value is independently mutable. At [block 22,674,244](/contracts/reference/dlmm/deployments), the Robinhood factory was not connected to `Voter`, sampled pools had no rewarder hook, and its open presets and sampled pools used `protocolShare = 500`, or 5%. `protocolShare` is mutable. Read it from `DLMMPool.getStaticFeeParameters()`; do not infer it from a pool label or from the factory's generic default constant. ## Protocol Fee Distribution **Contracts**: `FeeCollector.sol` for concentrated liquidity and `DLMMFeeCollector.sol` for DLMM. When `collectProtocolFees(pool)` is called, the relevant collector: 1. Pulls the protocol's share from the pool 2. If the pool has **no gauge** (or gauge is not alive): sends everything directly to the treasury 3. If the pool has a **live gauge**: splits fees between the FeeDistributor (for voters) and the treasury based on the `treasuryFees` ratio | Scenario | FeeDistributor (Voters) | Treasury | | ------------------- | ----------------------- | ------------------------ | | **Gauged pool** | `100% - treasuryFees` | `treasuryFees` share | | **Non-gauged pool** | N/A (no FeeDistributor) | 100% of protocol portion | ### FeeCollector Interface ```solidity theme={null} interface IFeeCollector { // Collect protocol fees from a pool and distribute to FeeDistributor + Treasury function collectProtocolFees(address pool) external; // Treasury configuration (governance) function setTreasury(address newTreasury) external; function setTreasuryFees(uint256 _treasuryFees) external; // Read state function treasury() external returns (address); function treasuryFees() external returns (uint256); } ``` ### Distribution Cycle 1. **Accumulation**: Fees accumulate in pools continuously 2. **Collection**: Anyone can call `collectProtocolFees(pool)` to trigger collection and distribution (permissionless) 3. **Voter Claims**: On gauged pools, xRAM holders claim from FeeDistributor proportional to their voting weight 4. **CL LP Claims**: On non-gauged CL pools, LPs collect their retained share via `collect()` 5. **DLMM LP Accounting**: On fee-only DLMM pools, the retained share stays in bin reserves and increases LP share value ## Integrator Considerations ### Querying Current Fees Always query or quote the current fee before estimating swap outputs. ```solidity theme={null} // Concentrated liquidity uint24 currentFee = pool.fee(); // DLMM: returns amountInLeft, amountOut, and the current fee amount (uint128 amountInLeft, uint128 amountOut, uint128 feeAmount) = dlmmPool.getSwapOut(amountIn, swapForY); ``` For DLMM, reject a quote when `amountInLeft != 0`, because the pool cannot completely fill the input. ### Slippage protection Since fees and reserves can change before execution, set appropriate slippage tolerance: ```solidity theme={null} // Use the applicable CL or DLMM quoter for the complete route. uint256 quotedOut = quote.amountOut; require(quotedOut > 0, "no complete quote"); uint256 minOut = quotedOut * 99 / 100; // example 1% slippage tolerance ``` The route quote must include token prices, decimals, fee configuration, available tick/bin liquidity, and price impact. Subtracting a fee from `amountIn` is not an output quote. ### Events ```solidity theme={null} // Emitted by factory when a pool's fee is changed event FeeAdjustment(address pool, uint24 newFee); // Emitted by factory when default protocol fee changes event SetFeeProtocol(uint24 feeProtocolOld, uint24 feeProtocolNew); // Emitted by factory when pool-specific protocol fee changes event SetPoolFeeProtocol(address pool, uint24 feeProtocolOld, uint24 feeProtocolNew); // DLMM pool fee and volatility configuration event StaticFeeParametersSet(...); // DLMM fee accounting event CompositionFees(...); event CollectedProtocolFees(...); ``` ## Additional Resources * [Concentrated Liquidity](/concepts/protocol/concentrated-liquidity) * [DLMM & Liquidity Bins](/concepts/protocol/dlmm) * [DLMM Contract Architecture](/contracts/reference/dlmm/overview) * [Token Contracts & Tokenomics](/concepts/tokenomics) * [RamsesV3Pool Reference](/contracts/reference/core/RamsesV3Pool) * [RamsesV3Factory Reference](/contracts/reference/core/RamsesV3Factory) *** [^1]: **In-range liquidity** refers to liquidity contained in any positions where `tickLower ≤ currentTick < tickUpper`, meaning the position spans both sides of the current price. # Token Integration Issues Source: https://tech.ramses.xyz/concepts/protocol/integration-issues Fee-on-transfer and rebasing tokens will not function correctly on v3. ## Fee-on-transfer Tokens Fee-on-transfer tokens will not function with our router contracts. As a workaround, the token creators may create a token wrapper or a customized router. We will not be making a router that supports fee-on-transfer tokens in the future. ## Rebasing Tokens Rebasing tokens will succeed in pool creation and swapping, but liquidity providers will bear the loss of a negative rebase when their position becomes active, with no way to recover the loss. # Oracle Source: https://tech.ramses.xyz/concepts/protocol/oracle All Ramses V3 pools can serve as oracles, offering access to historical price and liquidity data. Historical data is stored as an array of observations. At first, each pool tracks only a single observation, overwriting it as blocks elapse. This limits how far into the past users may access data. However, any party willing to pay the transaction fees may [increase the number of tracked observations](../../contracts/reference/core/RamsesV3Pool#increaseobservationcardinalitynext) (up to a maximum of `65535`), expanding the period of data availability to \~9 days or more. The oracle's maximum length makes price manipulation significantly more difficult, as the calling contract can construct a time-weighted average over any arbitrary range inside of (or fully encompassing) the length of the oracle array. ## Observations `Observation`s take the following form: ```solidity theme={null} struct Observation { // the block timestamp of the observation uint32 blockTimestamp; // the tick accumulator, i.e. tick * time elapsed since the pool was first initialized int56 tickCumulative; // the seconds per liquidity, i.e. seconds elapsed / max(1, liquidity) since the pool was first initialized uint160 secondsPerLiquidityCumulativeX128; // whether or not the observation is initialized bool initialized; } ``` `Observation`s may be retrieved via the [`observations`](../../contracts/reference/core/interfaces/pool/IRamsesV3PoolState#observations) method on v3 pools. However, this is *not* the recommended way to consume oracle data. Instead, prefer [`observe`](../../contracts/reference/core/RamsesV3Pool#observe): ```solidity theme={null} function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); ``` Each time `observe` is called, the caller must specify an array containing any number of seconds ago, denoting the times to return observations from. Note that each of the given times must be more recent (or as old as) the oldest stored observation. Note: if the times don't correspond exactly to a block in which an observation was written, a counterfactual observation will be constructed, removing the need for the caller to interpolate manually. This is one of the primary reasons to use `observe` over `observations`. Note that because the oracle is only updated at most once every block, calling `observe` with a `secondsAgo` value of `0` will return the most recently written observation, which can only be as recent as the beginning of the current block (or older). ## Tick Accumulator The tick accumulator stores the cumulative sum of the active tick at the time of the observation. The tick accumulator value increases monotonically and grows by the value of the current tick - per second. To derive the arithmetic mean tick over an interval, the caller needs to retrieve two observations, one after the other, take the delta of the two values, and divide by the time elapsed between them. Calculating a TWAP from the tick accumulator is also covered in the [**whitepaper**](https://uniswap.org/whitepaper-v3.pdf). Note that using an arithmetic mean tick to derive a price corresponds to a *geometric* mean price. See `OracleLibrary` for an example of how to use the tick accumulator. ## Liquidity Accumulator The liquidity accumulator stores the value of seconds / in-range liquidity at the time of the observation. The liquidity accumulator value increases monotonically and grows by the value of seconds / in-range liquidity - per second. To derive the harmonic mean liquidity over an interval, the caller needs to retrieve two observations, one after the other, take the delta of the two values, then divide the time elapsed by this value. Calculating TWAL is addressed in finer detail in the [**whitepaper**](https://uniswap.org/whitepaper-v3.pdf). The in-range liquidity accumulator should be used with care. Because the current tick and the current in-range liquidity can be entirely uncorrelated, there are scenarios in which taking the arithmetic mean tick and the harmonic mean liquidity over the same interval in a pool can inaccurately characterize this pool relative to another. For example, if the current tick on pool A is 0 for 5 seconds, and 100 for 5 seconds, the tick accumulator will be 50. If over this same interval, the in-range liquidity was 5000 and 50, the harmonic mean liquidity will be \~99. Compare this to pool B (composed of the same assets) where the tick was 50 and the in-range liquidity was \~99 for 10 seconds. The accumulator values will be identical, but the underlying behavior is of course quite different. ## Deriving Price From A Tick > When we use "active tick" or otherwise to refer to the current tick of a pool, we mean the lower tick boundary that is closest to the current price. When a pool is created, each token is assigned to either `token0` or `token1` based on the contract address of the tokens in the pair. Whether or not a token is `token0` or `token1` is meaningless; it is only used to maintain a fixed assignment for the purpose of relative valuation and general logic in the pool contract. Deriving an asset price from the current tick is achievable due to the fixed expression across the pool contract of token0 in terms of token1. *** An example of finding the price of WETH in a WETH / USDC pool, where WETH is `token0` and USDC is `token1`: You have an oracle reading that shows a return of `tickCumulative` as \[`70_000`, `1_070_000`], with an elapsed time between the observations of 10 seconds. We can derive the average tick over this interval by taking the difference in accumulator values (`1_070_000` - `70_000` = `1_000_000`), and dividing by the time elapsed (`1_000_000` / `10` = `100_000`). With a tick reading of `100_000`, we can find the value of `token1` (USDC) in terms of `token0` (WETH) by using the current tick as `i` in the formula `p(i) = 1.0001**i` (see 6.1 in the [whitepaper](https://uniswap.org/whitepaper-v3.pdf)). `1.0001**100_000 ≅ 22015.5` USDC / WETH *** Ticks are signed integers and can be expressed as a negative number, so for any circumstances where `token0` is of a lower value than `token1`, a negative tick value will be returned by `tickCumulative` and a relative value of `< 0` will be returned by a calculation of `token0` in terms of `token1`. # Range Orders Source: https://tech.ramses.xyz/concepts/protocol/range-orders Range orders in Ramses v3 follow the same implementation as Uniswap v3, providing limit order-like functionality through concentrated liquidity positions. Customizable liquidity positions, along with single-sided asset provisioning, allow for a new style of swapping with automated market makers: the range order. In typical order book markets, anyone can easily set a limit order: to buy or sell an asset at a specific predetermined price, allowing the order to be filled at an indeterminate time in the future. With Uniswap v3, one can approximate a limit order by providing a single asset as liquidity within a specific range. Like traditional limit orders, range orders may be set with the expectation they will execute at some point in the future, with the target asset available for withdrawal after the spot price has crossed the full range of the order. Unlike some markets where limit orders may incur fees, the range order maker generates fees while the order is filled. This is due to the range order technically being a form of liquidity provisioning rather than a typical swap. ## Possibilities of Range orders The nature of AMM design makes some styles of limit orders possible, while others cannot be replicated. The following are four examples of range orders and their traditional counterparts; the first two are possible, the second two are not. > One important distinction: range orders, unlike traditional limit orders, will be **unfilled** if the spot price crosses the given range and then reverses to recross in the opposite direction before the target asset is withdrawn. While you will be earning LP fees during this time, if the goal is to exit fully in the desired destination asset, you will need to keep an eye on the order and either manually remove your liquidity when the order has been filled or use a third party position manager service to withdraw on your behalf. ### Take-Profit Orders > The current price of a DAI / ETH pool is 1,500 DAI / ETH. You would like to sell your ETH for DAI when the price of ETH reaches 1,600 DAI / ETH. This is possible, as the price space above the spot price is denominated in the higher valued asset, ETH. You can provide ETH at a price of 1,600 DAI / ETH and have the order filled when the spot price crosses your position. Take-Profit Range Order *** ### Buy Limit Orders > The Current price of a DAI / ETH pool is 1,500 DAI / ETH. You expect that ETH will rebound after it drops to 1,000 at the next market downturn, so you would like to place a range order swapping DAI to ETH at the price of 1,000 DAI / ETH. This is possible, as the price space below the spot price is denominated in the lower-priced asset, DAI. You can provide DAI at the price of 1,000 DAI / ETH, which will be swapped for ETH when the spot price of ETH drops past 1,000 DAI / ETH. Buy Limit Range Order As the above examples show, in Uniswap v3, the two paired assets in a given pool are separated above and below the spot price, with the higher price asset available above the spot price and the lower-priced asset below. The following examples show limit order styles that are unable to be replicated due to the separation of assets in price space. *** ### Buy Stop Orders > The current price of a DAI / ETH pool is 1,500 DAI / ETH. You expect the price of ETH to rocket up to 3,000 once it hits 2,000 DAI/ ETH, So you would like to place a range order from DAI to ETH at a price of 2,000 DAI/ETH. This is not possible as the price space above 1,500 DAI / ETH is denominated in ETH - and thus, you cannot provide the DAI necessary at your desired price to be swapped into ETH. *** ### Stop-Loss Orders > The current price of a DAI / ETH pool is 1,500 DAI / ETH. You expect once the price of ETH drops to below 1,000, it will tank to 200. So you would like to place a range order from ETH to DAI at a price of 1,000. This is not possible as the price space below the spot price is denominated in DAI, and so you cannot allocate the ETH necessary at 1,000 to be swapped into DAI. *** ## Fees The fees due to your liquidity position will be denominated in both tokens of the given pair. In any of the above examples, after swapping ETH for DAI, or DAI for ETH, a small amount of both ETH and DAI will be due to your account as liquidity provisioning rewards. Approaches to concentration when setting range orders are up to the user. Selecting a wider range may generate more fees if there is price churn within your range, at the cost of increasing the risk of having your order unfilled if the spot price reverses before completing your full range. # Swaps Source: https://tech.ramses.xyz/concepts/protocol/swaps ## Introduction Swaps are the most common way of interacting with Ramses. For end-users, swapping is straightforward: a user selects an ERC-20 token that they own and a token they would like to trade it for. Executing a swap sells the currently owned tokens for the proportional[^1] amount of the tokens desired, minus the swap fee. That fee is routed according to the pool's configuration.[^2] Swapping with Ramses is a permissionless process. > note: Using web interfaces (websites) to swap via Ramses can introduce additional permission structures, and may result in different execution behavior compared to using Ramses directly. To learn more about the differences between the protocol and a web interface, see "What is Ramses?" Swaps using Ramses are different from traditional order book trades in that they are not executed against discrete orders on a first-in-first-out basis — rather, swaps execute against a passive pool of liquidity. LP fee eligibility depends on the pool model, the liquidity active at the executed prices, and the pool's configured fee routing. ## Pool Models Ramses supports more than one execution model: * Concentrated-liquidity swaps move through active tick intervals * DLMM swaps execute at one fixed-price bin at a time and cross to the next non-empty bin when needed A direct DLMM pool quote can be partial when the selected pool runs out of traversable liquidity. Reject `getSwapOut()` when `amountInLeft != 0`, and reject `getSwapIn()` when `amountOutLeft != 0`. The DLMM router handles DLMM-only paths. A mixed route that combines DLMM with concentrated-liquidity or Legacy pools requires a higher-level router or separate transactions; do not encode mixed pool types into `DLMMRouter.Path`. ## Price Impact In a traditional order-book market, a sizeable market-buy order may deplete the available liquidity of a prior limit-sell and continue to execute against a subsequent limit-sell order at a higher price. The result is the final execution price of the order is somewhere in between the two limit-sell prices against which the order was filled. Price impact affects the execution price of an AMM swap through model-specific mechanics. In a curve-based pool, the marginal price shifts continuously as the trade consumes liquidity. In a DLMM pool, execution stays at one fixed price inside a bin and changes discretely when the trade crosses bin IDs. Either path can produce an average execution price different from the starting price. As the amount of liquidity available at different price points can vary, the price impact for a given swap size will change relative to the amount of liquidity available at any given point in price space. The greater the liquidity available at a given price, the lower the price impact for a given swap size. The lesser the liquidity available, the higher the price impact. Approximate[^3] price impact is anticipated in real-time via the Ramses interface, and warnings appear if unusually high price impact will occur during a swap. Anyone executing a swap will have the ability to assess the circumstances of price impact when needed. ## Slippage The other relevant detail to consider when approaching swaps with Ramses is slippage. Slippage is the term we use to describe alterations to a given price that could occur while a submitted transaction is pending. When transactions are submitted to an EVM network, inclusion and ordering depend on that network's sequencer or validator rules. While a transaction is pending, other swaps can change pool reserves, the active tick or bin, and the applicable fee. Slippage tolerances establish a margin of change acceptable to the user beyond price impact. As long as the execution price is within the slippage range, for example 1%, the transaction will execute. If the execution price ends up outside the accepted range, the transaction will fail and the swap will not occur. A comparable situation in a traditional market would be a market-buy order executed after a delay. One can know the expected price of a market-buy order when submitted, but much can change in the time between submission and execution. ## Safety Checks Price impact and slippage can both change while a transaction is pending, which is why we have built numerous safety checks into Ramses to protect end-users from drastic changes in the execution environment of their swap. Some of the most commonly encountered safety checks: * **Deadline exceeded**: The transaction reverts after its deadline. CL and Legacy integrations may surface `Expired`; the DLMM router uses `LBRouter__DeadlineExceeded`. * **Minimum output not met**: The transaction reverts when execution would return less than the configured minimum. Legacy integrations may surface `INSUFFICIENT_OUTPUT_AMOUNT`; the DLMM router uses `LBRouter__InsufficientAmountOut`. ## Additional resources * [DLMM & Liquidity Bins](/concepts/protocol/dlmm) * [DLMM Integration Guide](/contracts/guides/dlmm/integration) * [Fees](/concepts/protocol/fees) [^1]: Proportional in this instance takes into account the relative price, fee, slippage, price impact, and other factors in an open and adversarial EVM environment. [^2]: Fee-only and gauged pools use different fee routing. See [Fees](/concepts/protocol/fees). [^3]: The Ramses interface informs the user about the circumstances of their swap, but it is not guaranteed. # The Ramses Protocol Source: https://tech.ramses.xyz/concepts/ramses-protocol ## Introduction The Ramses protocol is a permissionless automated-market-maker system for exchanging cryptocurrencies [(ERC-20 tokens)](https://ethereum.org/en/developers/docs/standards/tokens/erc-20/) on multiple blockchain networks. Its pool contracts hold liquidity under model-specific rules while governance and operational contracts manage configurable fees, incentives, and integrations. Ramses supports both concentrated-liquidity and DLMM pools: * **Concentrated Liquidity**: Uniswap V3-style ranges with Ramses period accounting * **DLMM**: Fixed-price liquidity bins with per-bin LP shares and an on-chain variable fee * **Governance-Adjustable Fees**: CL fees are decoupled from tick spacing; DLMM parameters are managed separately * **x(3,3) Deflationary Tokenomics**: 50% of RAM burned when converting to xRAM voting power * **Fee and Reward Routing**: Pool configuration determines whether fees remain with LPs, route to treasury, or route to voters Incentive accounting differs by pool model: * **Concentrated Liquidity**: Weekly period accounting tracks time-weighted active liquidity, and non-custodial gauges reward eligible positions * **DLMM**: An optional rewarder hook can stream RAM across eligible bins while LP shares remain holder-controlled and burnable [The contracts](/contracts/overview) maintain concentrated capital efficiency while adding these incentive-alignment mechanisms. The public [Ramses V3 repository](https://github.com/RamsesExchange/ramses-v3-contracts) contains the concentrated-liquidity stack; it should not be cited as the source of the DLMM implementation. See [DLMM & Liquidity Bins](/concepts/protocol/dlmm) for DLMM mechanics and the [deployment reference](/contracts/reference/dlmm/deployments) for the dated Robinhood snapshot. # Research Source: https://tech.ramses.xyz/concepts/research # The Goal Ramses is committed to furthering the space of research and employs reputable scholars to implement sophisticated research-driven solutions. # Relevant Research Ramses contributors have published papers that are informative around systems akin to that of Ramses, providing value insights for users and developers alike ## [Impermanent loss and loss-vs-rebalancing I: some statistical properties](https://arxiv.org/html/2410.00854v1) ### **Abstract** > There are two predominant metrics to assess the performance of automated market makers and their profitability for liquidity providers: ’impermanent loss’ (IL) and ’loss-versus-rebalance’ (LVR). In this short paper we shed light on the statistical aspects of both concepts and show that they are more similar than conventionally appreciated. Our analysis uses the properties of a random walk and some analytical properties of the statistical integral combined with the mechanics of a constant function market maker (CFMM). We consider non-toxic or rather unspecific trading in this paper. Our main finding can be summarized in one sentence: For Brownian motion with a given volatility, IL and LVR have identical expectation values but vastly differing distribution functions. # Resources Source: https://tech.ramses.xyz/concepts/resources This page contains helpful resources for calculations and software design related to Ramses concentrated-liquidity and DLMM pools. ## Official Resources * [**Ramses Documentation**](https://docs.ramses.xyz) * [**Ramses V3 Contracts**](https://github.com/RamsesExchange/ramses-v3-contracts) * [**Contract Addresses**](https://docs.ramses.xyz/pages/contract-addresses) * [**DLMM Mechanics**](/concepts/protocol/dlmm) * [**DLMM Integration Guide**](/contracts/guides/dlmm/integration) * [**Robinhood DLMM Deployments**](/contracts/reference/dlmm/deployments) ## Math Visualizations Ramses V3 uses the same concentrated liquidity math as Uniswap V3. These visualizations help understand the underlying mechanics: * [**Concentrated Liquidity Visualization**](https://www.desmos.com/calculator/q2kxfue441) * [**Multiple Positions Visualization**](https://www.desmos.com/calculator/oduetjzfp4) * [**AMM Calculations Spreadsheet**](https://docs.google.com/spreadsheets/d/1VH-lbF9RDUpVozGeA3BtWwypjW66MjcD1DnOYzcHmzk/edit#gid=0) ## Research * [**Uniswap V3 Whitepaper**](https://uniswap.org/whitepaper-v3.pdf) - Core concentrated liquidity math used by Ramses V3 ## Security Audits * [**ConsenSys Diligence Audit**](https://diligence.security/audits/2024/08/ramses-v3/) - Ramses V3 security audit * [**Cantina / Spearbit Audit**](https://cantina.xyz/portfolio/ramses-exchange) - Ramses Exchange audit by Cantina (Spearbit) * [**Code4rena Audit Report**](https://code4rena.com/reports/2024-10-ramses-exchange) - Ramses Exchange competitive audit # Token Contracts & Tokenomics Source: https://tech.ramses.xyz/concepts/tokenomics # Ramses Token Contracts and Emissions ## Token Stack | Layer | Contract | Purpose | | ------------------ | -------------------------- | ------------------------------------------------------ | | **RAM** | `Token.sol` + `Minter.sol` | Base emissions asset | | **xRAM** | `XRam.sol` | Transfer-restricted governance token | | **Voting power** | `VoteModule.sol` | Holds staked xRAM and exposes balances used by `Voter` | | **Liquid wrapper** | `R33.sol` | ERC4626 vault that mints `hyperRAM` shares | ## RAM and Minter The supply schedule is enforced by `Minter.sol`. ### Contract-level constants * `INITIAL_SUPPLY = 350_000_000e18` * `MAX_SUPPLY = 1_000_000_000e18` * `BASIS = 10_000` * `MAX_DEVIATION = 2_500` ### Lifecycle 1. `kickoff()` sets the RAM, voter, and xRAM addresses and mints the initial supply to the operator. 2. `initEpoch0()` starts weekly period tracking and mints the configured epoch-0 emissions to the operator. 3. `updatePeriod()` advances weekly emissions when a new period starts. 4. `updatePeriodAndRebase()` advances the period and then calls xRAM's `rebase()`. ### Emissions multiplier `updateEmissionsMultiplier()` is governance-controlled and cannot move by more than 25% in a single update. `calculateWeeklyEmissions()` also respects the global `MAX_SUPPLY`. ## xRAM `XRam.sol` is the governance token contract. ### Conversion ```solidity theme={null} function convertEmissionsToken(uint256 amount) external ``` This function: 1. Pulls `amount` RAM from the caller 2. Burns the configured slashing penalty 3. Mints `amount` xRAM to the caller The current slashing penalty is set so that at least 50% of the incoming RAM is burned. ### Exit ```solidity theme={null} function exit(uint256 amount) external returns (uint256 exitedAmount) ``` This burns xRAM and returns the post-penalty RAM amount to the caller, capped by the RAM currently held by the xRAM contract. ### Transfer restrictions xRAM is not freely transferable. Transfers only succeed when the sender or receiver is exempt, or when the transfer is part of recognized gauge and fee-distributor flows. ### Governance controls `AccessHub` can: * Pause or unpause xRAM * Manage exemption lists * Move the xRAM operator * Rescue non-RAM tokens from xRAM ## VoteModule `VoteModule.sol` is where voting power actually lives. ### Core behavior * Users deposit xRAM into `VoteModule` * `VoteModule.balanceOf(user)` is the user's voting power * `VoteModule.totalSupply()` is the total voting power in the system ### Delegation and admin permissions * `delegate(address)` is used for voting-related permissions * `setAdmin(address)` is used for broader owner-authorized operations such as fee claims ### Cooldown `VoteModule` exposes: * `cooldown()` * `unlockTime()` * `setCooldownExemption()` * `setNewCooldown()` Unless exempt, deposits and withdrawals require `block.timestamp >= unlockTime`. ## Voter and Weekly Periods `Voter.sol` is the contract that ties voting, gauges, and emissions together. ### Weekly period model The contracts use: ```solidity theme={null} period = block.timestamp / 1 weeks ``` ### Important consequence Votes are written into the **next** period, not the current one. That same next-period behavior also applies to: * `FeeDistributor.notifyRewardAmount()` * `FeeDistributor.incentivize()` ### Voting flow ```solidity theme={null} function vote(address owner, address[] calldata pools, uint256[] calldata weights) external ``` `Voter` normalizes the supplied weights against the owner's current `VoteModule.balanceOf(owner)` and records the resulting allocations for the next weekly period. ### Maintenance flow `Voter.distribute()`: * Ensures emissions are up to date through `Minter` * Routes emissions into gauges * Collects CL protocol fees through `FeeCollector` * Preserves or updates fee-split behavior depending on gauge status ## Fee Routing and Incentives Two contracts matter most here: `FeeCollector.sol` and `FeeDistributor.sol`. ### FeeCollector For CL pools, `FeeCollector`: 1. Reads accrued protocol fees from the pool 2. Sends a treasury portion according to `treasuryFees` 3. Routes the remainder into the pool's `FeeDistributor` If a pool has no active gauge, the fees go directly to the treasury. ### FeeDistributor Each fee distributor tracks: * Vote balances per owner address * Reward supply per token and per period * Claimed amounts per owner, token, and period Rewards can enter a fee distributor in two ways: * `notifyRewardAmount()` for routed protocol fees * `incentivize()` for vote incentives and bribes Claims are keyed by **owner address**, not by NFT token ID. ## R33 / hyperRAM `R33.sol` is an ERC4626 vault that wraps xRAM exposure. ### Naming * Source contract name: `R33` * Token name: `xRAM Liquid Staking Token` * Token symbol: `hyperRAM` ### Core behavior * Deposits pull xRAM from the user * The vault immediately deposits that xRAM into `VoteModule` * Vault shares are freely transferable * `totalAssets()` reflects the vault's staked xRAM balance in `VoteModule` ### Operator actions The vault operator can: * `submitVotes()` * `claimIncentives()` * `swapIncentiveViaAggregator()` * `compound()` * `unlock()` ### Locking Deposits require `isUnlocked()`, which means: * The current period has been unlocked * The system is not within one hour of the next weekly period Withdrawals and redeems do not use that same vault lock, but they still depend on `VoteModule.withdraw()` succeeding. ## Additional Resources * [ConsenSys Diligence Audit](https://diligence.security/audits/2024/08/ramses-v3/) * [Cantina / Spearbit Audit](https://cantina.xyz/portfolio/ramses-exchange) * [Code4rena Audit Report](https://code4rena.com/reports/2024-10-ramses-exchange) * [Ramses V3 Contracts Repository](https://github.com/RamsesExchange/ramses-v3-contracts) # Ramses Overview Source: https://tech.ramses.xyz/concepts/what-is-ramses ## Protocol, Interface, Community It helps to distinguish the different things people call "Ramses": * **Ramses Protocol**: The on-chain contracts for concentrated and discrete liquidity, emissions, fee routing, and governance. * **Ramses Interface**: The web application used to interact with those contracts. ## What is Ramses? Ramses combines two pool models with a shared fee and governance stack: 1. **Concentrated liquidity** with period-based accounting for CL positions 2. **DLMM** with fixed-price bins, per-bin LP shares, and on-chain variable fees 3. **Non-custodial gauge and optional rewarder systems** 4. **xRAM governance** through `XRam`, `VoteModule`, and `Voter` 5. **Protocol-fee routing** through pool-specific collectors and `FeeDistributor` 6. **Liquid governance exposure** through `R33` / `hyperRAM` ## Protocol Architecture ### Concentrated-liquidity core * **RamsesV3Factory**: Creates and configures CL pools * **RamsesV3Pool**: Handles swaps, liquidity, oracle state, and protocol fee accrual * **RamsesV3PositionManager**: Manages NFT positions and reward-claim integrations ### DLMM core * **DLMMFactory**: Creates pools and manages bin-step presets, fees, quote assets, and hooks * **DLMMPool / DLMMToken**: Handles swaps, bin reserves, oracle state, and per-bin LP shares * **DLMMRouter / DLMMQuoter**: User transactions and route discovery * **DLMMFeeCollector**: Pulls the configured protocol share from DLMM pools * **DLMMRewarder**: Optional RAM emission hook for eligible bins ### Emissions and fee routing * **GaugeV3**: Reward distribution for active CL markets * **ClGaugeFactory**: Gauge deployment and implementation management * **FeeCollector**: Pulls protocol fees from CL pools and routes them onward * **FeeDistributor**: Stores per-period voter rewards for a single market At the [Robinhood snapshot at block 22,674,244](/contracts/reference/dlmm/deployments), DLMM is fee-only, its factory is not connected to `Voter`, and its optional rewarder path is not live. ### Governance and token stack * **XRam**: Transfer-restricted governance token created from RAM * **VoteModule**: Staked xRAM balances, delegation, admin permissions, cooldowns * **Voter**: Vote accounting, gauge registry, emissions routing, reward claims * **Minter**: Weekly emission controller with capped total supply * **AccessHub**: Role, multisig, and timelock control plane * **R33 / hyperRAM**: ERC4626 liquid governance wrapper ## Weekly Period Model The contracts use: ```solidity theme={null} period = block.timestamp / 1 weeks ``` That weekly clock drives: * When votes become active * When fee and incentive rewards are queued * When emissions roll forward * When cooldown and unlock windows apply See [Token Contracts & Emissions](/concepts/tokenomics) for the contract-level flow. See [DLMM & Liquidity Bins](/concepts/protocol/dlmm) for the discrete-liquidity model. # Integrating DLMM Source: https://tech.ramses.xyz/contracts/guides/dlmm/integration Discover, quote, swap, add, and remove Ramses DLMM liquidity safely. # DLMM Integration Guide This guide covers the contract-level flow for Ramses DLMM pools. Start with [DLMM & Liquidity Bins](/concepts/protocol/dlmm) if bins, active IDs, or per-bin LP shares are unfamiliar. The addresses in this guide refer to the [Robinhood snapshot at block 22,674,244](/contracts/reference/dlmm/deployments). At that block, its factory was not connected to `Voter` and it had no live DLMM rewarder system. Re-read live state before sending transactions. ## 1. Discover a pool A token pair may have multiple pools with different bin steps. Query the factory instead of assuming a single address: ```solidity theme={null} IDLMMFactory.LBPairInformation[] memory candidates = factory.getAllLBPairs(tokenIn, tokenOut); for (uint256 i; i < candidates.length; ++i) { if (candidates[i].ignoredForRouting) continue; IDLMMPool pool = candidates[i].LBPair; uint16 binStep = candidates[i].binStep; // Quote this candidate and select the best complete fill. } ``` `ignoredForRouting` tells the official quoter to skip a pool. It does not delete the pool or prevent direct interaction. For a known bin step, use: ```solidity theme={null} IDLMMFactory.LBPairInformation memory info = factory.getLBPairInformation(tokenX, tokenY, binStep); ``` Then verify: ```solidity theme={null} require(factory.isPool(address(info.LBPair)), "unregistered pool"); IERC20 tokenX = info.LBPair.getTokenX(); IERC20 tokenY = info.LBPair.getTokenY(); uint24 activeId = info.LBPair.getActiveId(); ``` The factory sorts tokens internally for lookup, but the pool's `tokenX` and `tokenY` order controls swap direction, price, and valid liquidity composition. ## 2. Quote a swap For a single pool: ```solidity theme={null} bool swapForY = address(pool.getTokenY()) == address(tokenOut); require(amountIn <= type(uint128).max, "amount exceeds pool quote range"); uint128 amountIn128 = uint128(amountIn); (uint128 amountInLeft, uint128 amountOut, uint128 fee) = pool.getSwapOut(amountIn128, swapForY); require(amountInLeft == 0, "insufficient DLMM liquidity"); ``` `swapForY = true` means token X is sold for token Y. A non-zero `amountInLeft` means the pool cannot completely fill the input. For route discovery, `DLMMQuoter.findBestPathFromAmountIn()` and `findBestPathFromAmountOut()` compare all registered, non-ignored bin steps for each hop. The returned quote contains: * The selected pool and bin step for every hop * `Version.V2_1` for each DLMM hop * Per-hop amounts and a fee fraction scaled by `1e18` (`1e18` means 100%) * A virtual no-slippage amount for price-impact calculation The quoter can leave a hop's pair, bin step, or amount fields at zero when it finds no complete candidate. Reject any result containing those zero fields. Quotes are state-dependent. Re-quote near submission and apply explicit slippage protection. ## 3. Execute through the router Build a router path: ```solidity theme={null} IDLMMRouter.Path memory path = IDLMMRouter.Path({ pairBinSteps: binSteps, versions: versions, tokenPath: tokenPath }); ``` The enum retains `V1` and `V2` placeholders for path compatibility, but the current Ramses DLMM router executes `Version.V2_1`. For an exact-input ERC20 swap: ```solidity theme={null} tokenIn.approve(address(router), amountIn); uint256 amountOut = router.swapExactTokensForTokens( amountIn, amountOutMin, path, recipient, deadline ); ``` Native-asset, exact-output, and fee-on-transfer swap variants are also exposed. Do not call the core pool directly unless your integration deliberately handles pre-transfers, complete-fill checks, and its own slippage protection. ## 4. Create a pool Regular callers create a pool directly through: ```solidity theme={null} factory.createLBPair(tokenX, tokenY, activeId, binStep); ``` Creation succeeds only when: * The selected bin-step preset exists and is open * `tokenY` is already a whitelisted quote asset * Both token addresses are non-zero and the tokens are distinct * The token pair and bin step do not already exist * `activeId` produces a valid price Protocol operators use the dedicated `AccessHub.createDLMMPool()` route. That route can add the quote asset before creating the pool. Ordinary users should not wrap factory creation in `AccessHub.execute()`. Choose `activeId` from the intended starting price using the factory-compatible price helper. Reversing token order also reverses the price orientation. ## 5. Add liquidity The router accepts: ```solidity theme={null} struct LiquidityParameters { IERC20 tokenX; IERC20 tokenY; uint256 binStep; uint256 amountX; uint256 amountY; uint256 amountXMin; uint256 amountYMin; uint256 activeIdDesired; uint256 idSlippage; int256[] deltaIds; uint256[] distributionX; uint256[] distributionY; address to; address refundTo; uint256 deadline; } ``` At execution, the router reads the pool's current active ID, checks it against `activeIdDesired` and `idSlippage`, and calculates each destination bin as: ```text theme={null} destinationBin = liveActiveId + deltaIds[i] ``` When building the transaction, set `activeIdDesired` to the active ID you just quoted and use `deltaIds[i] = desiredBinAtQuote - activeIdDesired`. Negative offsets are below the active bin; positive offsets are above it. If the active ID moves but remains inside `idSlippage`, the router accepts the transaction and shifts every destination bin by the same amount. Use `idSlippage = 0` if the position must land on exact absolute bin IDs. The distribution values are `1e18`-scaled weights. To allocate all of a supplied token: ```text theme={null} sum(distributionX) = 1e18 sum(distributionY) = 1e18 ``` An array may sum below `1e18`; the unallocated amount is returned to `refundTo`. Over-allocation can revert and should be rejected before submission. Use an all-zero array when supplying none of that token. Respect pool composition: * Token Y can be assigned at or below the active bin * Token X can be assigned at or above the active bin * A two-sided range needs both tokens Approve ERC20 inputs to the router, then call `addLiquidity()` or `addLiquidityNATIVE()`. The router requires `to == msg.sender`, so the caller must receive the LP shares. Set `refundTo` explicitly: unused amounts go to that address, not automatically to `to`. Adding an asset ratio to the active bin that differs from its existing composition performs an implicit composition swap and charges a fee. Amount minimums should account for this. Large bin arrays can exceed practical gas limits. Estimate each transaction and split wide distributions into bounded chunks while preserving the intended aggregate weights. ## 6. Remove liquidity First authorize the router to burn the caller's per-bin shares: ```solidity theme={null} pool.approveForAll(address(router), true); ``` Then submit matching bin IDs and share amounts: ```solidity theme={null} (uint256 amountX, uint256 amountY) = router.removeLiquidity( tokenX, tokenY, binStep, amountXMin, amountYMin, ids, amountsToBurn, recipient, deadline ); ``` Each burn is pro rata to that bin's reserves and total share supply. Use the native variant only when one side is the router's configured wrapped-native token. ## 7. Index positions and activity DLMM positions are variable-length collections of per-bin balances. A practical index should keep: * One aggregate owner/pool position * One owner/pool/bin balance row * One pool/bin row with reserves and total supply * Swap, deposit, withdrawal, and transfer activity Primary events: | Event | Use | | ------------------------ | --------------------------------------------------- | | `LBPairCreated` | Register a pool | | `Swap` | Update price, active ID, reserves, fees, and volume | | `DepositedToBins` | Record liquidity additions | | `WithdrawnFromBins` | Record liquidity removals | | `TransferBatch` | Track bin-share ownership | | `CompositionFees` | Track active-bin composition fees | | `CollectedProtocolFees` | Track fees removed from pool accounting | | `StaticFeeParametersSet` | Refresh mutable fee configuration | | `HooksParametersSet` | Refresh hook and rewarder state | Do not treat a frontend's bounded active-bin window as a complete ownership index. Positions can remain in bins far from the current price. ## Final checks Before submitting a transaction: 1. Confirm chain ID and deployed addresses. 2. Confirm pool registration and token order. 3. Read the current active ID, fees, and hook parameters. 4. Require a complete quote. 5. Set minimum amounts, ID slippage, `to` equal to the caller, refund recipient, and deadline. 6. Simulate and estimate gas. 7. Re-read state after confirmation. ## Additional resources * [DLMM Contract Architecture](/contracts/reference/dlmm/overview) * [Robinhood DLMM Deployments](/contracts/reference/dlmm/deployments) * [Fees](/concepts/protocol/fees) # Calling Flash Source: https://tech.ramses.xyz/contracts/guides/flash-integrations/calling-flash ## Parameter Structs `FlashParams` contains the token addresses, amounts to borrow, and three fee tiers (source pool + two arb pools): ```solidity theme={null} struct FlashParams { address token0; address token1; uint24 fee1; uint256 amount0; uint256 amount1; uint24 fee2; uint24 fee3; } ``` `FlashCallbackData` is passed through to the callback. `poolKey` (from the `PoolAddress` library) identifies the source pool: ```solidity theme={null} struct FlashCallbackData { uint256 amount0; uint256 amount1; address payer; PoolAddress.PoolKey poolKey; uint24 poolFee2; uint24 poolFee3; } ``` ## Calling Flash Compute the pool address from the pool key, then call `flash` with the callback data abi-encoded: ```solidity theme={null} function initFlash(FlashParams memory params) external { PoolAddress.PoolKey memory poolKey = PoolAddress.PoolKey({token0: params.token0, token1: params.token1, fee: params.fee1}); IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey)); pool.flash( address(this), params.amount0, params.amount1, abi.encode( FlashCallbackData({ amount0: params.amount0, amount1: params.amount1, payer: msg.sender, poolKey: poolKey, poolFee2: params.fee2, poolFee3: params.fee3 }) ) ); } ``` # The Final Contract Source: https://tech.ramses.xyz/contracts/guides/flash-integrations/final-contract ## The Full Contract ```solidity theme={null} // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3FlashCallback.sol'; import '@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol'; import '@uniswap/v3-periphery/contracts/base/PeripheryPayments.sol'; import '@uniswap/v3-periphery/contracts/base/PeripheryImmutableState.sol'; import '@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol'; import '@uniswap/v3-periphery/contracts/libraries/CallbackValidation.sol'; import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol'; import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol'; /// @title Flash contract implementation /// @notice An example contract using the Ramses V3 flash function contract PairFlash is IUniswapV3FlashCallback, PeripheryImmutableState, PeripheryPayments { using LowGasSafeMath for uint256; using LowGasSafeMath for int256; ISwapRouter public immutable swapRouter; constructor( ISwapRouter _swapRouter, address _factory, address _WETH9 ) PeripheryImmutableState(_factory, _WETH9) { swapRouter = _swapRouter; } /// @param fee0 The fee from calling flash for token0 /// @param fee1 The fee from calling flash for token1 /// @param data The data needed in the callback passed as FlashCallbackData from `initFlash` /// @notice implements the callback called from flash /// @dev fails if the flash is not profitable, meaning the amountOut from the flash is less than the amount borrowed function uniswapV3FlashCallback( uint256 fee0, uint256 fee1, bytes calldata data ) external override { FlashCallbackData memory decoded = abi.decode(data, (FlashCallbackData)); CallbackValidation.verifyCallback(factory, decoded.poolKey); address token0 = decoded.poolKey.token0; address token1 = decoded.poolKey.token1; TransferHelper.safeApprove(token0, address(swapRouter), decoded.amount0); TransferHelper.safeApprove(token1, address(swapRouter), decoded.amount1); // profitable check // exactInputSingle will fail if this amount not met uint256 amount1Min = LowGasSafeMath.add(decoded.amount1, fee1); uint256 amount0Min = LowGasSafeMath.add(decoded.amount0, fee0); // call exactInputSingle for swapping token1 for token0 in pool w/fee2 uint256 amountOut0 = swapRouter.exactInputSingle( ISwapRouter.ExactInputSingleParams({ tokenIn: token1, tokenOut: token0, fee: decoded.poolFee2, recipient: address(this), deadline: block.timestamp, amountIn: decoded.amount1, amountOutMinimum: amount0Min, sqrtPriceLimitX96: 0 }) ); // call exactInputSingle for swapping token0 for token 1 in pool w/fee3 uint256 amountOut1 = swapRouter.exactInputSingle( ISwapRouter.ExactInputSingleParams({ tokenIn: token0, tokenOut: token1, fee: decoded.poolFee3, recipient: address(this), deadline: block.timestamp, amountIn: decoded.amount0, amountOutMinimum: amount1Min, sqrtPriceLimitX96: 0 }) ); // end up with amountOut0 of token0 from first swap and amountOut1 of token1 from second swap uint256 amount0Owed = LowGasSafeMath.add(decoded.amount0, fee0); uint256 amount1Owed = LowGasSafeMath.add(decoded.amount1, fee1); TransferHelper.safeApprove(token0, address(this), amount0Owed); TransferHelper.safeApprove(token1, address(this), amount1Owed); if (amount0Owed > 0) pay(token0, address(this), msg.sender, amount0Owed); if (amount1Owed > 0) pay(token1, address(this), msg.sender, amount1Owed); // if profitable pay profits to payer if (amountOut0 > amount0Owed) { uint256 profit0 = LowGasSafeMath.sub(amountOut0, amount0Owed); TransferHelper.safeApprove(token0, address(this), profit0); pay(token0, address(this), decoded.payer, profit0); } if (amountOut1 > amount1Owed) { uint256 profit1 = LowGasSafeMath.sub(amountOut1, amount1Owed); TransferHelper.safeApprove(token0, address(this), profit1); pay(token1, address(this), decoded.payer, profit1); } } //fee1 is the fee of the pool from the initial borrow //fee2 is the fee of the first pool to arb from //fee3 is the fee of the second pool to arb from struct FlashParams { address token0; address token1; uint24 fee1; uint256 amount0; uint256 amount1; uint24 fee2; uint24 fee3; } // fee2 and fee3 are the two other fees associated with the two other pools of token0 and token1 struct FlashCallbackData { uint256 amount0; uint256 amount1; address payer; PoolAddress.PoolKey poolKey; uint24 poolFee2; uint24 poolFee3; } /// @param params The parameters necessary for flash and the callback, passed in as FlashParams /// @notice Calls the pools flash function with data needed in `uniswapV3FlashCallback` function initFlash(FlashParams memory params) external { PoolAddress.PoolKey memory poolKey = PoolAddress.PoolKey({token0: params.token0, token1: params.token1, fee: params.fee1}); IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey)); pool.flash( address(this), params.amount0, params.amount1, abi.encode( FlashCallbackData({ amount0: params.amount0, amount1: params.amount1, payer: msg.sender, poolKey: poolKey, poolFee2: params.fee2, poolFee3: params.fee3 }) ) ); } } ``` # The Flash Callback Source: https://tech.ramses.xyz/contracts/guides/flash-integrations/flash-callback ## Setting Up The Callback Override `uniswapV3FlashCallback` with the arbitrage logic. ```solidity theme={null} function uniswapV3FlashCallback( uint256 fee0, uint256 fee1, bytes calldata data ) external override { ``` Decode the data and validate the callback origin: ```solidity theme={null} FlashCallbackData memory decoded = abi.decode(data, (FlashCallbackData)); CallbackValidation.verifyCallback(factory, decoded.poolKey); ``` Approve the router and set minimum output amounts (borrowed + fees) so swaps revert if unprofitable: ```solidity theme={null} address token0 = decoded.poolKey.token0; address token1 = decoded.poolKey.token1; TransferHelper.safeApprove(token0, address(swapRouter), decoded.amount0); TransferHelper.safeApprove(token1, address(swapRouter), decoded.amount1); uint256 amount1Min = LowGasSafeMath.add(decoded.amount1, fee1); uint256 amount0Min = LowGasSafeMath.add(decoded.amount0, fee0); ``` ## Executing The Swaps Swap the flash-borrowed tokens in pools with different fee tiers: ```solidity theme={null} uint256 amountOut0 = swapRouter.exactInputSingle( ISwapRouter.ExactInputSingleParams({ tokenIn: token1, tokenOut: token0, fee: decoded.poolFee2, recipient: address(this), deadline: block.timestamp + 200, amountIn: decoded.amount1, amountOutMinimum: amount0Min, sqrtPriceLimitX96: 0 }) ); uint256 amountOut1 = swapRouter.exactInputSingle( ISwapRouter.ExactInputSingleParams({ tokenIn: token0, tokenOut: token1, fee: decoded.poolFee3, recipient: address(this), deadline: block.timestamp + 200, amountIn: decoded.amount0, amountOutMinimum: amount1Min, sqrtPriceLimitX96: 0 }) ); ``` ## Paying Back The Pool And Collecting Profits ```solidity theme={null} uint256 amount0Owed = LowGasSafeMath.add(decoded.amount0, fee0); uint256 amount1Owed = LowGasSafeMath.add(decoded.amount1, fee1); TransferHelper.safeApprove(token0, address(this), amount0Owed); TransferHelper.safeApprove(token1, address(this), amount1Owed); if (amount0Owed > 0) pay(token0, address(this), msg.sender, amount0Owed); if (amount1Owed > 0) pay(token1, address(this), msg.sender, amount1Owed); if (amountOut0 > amount0Owed) { uint256 profit0 = LowGasSafeMath.sub(amountOut0, amount0Owed); TransferHelper.safeApprove(token0, address(this), profit0); pay(token0, address(this), decoded.payer, profit0); } if (amountOut1 > amount1Owed) { uint256 profit1 = LowGasSafeMath.sub(amountOut1, amount1Owed); TransferHelper.safeApprove(token0, address(this), profit1); pay(token1, address(this), decoded.payer, profit1); } ``` # Getting Started Source: https://tech.ramses.xyz/contracts/guides/flash-integrations/inheritance-constructors Ramses V3 uses interfaces compatible with Uniswap V3, so you can use the `@uniswap/v3-periphery` and `@uniswap/v3-core` npm packages for interface definitions. The callback function names (`uniswapV3FlashCallback`, etc.) remain the same for compatibility. This guide builds a contract that calls `flash` on a Ramses V3 pool and arbitrages the price difference between pools with different fee tiers for the same token pair. ## Flash Transactions Overview `flash` withdraws specified amounts of both `token0` and `token1` to a `recipient`. The withdrawn amount plus fees must be repaid by the end of the transaction. A `data` parameter allows passing arbitrary abi-encoded data to the callback. ```solidity theme={null} function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external override lock noDelegateCall { ``` ## The Flash Callback Inside `flash`, the pool calls back into `msg.sender`: ```solidity theme={null} IUniswapV3FlashCallback(msg.sender).uniswapV3FlashCallback(fee0, fee1, data); ``` This is where you implement your custom logic. Three callbacks exist: `uniswapV3SwapCallback`, `uniswapV3MintCallback`, and `uniswapV3FlashCallback`. ## Contract Setup Inherit `IUniswapV3FlashCallback` and `PeripheryPayments`. `PeripheryPayments` extends other contracts we need, including [LowGasSafeMath](../../reference/core/libraries/LowGasSafeMath). ```solidity theme={null} pragma solidity =0.7.6; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3FlashCallback.sol'; import '@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol'; import '@uniswap/v3-periphery/contracts/base/PeripheryPayments.sol'; import '@uniswap/v3-periphery/contracts/base/PeripheryImmutableState.sol'; import '@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol'; import '@uniswap/v3-periphery/contracts/libraries/CallbackValidation.sol'; import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol'; import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol'; contract PairFlash is IUniswapV3FlashCallback, PeripheryPayments { using LowGasSafeMath for uint256; using LowGasSafeMath for int256; ISwapRouter public immutable swapRouter; constructor( ISwapRouter _swapRouter, address _factory, address _WETH9 ) PeripheryImmutableState(_factory, _WETH9) { swapRouter = _swapRouter; } } ``` # Set Up Your Local Environment Source: https://tech.ramses.xyz/contracts/guides/local-environment # Quick Start ```bash theme={null} mkdir ramses-integration-example cd ramses-integration-example npm init -y npm add --save-dev hardhat @uniswap/v3-periphery @uniswap/v3-core npx hardhat init ``` Then hop to the `Local Node with a Mainnet Fork` section to complete your setup. # Start from Scratch ## Set Up Dependencies ```bash theme={null} $ npm init ``` ```bash theme={null} $ npm add --save-dev hardhat ``` Initialize Hardhat and follow the prompts (use a templated JS or TS project): ```bash theme={null} $ npx hardhat init ``` Install the V3 contract interfaces: ```bash theme={null} $ npm add @uniswap/v3-periphery @uniswap/v3-core ``` Ramses V3 uses interfaces compatible with Uniswap V3, so you can use the `@uniswap/v3-periphery` and `@uniswap/v3-core` npm packages for interface definitions. The actual contract addresses will differ based on the chain you're deploying to. Set the Solidity compiler version in `./hardhat.config.js`: ```jsx theme={null} // ... module.exports = { solidity: "0.7.6", }; ``` Verify your setup: ```bash theme={null} $ npx hardhat compile ``` # Local Node with a Mainnet Fork See [the SDK getting started guide](../../../sdk/v3/guides/local-development) for a full example on how to use forks. Run tests against your local fork: ```bash theme={null} $ npx hardhat test --network localhost ``` # Collecting Fees Source: https://tech.ramses.xyz/contracts/guides/providing-liquidity/collect-fees ## Collect Fees The contract must hold the position NFT to collect fees. See [Setting Up Your Contract](./setting-up-your-contract) for the base contract. ```solidity theme={null} /// @notice Collects the fees associated with provided liquidity /// @dev The contract must hold the erc721 token before it can collect fees /// @param tokenId The id of the erc721 token /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collectAllFees(uint256 tokenId) external returns (uint256 amount0, uint256 amount1) { // Caller must own the ERC721 position // Call to safeTransfer will trigger `onERC721Received` which must return the selector else transfer will fail nonfungiblePositionManager.safeTransferFrom(msg.sender, address(this), tokenId); // set amount0Max and amount1Max to uint256.max to collect all fees // alternatively can set recipient to msg.sender and avoid another transaction in `sendToOwner` IRamsesV3PositionManager.CollectParams memory params = IRamsesV3PositionManager.CollectParams({ tokenId: tokenId, recipient: address(this), amount0Max: type(uint128).max, amount1Max: type(uint128).max }); (amount0, amount1) = nonfungiblePositionManager.collect(params); // send collected feed back to owner _sendToOwner(tokenId, amount0, amount1); } ``` ## `_sendToOwner` Helper ```solidity theme={null} /// @notice Transfers funds to owner of NFT /// @param tokenId The id of the erc721 /// @param amount0 The amount of token0 /// @param amount1 The amount of token1 function _sendToOwner( uint256 tokenId, uint256 amount0, uint256 amount1 ) internal { address owner = deposits[tokenId].owner; address token0 = deposits[tokenId].token0; address token1 = deposits[tokenId].token1; TransferHelper.safeTransfer(token0, owner, amount0); TransferHelper.safeTransfer(token1, owner, amount1); } ``` # Decrease Liquidity Source: https://tech.ramses.xyz/contracts/guides/providing-liquidity/decrease-liquidity See [Setting Up Your Contract](./setting-up-your-contract) for the base contract. This example assumes the contract already has custody of the NFT. * In production, `amount0Min` and `amount1Min` should be set for slippage protection. ## Decrease Liquidity ```solidity theme={null} /// @notice A function that decreases the current liquidity by half. An example to show how to call the `decreaseLiquidity` function defined in periphery. /// @param tokenId The id of the erc721 token /// @return amount0 The amount received back in token0 /// @return amount1 The amount returned back in token1 function decreaseLiquidityInHalf(uint256 tokenId) external returns (uint256 amount0, uint256 amount1) { // caller must be the owner of the NFT require(msg.sender == deposits[tokenId].owner, 'Not the owner'); // get liquidity data for tokenId uint128 liquidity = deposits[tokenId].liquidity; uint128 halfLiquidity = liquidity / 2; IRamsesV3PositionManager.DecreaseLiquidityParams memory params = IRamsesV3PositionManager.DecreaseLiquidityParams({ tokenId: tokenId, liquidity: halfLiquidity, amount0Min: 0, amount1Min: 0, deadline: block.timestamp }); nonfungiblePositionManager.decreaseLiquidity(params); (amount0, amount1) = nonfungiblePositionManager.collect( IRamsesV3PositionManager.CollectParams({ tokenId: tokenId, recipient: address(this), amount0Max: type(uint128).max, amount1Max: type(uint128).max }) ); //send liquidity back to owner _sendToOwner(tokenId, amount0, amount1); } ``` # Increase Liquidity Source: https://tech.ramses.xyz/contracts/guides/providing-liquidity/increase-liquidity ## Increase Liquidity Within The Current Range See [Setting Up Your Contract](./setting-up-your-contract) for the base contract. This example assumes the contract already has custody of the NFT. * You cannot change the tick boundaries of a position -- `increaseLiquidity` only adds liquidity to the existing range. * In production, `amount0Min` and `amount1Min` should be set for slippage protection. ```solidity theme={null} /// @notice Increases liquidity in the current range /// @dev Pool must be initialized already to add liquidity /// @param tokenId The id of the erc721 token /// @param amount0 The amount to add of token0 /// @param amount1 The amount to add of token1 function increaseLiquidityCurrentRange( uint256 tokenId, uint256 amountAdd0, uint256 amountAdd1 ) external returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { IRamsesV3PositionManager.IncreaseLiquidityParams memory params = IRamsesV3PositionManager.IncreaseLiquidityParams({ tokenId: tokenId, amount0Desired: amountAdd0, amount1Desired: amountAdd1, amount0Min: 0, amount1Min: 0, deadline: block.timestamp }); (liquidity, amount0, amount1) = nonfungiblePositionManager.increaseLiquidity(params); } ``` # Mint a New Position Source: https://tech.ramses.xyz/contracts/guides/providing-liquidity/mint-a-new-position ## Input Parameters To mint, call `nonfungiblePositionManager.mint` with `MintParams`. ```solidity theme={null} /// @notice Calls the mint function defined in periphery, mints the same amount of each token. For this example we are providing 1000 DAI and 1000 USDC in liquidity /// @return tokenId The id of the newly minted ERC721 /// @return liquidity The amount of liquidity for the position /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function mintNewPosition() external returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ) { uint256 amount0ToMint = 1000; uint256 amount1ToMint = 1000; ``` ## Calling Mint * `TickMath.MIN_TICK` / `TickMath.MAX_TICK` provides liquidity across the whole range. For other fee tiers, snap to the pool's tick spacing: `(TickMath.MIN_TICK / tickSpacing) * tickSpacing`. Get tick spacing via `pool.tickSpacing()`. Tick spacings: `0.01% = 1, 0.05% = 10, 0.3% = 60, 1% = 200`. * `amount0Min` / `amount1Min` are set to zero here. **In production, set slippage protection** to prevent frontrunning. * This will not initialize a pool that does not yet exist. ```solidity theme={null} // Approve the position manager TransferHelper.safeApprove(DAI, address(nonfungiblePositionManager), amount0ToMint); TransferHelper.safeApprove(USDC, address(nonfungiblePositionManager), amount1ToMint); IRamsesV3PositionManager.MintParams memory params = IRamsesV3PositionManager.MintParams({ token0: DAI, token1: USDC, fee: poolFee, tickLower: TickMath.MIN_TICK, tickUpper: TickMath.MAX_TICK, amount0Desired: amount0ToMint, amount1Desired: amount1ToMint, amount0Min: 0, amount1Min: 0, recipient: address(this), deadline: block.timestamp }); // Note that the pool defined by DAI/USDC and fee tier 0.3% must already be created and initialized in order to mint (tokenId, liquidity, amount0, amount1) = nonfungiblePositionManager.mint(params); ``` ## Updating The Deposit Mapping And Refunding ```solidity theme={null} // Create a deposit _createDeposit(msg.sender, tokenId); // Remove allowance and refund in both assets. if (amount0 < amount0ToMint) { TransferHelper.safeApprove(DAI, address(nonfungiblePositionManager), 0); uint256 refund0 = amount0ToMint - amount0; TransferHelper.safeTransfer(DAI, msg.sender, refund0); } if (amount1 < amount1ToMint) { TransferHelper.safeApprove(USDC, address(nonfungiblePositionManager), 0); uint256 refund1 = amount1ToMint - amount1; TransferHelper.safeTransfer(USDC, msg.sender, refund1); } } ``` # Set Up Your Contract Source: https://tech.ramses.xyz/contracts/guides/providing-liquidity/setting-up-your-contract ## Setting up the Contract This guide builds a custodial contract for Ramses V3 positions -- minting, adding/removing liquidity, and collecting fees. Ramses V3 uses interfaces compatible with Uniswap V3, so you can use the `@uniswap/v3-periphery` and `@uniswap/v3-core` npm packages for interface definitions. ```solidity theme={null} // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import '@uniswap/v3-core/contracts/libraries/TickMath.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol'; import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol'; import '@uniswap/v3-periphery/contracts/interfaces/IRamsesV3PositionManager.sol'; import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol'; import '@uniswap/v3-periphery/contracts/base/LiquidityManagement.sol'; ``` ```solidity theme={null} contract LiquidityExamples is IERC721Receiver { address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; uint24 public constant poolFee = 3000; IRamsesV3PositionManager public immutable nonfungiblePositionManager; struct Deposit { address owner; uint128 liquidity; address token0; address token1; } mapping(uint256 => Deposit) public deposits; constructor( IRamsesV3PositionManager _nonfungiblePositionManager, address _factory, address _WETH9 ) PeripheryImmutableState(_factory, _WETH9) { nonfungiblePositionManager = _nonfungiblePositionManager; } ``` ## Allowing ERC721 Interactions ```solidity theme={null} function onERC721Received( address operator, address, uint256 tokenId, bytes calldata ) external override returns (bytes4) { _createDeposit(operator, tokenId); return this.onERC721Received.selector; } ``` ## Creating a Deposit ```solidity theme={null} function _createDeposit(address owner, uint256 tokenId) internal { (, , address token0, address token1, , , , uint128 liquidity, , , , ) = nonfungiblePositionManager.positions(tokenId); deposits[tokenId] = Deposit({owner: owner, liquidity: liquidity, token0: token0, token1: token1}); } ``` # The Full Contract Source: https://tech.ramses.xyz/contracts/guides/providing-liquidity/the-full-contract Ramses V3 uses interfaces compatible with Uniswap V3, so you can use the `@uniswap/v3-periphery` and `@uniswap/v3-core` npm packages for interface definitions. The actual contract addresses will differ based on the chain you're deploying to. ```solidity theme={null} // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import '@uniswap/v3-core/contracts/libraries/TickMath.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol'; import '../libraries/TransferHelper.sol'; import '../interfaces/IRamsesV3PositionManager.sol'; import '../base/LiquidityManagement.sol'; contract LiquidityExamples is IERC721Receiver { address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; uint24 public constant poolFee = 3000; IRamsesV3PositionManager public immutable nonfungiblePositionManager; /// @notice Represents the deposit of an NFT struct Deposit { address owner; uint128 liquidity; address token0; address token1; } /// @dev deposits[tokenId] => Deposit mapping(uint256 => Deposit) public deposits; constructor( IRamsesV3PositionManager _nonfungiblePositionManager ) { nonfungiblePositionManager = _nonfungiblePositionManager; } // Implementing `onERC721Received` so this contract can receive custody of erc721 tokens function onERC721Received( address operator, address, uint256 tokenId, bytes calldata ) external override returns (bytes4) { _createDeposit(operator, tokenId); return this.onERC721Received.selector; } function _createDeposit(address owner, uint256 tokenId) internal { (, , address token0, address token1, , , , uint128 liquidity, , , , ) = nonfungiblePositionManager.positions(tokenId); deposits[tokenId] = Deposit({owner: owner, liquidity: liquidity, token0: token0, token1: token1}); } /// @notice Calls the mint function defined in periphery, mints the same amount of each token. /// For this example we are providing 1000 DAI and 1000 USDC in liquidity /// @return tokenId The id of the newly minted ERC721 /// @return liquidity The amount of liquidity for the position /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function mintNewPosition() external returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ) { uint256 amount0ToMint = 1000; uint256 amount1ToMint = 1000; // transfer tokens to contract TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amount0ToMint); TransferHelper.safeTransferFrom(USDC, msg.sender, address(this), amount1ToMint); // Approve the position manager TransferHelper.safeApprove(DAI, address(nonfungiblePositionManager), amount0ToMint); TransferHelper.safeApprove(USDC, address(nonfungiblePositionManager), amount1ToMint); IRamsesV3PositionManager.MintParams memory params = IRamsesV3PositionManager.MintParams({ token0: DAI, token1: USDC, fee: poolFee, tickLower: TickMath.MIN_TICK, tickUpper: TickMath.MAX_TICK, amount0Desired: amount0ToMint, amount1Desired: amount1ToMint, amount0Min: 0, amount1Min: 0, recipient: address(this), deadline: block.timestamp }); // Note that the pool defined by DAI/USDC and fee tier 0.3% must already be created and initialized in order to mint (tokenId, liquidity, amount0, amount1) = nonfungiblePositionManager.mint(params); // Create a deposit _createDeposit(msg.sender, tokenId); // Remove allowance and refund in both assets. if (amount0 < amount0ToMint) { TransferHelper.safeApprove(DAI, address(nonfungiblePositionManager), 0); uint256 refund0 = amount0ToMint - amount0; TransferHelper.safeTransfer(DAI, msg.sender, refund0); } if (amount1 < amount1ToMint) { TransferHelper.safeApprove(USDC, address(nonfungiblePositionManager), 0); uint256 refund1 = amount1ToMint - amount1; TransferHelper.safeTransfer(USDC, msg.sender, refund1); } } /// @notice Collects the fees associated with provided liquidity /// @dev The contract must hold the erc721 token before it can collect fees /// @param tokenId The id of the erc721 token /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collectAllFees(uint256 tokenId) external returns (uint256 amount0, uint256 amount1) { IRamsesV3PositionManager.CollectParams memory params = IRamsesV3PositionManager.CollectParams({ tokenId: tokenId, recipient: address(this), amount0Max: type(uint128).max, amount1Max: type(uint128).max }); (amount0, amount1) = nonfungiblePositionManager.collect(params); // send collected feed back to owner _sendToOwner(tokenId, amount0, amount1); } /// @notice A function that decreases the current liquidity by half. An example to show how to call the `decreaseLiquidity` function defined in periphery. /// @param tokenId The id of the erc721 token /// @return amount0 The amount received back in token0 /// @return amount1 The amount returned back in token1 function decreaseLiquidityInHalf(uint256 tokenId) external returns (uint256 amount0, uint256 amount1) { // caller must be the owner of the NFT require(msg.sender == deposits[tokenId].owner, 'Not the owner'); // get liquidity data for tokenId uint128 liquidity = deposits[tokenId].liquidity; uint128 halfLiquidity = liquidity / 2; IRamsesV3PositionManager.DecreaseLiquidityParams memory params = IRamsesV3PositionManager.DecreaseLiquidityParams({ tokenId: tokenId, liquidity: halfLiquidity, amount0Min: 0, amount1Min: 0, deadline: block.timestamp }); (amount0, amount1) = nonfungiblePositionManager.decreaseLiquidity(params); //send liquidity back to owner _sendToOwner(tokenId, amount0, amount1); } /// @notice Increases liquidity in the current range /// @dev Pool must be initialized already to add liquidity /// @param tokenId The id of the erc721 token /// @param amount0 The amount to add of token0 /// @param amount1 The amount to add of token1 function increaseLiquidityCurrentRange( uint256 tokenId, uint256 amountAdd0, uint256 amountAdd1 ) external returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { TransferHelper.safeTransferFrom(deposits[tokenId].token0, msg.sender, address(this), amountAdd0); TransferHelper.safeTransferFrom(deposits[tokenId].token1, msg.sender, address(this), amountAdd1); TransferHelper.safeApprove(deposits[tokenId].token0, address(nonfungiblePositionManager), amountAdd0); TransferHelper.safeApprove(deposits[tokenId].token1, address(nonfungiblePositionManager), amountAdd1); IRamsesV3PositionManager.IncreaseLiquidityParams memory params = IRamsesV3PositionManager.IncreaseLiquidityParams({ tokenId: tokenId, amount0Desired: amountAdd0, amount1Desired: amountAdd1, amount0Min: 0, amount1Min: 0, deadline: block.timestamp }); (liquidity, amount0, amount1) = nonfungiblePositionManager.increaseLiquidity(params); } /// @notice Transfers funds to owner of NFT /// @param tokenId The id of the erc721 /// @param amount0 The amount of token0 /// @param amount1 The amount of token1 function _sendToOwner( uint256 tokenId, uint256 amount0, uint256 amount1 ) internal { address owner = deposits[tokenId].owner; address token0 = deposits[tokenId].token0; address token1 = deposits[tokenId].token1; TransferHelper.safeTransfer(token0, owner, amount0); TransferHelper.safeTransfer(token1, owner, amount1); } /// @notice Transfers the NFT to the owner /// @param tokenId The id of the erc721 function retrieveNFT(uint256 tokenId) external { require(msg.sender == deposits[tokenId].owner, 'Not the owner'); nonfungiblePositionManager.safeTransferFrom(address(this), msg.sender, tokenId); delete deposits[tokenId]; } } ``` # Multihop Swaps Source: https://tech.ramses.xyz/contracts/guides/swaps/multihop-swaps ## Introduction Multi-hop swaps route through intermediate pools. The contract setup is identical to [single swaps](./single-swaps) -- refer to that guide for the base contract, imports, and constructor. ## Exact Input Multi Hop Swaps ### Input Parameters * `path`: A sequence of `(tokenAddress, fee, tokenAddress)` encoded via `abi.encodePacked`. The router resolves each pool from these values. * `amountOutMinimum`: minimum output amount -- use an oracle or the SDK in production. ### Calling the function ```solidity theme={null} /// @notice swapExactInputMultihop swaps a fixed amount of DAI for a maximum possible amount of WETH9 through an intermediary pool. /// For this example, we will swap DAI to USDC, then USDC to WETH9 to achieve our desired output. /// @dev The calling address must approve this contract to spend at least `amountIn` worth of its DAI for this function to succeed. /// @param amountIn The amount of DAI to be swapped. /// @return amountOut The amount of WETH9 received after the swap. function swapExactInputMultihop(uint256 amountIn) external returns (uint256 amountOut) { // Transfer `amountIn` of DAI to this contract. TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountIn); // Approve the router to spend DAI. TransferHelper.safeApprove(DAI, address(swapRouter), amountIn); // Multiple pool swaps are encoded through bytes called a `path`. A path is a sequence of token addresses and poolFees that define the pools used in the swaps. // The format for pool encoding is (tokenIn, fee, tokenOut/tokenIn, fee, tokenOut) where tokenOut/tokenIn parameter is the shared token across the pools. // Since we are swapping DAI to USDC and then USDC to WETH9 the path encoding is (DAI, 0.3%, USDC, 0.3%, WETH9). ISwapRouter.ExactInputParams memory params = ISwapRouter.ExactInputParams({ path: abi.encodePacked(DAI, poolFee, USDC, poolFee, WETH9), recipient: msg.sender, deadline: block.timestamp, amountIn: amountIn, amountOutMinimum: 0 }); // Executes the swap. amountOut = swapRouter.exactInput(params); } ``` ## Exact Output Multihop Swap For exact output, the `path` is **encoded in reverse order** because the swap executes backwards to determine the required input. ### Input Parameters * `path`: `(tokenOut, fee, intermediary, fee, tokenIn)` -- note the reversed order. * `amountOut`: the desired output amount. * `amountInMaximum`: maximum input willing to spend. ### Calling the function ```solidity theme={null} /// @notice swapExactOutputMultihop swaps a minimum possible amount of DAI for a fixed amount of WETH through an intermediary pool. /// For this example, we want to swap DAI for WETH9 through a USDC pool but we specify the desired amountOut of WETH9. Notice how the path encoding is slightly different in for exact output swaps. /// @dev The calling address must approve this contract to spend its DAI for this function to succeed. As the amount of input DAI is variable, /// the calling address will need to approve for a slightly higher amount, anticipating some variance. /// @param amountOut The desired amount of WETH9. /// @param amountInMaximum The maximum amount of DAI willing to be swapped for the specified amountOut of WETH9. /// @return amountIn The amountIn of DAI actually spent to receive the desired amountOut. function swapExactOutputMultihop(uint256 amountOut, uint256 amountInMaximum) external returns (uint256 amountIn) { // Transfer the specified `amountInMaximum` to this contract. TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountInMaximum); // Approve the router to spend `amountInMaximum`. TransferHelper.safeApprove(DAI, address(swapRouter), amountInMaximum); // The parameter path is encoded as (tokenOut, fee, tokenIn/tokenOut, fee, tokenIn) // The tokenIn/tokenOut field is the shared token between the two pools used in the multiple pool swap. In this case USDC is the "shared" token. // For an exactOutput swap, the first swap that occurs is the swap which returns the eventual desired token. // In this case, our desired output token is WETH9 so that swap happens first, and is encoded in the path accordingly. ISwapRouter.ExactOutputParams memory params = ISwapRouter.ExactOutputParams({ path: abi.encodePacked(WETH9, poolFee, USDC, poolFee, DAI), recipient: msg.sender, deadline: block.timestamp, amountOut: amountOut, amountInMaximum: amountInMaximum }); // Executes the swap, returning the amountIn actually spent. amountIn = swapRouter.exactOutput(params); // If the swap did not require the full amountInMaximum to achieve the exact amountOut then we refund msg.sender and approve the router to spend 0. if (amountIn < amountInMaximum) { TransferHelper.safeApprove(DAI, address(swapRouter), 0); TransferHelper.safeTransfer(DAI, msg.sender, amountInMaximum - amountIn); } } ``` # Single Swaps Source: https://tech.ramses.xyz/contracts/guides/swaps/single-swaps This example shows how to implement single-path swaps using two functions: * `swapExactInputSingle` - swap a fixed input amount for maximum output * `swapExactOutputSingle` - swap minimum input for a fixed output amount Both use the [ISwapRouter](../../reference/periphery/interfaces/ISwapRouter) interface. **Note:** The swap examples are not production ready code, and are implemented in a simplistic manner for the purpose of learning. ## Set Up the Contract ```solidity theme={null} // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; pragma abicoder v2; import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol'; import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol'; ``` ```solidity theme={null} contract SwapExamples { ISwapRouter public immutable swapRouter; address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; uint24 public constant poolFee = 3000; constructor(ISwapRouter _swapRouter) { swapRouter = _swapRouter; } ``` ## Exact Input Swaps The caller must `approve` the contract to withdraw tokens. Since the contract itself holds the tokens after `safeTransferFrom`, it must also approve the router. ```solidity theme={null} /// @notice swapExactInputSingle swaps a fixed amount of DAI for a maximum possible amount of WETH9 /// using the DAI/WETH9 0.3% pool by calling `exactInputSingle` in the swap router. /// @dev The calling address must approve this contract to spend at least `amountIn` worth of its DAI for this function to succeed. /// @param amountIn The exact amount of DAI that will be swapped for WETH9. /// @return amountOut The amount of WETH9 received. function swapExactInputSingle(uint256 amountIn) external returns (uint256 amountOut) { // msg.sender must approve this contract // Transfer the specified amount of DAI to this contract. TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountIn); // Approve the router to spend DAI. TransferHelper.safeApprove(DAI, address(swapRouter), amountIn); ``` ### Swap Input Parameters Parameters for `ExactInputSingleParams` ([reference](../../reference/periphery/interfaces/ISwapRouter)): * `fee` - pool fee tier, used to determine the correct pool contract * `amountOutMinimum` - set to zero here, but **in production use an oracle or the SDK to calculate this**. Without slippage protection you are vulnerable to sandwich attacks. * `sqrtPriceLimitX96` - set to zero (inactive). Can be used to cap the price impact of a swap. **WARNING: A non-zero `sqrtPriceLimitX96` can cause fewer tokens than `amountIn` to be swapped.** Any contract using this must refund unswapped tokens. ### Call the function ```solidity theme={null} // Naively set amountOutMinimum to 0. In production, use an oracle or other data source to choose a safer value for amountOutMinimum. // We also set the sqrtPriceLimitx96 to be 0 to ensure we swap our exact input amount. ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({ tokenIn: DAI, tokenOut: WETH9, fee: poolFee, recipient: msg.sender, deadline: block.timestamp, amountIn: amountIn, amountOutMinimum: 0, sqrtPriceLimitX96: 0 }); // The call to `exactInputSingle` executes the swap. amountOut = swapRouter.exactInputSingle(params); } ``` ## Exact Output Swaps Swaps a minimum possible amount of the input token for a fixed amount of the outbound token. Any leftover input is refunded to the caller. ### Call the function ```solidity theme={null} /// @notice swapExactOutputSingle swaps a minimum possible amount of DAI for a fixed amount of WETH. /// @dev The calling address must approve this contract to spend its DAI for this function to succeed. As the amount of input DAI is variable, /// the calling address will need to approve for a slightly higher amount, anticipating some variance. /// @param amountOut The exact amount of WETH9 to receive from the swap. /// @param amountInMaximum The amount of DAI we are willing to spend to receive the specified amount of WETH9. /// @return amountIn The amount of DAI actually spent in the swap. function swapExactOutputSingle(uint256 amountOut, uint256 amountInMaximum) external returns (uint256 amountIn) { // Transfer the specified amount of DAI to this contract. TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountInMaximum); // Approve the router to spend the specified `amountInMaximum` of DAI. // In production, you should choose the maximum amount to spend based on oracles or other data sources to achieve a better swap. TransferHelper.safeApprove(DAI, address(swapRouter), amountInMaximum); ISwapRouter.ExactOutputSingleParams memory params = ISwapRouter.ExactOutputSingleParams({ tokenIn: DAI, tokenOut: WETH9, fee: poolFee, recipient: msg.sender, deadline: block.timestamp, amountOut: amountOut, amountInMaximum: amountInMaximum, sqrtPriceLimitX96: 0 }); // Executes the swap returning the amountIn needed to spend to receive the desired amountOut. amountIn = swapRouter.exactOutputSingle(params); // For exact output swaps, the amountInMaximum may not have all been spent. // If the actual amount spent (amountIn) is less than the specified maximum amount, we must refund the msg.sender and approve the swapRouter to spend 0. if (amountIn < amountInMaximum) { TransferHelper.safeApprove(DAI, address(swapRouter), 0); TransferHelper.safeTransfer(DAI, msg.sender, amountInMaximum - amountIn); } } ``` # Overview Source: https://tech.ramses.xyz/contracts/overview # The Ramses Smart Contracts Welcome to the Ramses contract documentation. Ramses combines Uniswap V3-style concentrated liquidity with an LFJ v2.2-style DLMM implementation, weekly accounting, gauge-directed emissions, fee routing, and a separate governance stack built around `xRAM`, `VoteModule`, `Voter`, and `AccessHub`. The [Ramses V3 contracts repository](https://github.com/RamsesExchange/ramses-v3-contracts) is the public source reference for the concentrated-liquidity stack. DLMM deployment state and addresses are documented separately because they are not present in that repository. ## What Makes Ramses Different ### Compiler Ramses V3 contracts are compiled with Solidity `^0.8.0` using `via-ir` (the Yul-based intermediate representation pipeline). This is a significant departure from upstream Uniswap V3, which targets Solidity `0.7.6` without `via-ir`. Key implications: * **Custom errors** replace string `revert` messages across most of the protocol (see [Error Codes](./reference/error-codes)) * **Overflow checks** are built into the compiler — explicit `SafeMath` wrappers are no longer needed * **`via-ir` optimization** enables cross-function inlining and stack-depth relief, allowing the contracts to compile with deeper call stacks and more complex internal logic than the legacy pipeline permits ### 1. Period-based accounting for CL rewards Ramses V3 pools track weekly liquidity participation so gauges can reward positions based on time spent in range during each period. This is the main on-chain difference from a plain Uniswap V3 deployment. ### 2. Discrete liquidity bins DLMM pools divide price space into fixed-price bins and represent LP ownership as per-bin fungible shares. The trader fee combines a static floor with a variable component driven by on-chain bin movement. ### 3. Non-custodial CL gauges `GaugeV3` rewards are tied to CL pool positions without moving the underlying pool liquidity into a separate staking contract. The surrounding periphery and voter contracts coordinate eligibility and claims. ### 4. Address-based governance, not veNFT voting Governance in the current contracts is address-based: * `XRam.sol` creates transfer-restricted `xRAM` * `VoteModule.sol` holds staked `xRAM` and exposes voting power * `Voter.sol` records votes by owner address for the next weekly period * `FeeDistributor.sol` pays rewards to those addresses based on periodized vote weight ### 5. Centralized governance routing through AccessHub `AccessHub.sol` is the operational control plane for the protocol. It owns batch fee updates, gauge lifecycle management, xRAM/R33 administration, treasury settings, and other protocol-wide actions through roles, multisig-only functions, and timelock-only functions. ### 6. Liquid governance wrapper `R33.sol` is an ERC4626 vault that wraps xRAM exposure. The source contract is named `R33`, while the token it mints is `hyperRAM` (`xRAM Liquid Staking Token` in the constructor). It stakes the underlying xRAM into `VoteModule`, allows an operator to vote and compound, and exposes a liquid ERC20 share token. ## Contract Layout ### Concentrated liquidity **Core contracts**: * **RamsesV3Factory**: Pool creation, fee configuration, fee collector wiring, and voter integration * **RamsesV3Pool**: Swaps, liquidity management, oracle state, protocol fee accrual, and weekly accounting * **RamsesV3PoolDeployer**: Factory helper used to deploy pool instances **Periphery contracts**: * **RamsesV3PositionManager**: NFT position management and reward-claim integrations * **SwapRouter**: Single-hop and multi-hop swap execution * **Quoter / QuoterV2 / TickLens**: Read-oriented helpers ### Discrete liquidity **Core contracts**: * **DLMMFactory**: Pool creation, bin-step presets, quote assets, fee configuration, protocol share, and hooks * **DLMMPool / DLMMToken**: Bin reserves, swaps, oracle state, protocol fees, and per-bin LP shares **Periphery and routing contracts**: * **DLMMRouter**: Pool creation, swaps, deposits, withdrawals, native assets, and transaction safeguards * **DLMMQuoter**: Best-path search across registered bin steps * **DLMMFeeCollector**: Protocol-fee collection and treasury or voter routing **Optional reward contracts**: * **DLMMRewarder**: RAM emission hook for eligible bins * **DLMMRewarderFactory**: Beacon-proxy deployment and pool/rewarder linkage * [Read the DLMM contract architecture](./reference/dlmm/overview) ### Gauges and fee routing **Gauge contracts**: * **GaugeV3**: CL reward distribution * **ClGaugeFactory**: Gauge deployment and implementation management * **FeeCollector**: Collects protocol fees from CL pools and routes them to treasury and fee distributors * **DLMMRewarder**: Optional DLMM emission target; inactive in the [Robinhood block 22,674,244 snapshot](/contracts/reference/dlmm/deployments) * **DLMMFeeCollector**: Collects the DLMM protocol share **Reward distribution contracts**: * **FeeDistributor**: Tracks vote weight per period and distributes fee/incentive tokens to voter addresses ### Governance and token stack * **AccessHub**: Role-based and multisig/timelock governance router * **Voter**: Vote accounting, gauge registry, emissions routing, reward claims * **VoteModule**: xRAM staking, delegation, admin permissions, cooldown management * **Minter**: Weekly emission controller with a capped supply schedule * **XRam**: Transfer-restricted governance token with conversion and exit penalties * **R33 / hyperRAM**: ERC4626 liquid wrapper over xRAM staked in VoteModule * **AutoVault**: Optional xRAM automation layer for reward conversion and delegated voting ## Weekly Period Model The contracts use: ```solidity theme={null} period = block.timestamp / 1 weeks ``` Key consequences of that model: 1. `Voter.vote()` writes allocations into the **next** period. 2. `FeeDistributor.notifyRewardAmount()` and `incentivize()` also queue rewards into the **next** period. 3. `Minter.updatePeriod()` advances emissions when a new weekly period has started. 4. `Voter.distribute()` ties together emissions distribution and protocol-fee routing for gauges. 5. `VoteModule` cooldowns and `R33` unlock windows are also expressed around this weekly cadence. ## Code Audit Status Ramses V3 has undergone multiple professional security audits: * **ConsenSys Diligence** (August 2024): 10 contracts, 2,250 nSLOC * Focus on period-based accounting system * Critical findings addressed in final implementation * [View Report](https://diligence.security/audits/2024/08/ramses-v3/) * **Cantina / Spearbit**: Independent security review * [View on Cantina](https://cantina.xyz/portfolio/ramses-exchange) * **Code4rena** (October 2024): \$120,000 audit competition * 2 medium severity findings, all resolved * [View Report](https://code4rena.com/reports/2024-10-ramses-exchange) Do not assume these V3 reports cover DLMM merely because DLMM is part of the wider Ramses codebase. Verify the named contracts and commit in each report before treating any finding or assurance as applicable to DLMM. The period-accounting and reward-routing stack requires special attention to: * Tick and position boundary edge cases * Weekly period transitions * Reward accounting across gauges and fee distributors * Fee routing across treasury, fee collectors, and active gauges # Guides If you are new to Ramses, start with the [protocol concepts](../concepts/ramses-protocol). Then set up your [local environment](./guides/local-environment), walk through a [first CL swap](./guides/swaps/single-swaps), or follow the [DLMM integration guide](./guides/dlmm/integration). # Reference For a deeper dive, read the [technical reference](./reference/overview). # Resources * [**Ramses V3 Contracts**](https://github.com/RamsesExchange/ramses-v3-contracts) - Public concentrated-liquidity source * [**ConsenSys Diligence Audit**](https://diligence.security/audits/2024/08/ramses-v3/) * [**Cantina / Spearbit Audit**](https://cantina.xyz/portfolio/ramses-exchange) * [**Code4rena Audit Report**](https://code4rena.com/reports/2024-10-ramses-exchange) * [**Uniswap V3 Core**](https://github.com/Uniswap/v3-core) - Reference implementation for concentrated-liquidity mechanics # RamsesV3Factory Source: https://tech.ramses.xyz/contracts/reference/core/RamsesV3Factory Deploys Ramses V3 pools and manages control over pool protocol fees. Uses the AccessHub pattern for governance instead of simple ownership. ## Functions ### createPool ```solidity theme={null} function createPool( address tokenA, address tokenB, int24 tickSpacing, uint160 sqrtPriceX96 ) external returns (address pool) ``` Creates a pool for the given two tokens and tick spacing, optionally initializing it with a price tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. The fee is automatically derived from the `tickSpacingInitialFee` mapping. The call will revert if the pool already exists, the token arguments are invalid, or no fee has been enabled for the given tick spacing. If `sqrtPriceX96` is non-zero, the pool will be initialized with that price. #### Parameters: | Name | Type | Description | | :------------- | :------ | :-------------------------------------------------------------- | | `tokenA` | address | One of the two tokens in the desired pool | | `tokenB` | address | The other of the two tokens in the desired pool | | `tickSpacing` | int24 | The desired tick spacing for the pool | | `sqrtPriceX96` | uint160 | The initial sqrt price of the pool as a Q64.96 (0 to skip init) | #### Return Values: | Name | Type | Description | | :----- | :------ | :------------------------------------ | | `pool` | address | The address of the newly created pool | ### enableTickSpacing ```solidity theme={null} function enableTickSpacing( int24 tickSpacing, uint24 initialFee ) external ``` Enables a tick spacing with the given default fee Maps tick spacing values to their default fee amounts. This is the inverse of Uniswap V3's `enableFeeAmount`. Only callable by governance (AccessHub). #### Parameters: | Name | Type | Description | | :------------ | :----- | :--------------------------------------------------------------------- | | `tickSpacing` | int24 | The spacing between ticks to enable | | `initialFee` | uint24 | The default fee amount, denominated in hundredths of a bip (i.e. 1e-6) | ### setFeeProtocol ```solidity theme={null} function setFeeProtocol( uint24 _feeProtocol ) external ``` Sets the default protocol fee for all pools. Only callable by governance (AccessHub). #### Parameters: | Name | Type | Description | | :------------- | :----- | :---------------------------------------------------------- | | `_feeProtocol` | uint24 | The new default protocol fee, denominated in 1e-6 precision | ### setPoolFeeProtocol ```solidity theme={null} function setPoolFeeProtocol( address pool, uint24 _feeProtocol ) external ``` Sets the protocol fee for a specific pool. Only callable by governance (AccessHub). Pass `type(uint24).max` to revert the pool to the global default. #### Parameters: | Name | Type | Description | | :------------- | :------ | :--------------------------------------------- | | `pool` | address | The pool address to update | | `_feeProtocol` | uint24 | The new protocol fee for the pool (1e-6 basis) | ### gaugeFeeSplitEnable ```solidity theme={null} function gaugeFeeSplitEnable( address pool ) external ``` Enables gauge fee splitting for a pool. When called by the voter contract, sets the pool's fee protocol to 100% so all fees route through the FeeCollector for distribution to voters. When called by other addresses, simply refreshes the pool's fee protocol from the factory. #### Parameters: | Name | Type | Description | | :----- | :------ | :---------------------------------------- | | `pool` | address | The pool to enable gauge fee splitting on | ### setFeeCollector ```solidity theme={null} function setFeeCollector( address _feeCollector ) external ``` Updates the fee collector address. Only callable by governance (AccessHub). #### Parameters: | Name | Type | Description | | :-------------- | :------ | :---------------------------- | | `_feeCollector` | address | The new fee collector address | ### setVoter ```solidity theme={null} function setVoter( address _voter ) external ``` Updates the voter contract address. Only callable by governance (AccessHub). #### Parameters: | Name | Type | Description | | :------- | :------ | :-------------------- | | `_voter` | address | The new voter address | ### setFee ```solidity theme={null} function setFee( address _pool, uint24 _fee ) external ``` Sets the swap fee for a specific pool. Only callable by governance (AccessHub). #### Parameters: | Name | Type | Description | | :------ | :------ | :--------------------------------------------------------------- | | `_pool` | address | The pool to update | | `_fee` | uint24 | The new swap fee, denominated in hundredths of a bip (i.e. 1e-6) | ## State Variables ### voter ```solidity theme={null} function voter( ) external returns (address) ``` Returns the address of the Voter contract used for gauge integration. ### feeCollector ```solidity theme={null} function feeCollector( ) external view returns (address) ``` Returns the address of the FeeCollector contract that routes protocol fees. ### feeProtocol ```solidity theme={null} function feeProtocol( ) external view returns (uint24) ``` Returns the default protocol fee applied to pools that don't have a pool-specific override. ### tickSpacingInitialFee ```solidity theme={null} function tickSpacingInitialFee( int24 tickSpacing ) external view returns (uint24 initialFee) ``` Returns the default fee for a given tick spacing. Returns 0 if the tick spacing is not enabled. ### poolFeeProtocol ```solidity theme={null} function poolFeeProtocol( address pool ) external view returns (uint24) ``` Returns the effective protocol fee for a specific pool. Falls back to the global `feeProtocol` if no pool-specific override is set. ## Events ### PoolCreated ```solidity theme={null} event PoolCreated( address token0, address token1, uint24 fee, int24 tickSpacing, address pool ) ``` Emitted when a pool is created #### Parameters: | Name | Type | Description | | :------------ | :------ | :-------------------------------------------------------------------------------- | | `token0` | address | The first token of the pool by address sort order | | `token1` | address | The second token of the pool by address sort order | | `fee` | uint24 | The fee collected upon every swap in the pool, denominated in hundredths of a bip | | `tickSpacing` | int24 | The minimum number of ticks between initialized ticks | | `pool` | address | The address of the created pool | ### TickSpacingEnabled ```solidity theme={null} event TickSpacingEnabled( int24 tickSpacing, uint24 fee ) ``` Emitted when a new tick spacing is enabled for pool creation via the factory #### Parameters: | Name | Type | Description | | :------------ | :----- | :----------------------------------------------- | | `tickSpacing` | int24 | The tick spacing that was enabled | | `fee` | uint24 | The default fee associated with the tick spacing | ### SetFeeProtocol ```solidity theme={null} event SetFeeProtocol( uint24 feeProtocolOld, uint24 feeProtocolNew ) ``` Emitted when the default protocol fee is changed #### Parameters: | Name | Type | Description | | :--------------- | :----- | :------------------------ | | `feeProtocolOld` | uint24 | The previous protocol fee | | `feeProtocolNew` | uint24 | The updated protocol fee | ### SetPoolFeeProtocol ```solidity theme={null} event SetPoolFeeProtocol( address pool, uint24 feeProtocolOld, uint24 feeProtocolNew ) ``` Emitted when a pool-specific protocol fee is changed #### Parameters: | Name | Type | Description | | :--------------- | :------ | :------------------------ | | `pool` | address | The pool address | | `feeProtocolOld` | uint24 | The previous protocol fee | | `feeProtocolNew` | uint24 | The updated protocol fee | ### FeeAdjustment ```solidity theme={null} event FeeAdjustment( address pool, uint24 newFee ) ``` Emitted when a pool's swap fee is changed #### Parameters: | Name | Type | Description | | :------- | :------ | :--------------- | | `pool` | address | The pool address | | `newFee` | uint24 | The new swap fee | ### FeeCollectorChanged ```solidity theme={null} event FeeCollectorChanged( address indexed oldFeeCollector, address indexed newFeeCollector ) ``` Emitted when the fee collector address is changed #### Parameters: | Name | Type | Description | | :---------------- | :------ | :------------------------- | | `oldFeeCollector` | address | The previous fee collector | | `newFeeCollector` | address | The new fee collector | # RamsesV3Pool Source: https://tech.ramses.xyz/contracts/reference/core/RamsesV3Pool ## Functions ### \_blockTimestamp ```solidity theme={null} function _blockTimestamp( ) internal view virtual returns (uint32) ``` Returns the block timestamp truncated to 32 bits, i.e. mod 2\*\*32. This method is overridden in tests. ### \_advancePeriod ```solidity theme={null} modifier _advancePeriod() ``` Modifier that advances the period (weekly epoch) if the current timestamp has crossed into a new period. This drives Ramses' period-based accounting for gauge reward distribution. ### snapshotCumulativesInside ```solidity theme={null} function snapshotCumulativesInside( int24 tickLower, int24 tickUpper ) external view override noDelegateCall returns (int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside) ``` Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range Snapshots must only be compared to other snapshots, taken over a period for which a position existed. I.e., snapshots cannot be compared if a position is not held for the entire period between when the first snapshot is taken and the second snapshot is taken. #### Parameters: | Name | Type | Description | | :---------- | :---- | :-------------------------- | | `tickLower` | int24 | The lower tick of the range | | `tickUpper` | int24 | The upper tick of the range | #### Return Values: | Name | Type | Description | | :------------------------------ | :------ | :-------------------------------------------------- | | `tickCumulativeInside` | int56 | The snapshot of the tick accumulator for the range | | `secondsPerLiquidityInsideX128` | uint160 | The snapshot of seconds per liquidity for the range | | `secondsInside` | uint32 | The snapshot of seconds per liquidity for the range | ### observe ```solidity theme={null} function observe( uint32[] secondsAgos ) external view override noDelegateCall returns (int56[] tickCumulatives, uint160[] secondsPerLiquidityCumulativeX128s) ``` Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, you must call it with secondsAgos = \[3600, 0]. The time weighted average tick represents the geometric time weighted average price of the pool, in log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. #### Parameters: | Name | Type | Description | | :------------ | :-------- | :---------------------------------------------------------------------------- | | `secondsAgos` | uint32\[] | From how long ago each cumulative tick and liquidity value should be returned | #### Return Values: | Name | Type | Description | | :----------------------------------- | :--------- | :---------------------------------------------------------------------------------------------- | | `tickCumulatives` | int56\[] | Cumulative tick values as of each `secondsAgos` from the current block timestamp | | `secondsPerLiquidityCumulativeX128s` | uint160\[] | Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block | timestamp ### increaseObservationCardinalityNext ```solidity theme={null} function increaseObservationCardinalityNext( uint16 observationCardinalityNext ) external override lock noDelegateCall ``` Increase the maximum number of price and liquidity observations that this pool will store This method is no-op if the pool already has an observationCardinalityNext greater than or equal to the input observationCardinalityNext. #### Parameters: | Name | Type | Description | | :--------------------------- | :----- | :--------------------------------------------------------------- | | `observationCardinalityNext` | uint16 | The desired minimum number of observations for the pool to store | ### initialize ```solidity theme={null} function initialize( uint160 sqrtPriceX96 ) external override ``` Sets the initial price for the pool not locked because it initializes unlocked #### Parameters: | Name | Type | Description | | :------------- | :------ | :--------------------------------------------- | | `sqrtPriceX96` | uint160 | the initial sqrt price of the pool as a Q64.96 | ### mint ```solidity theme={null} function mint( address recipient, uint256 index, int24 tickLower, int24 tickUpper, uint128 amount, bytes data ) external override lock returns (uint256 amount0, uint256 amount1) ``` Adds liquidity for the given recipient/index/tickLower/tickUpper position noDelegateCall is applied indirectly via \_modifyPosition. The `index` parameter distinguishes multiple positions by the same owner at the same tick range, and is included in the position key hash: `keccak256(abi.encodePacked(owner, index, tickLower, tickUpper))`. #### Parameters: | Name | Type | Description | | :---------- | :------ | :----------------------------------------------------------------------------------- | | `recipient` | address | The address for which the liquidity will be created | | `index` | uint256 | The index of the position (used to distinguish multiple positions at the same range) | | `tickLower` | int24 | The lower tick of the position in which to add liquidity | | `tickUpper` | int24 | The upper tick of the position in which to add liquidity | | `amount` | uint128 | The amount of liquidity to mint | | `data` | bytes | Any data that should be passed through to the callback | #### Return Values: | Name | Type | Description | | :-------- | :------ | :---------------------------------------------------------------------------------------------------------- | | `amount0` | uint256 | The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback | | `amount1` | uint256 | The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback | ### collect ```solidity theme={null} function collect( address recipient, uint256 index, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external override lock returns (uint128 amount0, uint128 amount1) ``` Collects tokens owed to a position Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. #### Parameters: | Name | Type | Description | | :----------------- | :------ | :------------------------------------------------------- | | `recipient` | address | The address which should receive the fees collected | | `index` | uint256 | The index of the position | | `tickLower` | int24 | The lower tick of the position for which to collect fees | | `tickUpper` | int24 | The upper tick of the position for which to collect fees | | `amount0Requested` | uint128 | How much token0 should be withdrawn from the fees owed | | `amount1Requested` | uint128 | How much token1 should be withdrawn from the fees owed | #### Return Values: | Name | Type | Description | | :-------- | :------ | :------------------------------------- | | `amount0` | uint128 | The amount of fees collected in token0 | | `amount1` | uint128 | The amount of fees collected in token1 | ### burn ```solidity theme={null} function burn( uint256 index, int24 tickLower, int24 tickUpper, uint128 amount ) external override lock returns (uint256 amount0, uint256 amount1) ``` Burn liquidity from the sender and account tokens owed for the liquidity to the position noDelegateCall is applied indirectly via \_modifyPosition #### Parameters: | Name | Type | Description | | :---------- | :------ | :--------------------------------------------------------- | | `index` | uint256 | The index of the position | | `tickLower` | int24 | The lower tick of the position for which to burn liquidity | | `tickUpper` | int24 | The upper tick of the position for which to burn liquidity | | `amount` | uint128 | How much liquidity to burn | #### Return Values: | Name | Type | Description | | :-------- | :------ | :----------------------------------------- | | `amount0` | uint256 | The amount of token0 sent to the recipient | | `amount1` | uint256 | The amount of token1 sent to the recipient | ### swap ```solidity theme={null} function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes data ) external override returns (int256 amount0, int256 amount1) ``` Swap token0 for token1, or token1 for token0 The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback #### Parameters: | Name | Type | Description | | :------------------ | :------ | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `recipient` | address | The address to receive the output of the swap | | `zeroForOne` | bool | The direction of the swap, true for token0 to token1, false for token1 to token0 | | `amountSpecified` | int256 | The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) | | `sqrtPriceLimitX96` | uint160 | The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this value after the swap. If one for zero, the price cannot be greater than this value after the swap | | `data` | bytes | Any data to be passed through to the callback | #### Return Values: | Name | Type | Description | | :-------- | :----- | :----------------------------------------------------------------------------------------- | | `amount0` | int256 | The delta of the balance of token0 of the pool, exact when negative, minimum when positive | | `amount1` | int256 | The delta of the balance of token1 of the pool, exact when negative, minimum when positive | ### flash ```solidity theme={null} function flash( address recipient, uint256 amount0, uint256 amount1, bytes data ) external override lock noDelegateCall ``` Receive token0 and/or token1 and pay it back, plus a fee, in the callback The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling with 0 amount and sending the donation amount(s) from the callback #### Parameters: | Name | Type | Description | | :---------- | :------ | :----------------------------------------------------------- | | `recipient` | address | The address which will receive the token0 and token1 amounts | | `amount0` | uint256 | The amount of token0 to send | | `amount1` | uint256 | The amount of token1 to send | | `data` | bytes | Any data to be passed through to the callback | ### setFee ```solidity theme={null} function setFee( uint24 _fee ) external override lock ``` Sets the pool's swap fee dynamically. Can only be called by the factory. Can only be called by the factory. Ramses-specific addition allowing governance to adjust swap fees per pool. #### Parameters: | Name | Type | Description | | :----- | :----- | :--------------------------------------------------------------- | | `_fee` | uint24 | The new swap fee, denominated in hundredths of a bip (i.e. 1e-6) | ### setFeeProtocol ```solidity theme={null} function setFeeProtocol( ) external override lock ``` Syncs the pool's protocol fee from the factory. Called by the factory when the global or pool-specific fee protocol is updated. Takes no parameters -- reads the fee directly from `IRamsesV3Factory.poolFeeProtocol(address(this))`. ### collectProtocol ```solidity theme={null} function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external override lock onlyFactoryOwner returns (uint128 amount0, uint128 amount1) ``` Collect the protocol fee accrued to the pool #### Parameters: | Name | Type | Description | | :----------------- | :------ | :---------------------------------------------------------------------------- | | `recipient` | address | The address to which collected protocol fees should be sent | | `amount0Requested` | uint128 | The maximum amount of token0 to send, can be 0 to collect fees in only token1 | | `amount1Requested` | uint128 | The maximum amount of token1 to send, can be 0 to collect fees in only token0 | #### Return Values: | Name | Type | Description | | :-------- | :------ | :----------------------------------- | | `amount0` | uint128 | The protocol fee collected in token0 | | `amount1` | uint128 | The protocol fee collected in token1 | ## Ramses-Specific State ### grossFeeGrowthGlobal0X128 ```solidity theme={null} function grossFeeGrowthGlobal0X128( ) external view returns (uint256) ``` The gross fee growth of token0 as a Q128.128. Tracks fees before protocol fee deduction. ### grossFeeGrowthGlobal1X128 ```solidity theme={null} function grossFeeGrowthGlobal1X128( ) external view returns (uint256) ``` The gross fee growth of token1 as a Q128.128. Tracks fees before protocol fee deduction. ### periods The pool maintains an array of period snapshots for weekly epoch-based accounting. Each period contains cumulative data used by GaugeV3 to distribute rewards proportionally to liquidity providers based on their time-weighted in-range contribution during each period. ### Storage RamsesV3Pool uses ERC-7201 namespaced storage via the `PoolStorage` library. All pool state is stored in a structured namespace rather than raw storage slots, improving upgradeability and avoiding storage collisions. Position keys are computed as: `keccak256(abi.encodePacked(owner, index, tickLower, tickUpper))` -- note the extra `index` parameter compared to Uniswap V3. # RamsesV3PoolDeployer Source: https://tech.ramses.xyz/contracts/reference/core/RamsesV3PoolDeployer ## Functions ### deploy ```solidity theme={null} function deploy( address token0, address token1, int24 tickSpacing ) external returns (address pool) ``` Deploys a pool with the given parameters. Can only be called by the RamsesV3Factory. The pool's factory, fee, and tick spacing are read from the factory's `parameters()` transient storage during deployment. #### Parameters: | Name | Type | Description | | :------------ | :------ | :------------------------------------------------- | | `token0` | address | The first token of the pool by address sort order | | `token1` | address | The second token of the pool by address sort order | | `tickSpacing` | int24 | The spacing between usable ticks | #### Return Values: | Name | Type | Description | | :----- | :------ | :------------------------------------ | | `pool` | address | The address of the newly created pool | ### parameters ```solidity theme={null} function parameters( ) external view returns (address factory, address token0, address token1, uint24 fee, int24 tickSpacing) ``` Returns the pool constructor parameters. Reads from the factory's `parameters()` storage, which is transiently set during `createPool` and cleared after deployment. ### RamsesV3Factory ```solidity theme={null} function RamsesV3Factory( ) external view returns (address) ``` Returns the address of the canonical RamsesV3Factory. Set as an immutable in the constructor. # IERC20Minimal Source: https://tech.ramses.xyz/contracts/reference/core/interfaces/IERC20Minimal Contains a subset of the full ERC20 interface that is used in Ramses V3 ## Functions ### balanceOf ```solidity theme={null} function balanceOf( address account ) external view returns (uint256) ``` Returns the balance of a token #### Parameters: | Name | Type | Description | | :-------- | :------ | :----------------------------------------------------------------------------- | | `account` | address | The account for which to look up the number of tokens it has, i.e. its balance | #### Return Values: | Type | Description | | :------ | :----------------------------------- | | uint256 | number of tokens held by the account | ### transfer ```solidity theme={null} function transfer( address recipient, uint256 amount ) external returns (bool) ``` Transfers the amount of token from the `msg.sender` to the recipient #### Parameters: | Name | Type | Description | | :---------- | :------ | :------------------------------------------------------------ | | `recipient` | address | The account that will receive the amount transferred | | `amount` | uint256 | The number of tokens to send from the sender to the recipient | #### Return Values: | Type | Description | | :--- | :----------------------------------------------------------------- | | bool | true for a successful transfer, false for an unsuccessful transfer | ### allowance ```solidity theme={null} function allowance( address owner, address spender ) external view returns (uint256) ``` Returns the current allowance given to a spender by an owner #### Parameters: | Name | Type | Description | | :-------- | :------ | :------------------------------- | | `owner` | address | The account of the token owner | | `spender` | address | The account of the token spender | #### Return Values: | Type | Description | | :------ | :------------------------------------------------ | | uint256 | current allowance granted by `owner` to `spender` | ### approve ```solidity theme={null} function approve( address spender, uint256 amount ) external returns (bool) ``` Sets the allowance of a spender from the `msg.sender` to the value `amount` #### Parameters: | Name | Type | Description | | :-------- | :------ | :----------------------------------------------------------------------------- | | `spender` | address | The account which will be allowed to spend a given amount of the owners tokens | | `amount` | uint256 | The amount of tokens allowed to be used by `spender` | #### Return Values: | Type | Description | | :--- | :----------------------------------------------------- | | bool | true for a successful approval, false for unsuccessful | ### transferFrom ```solidity theme={null} function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool) ``` Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender` #### Parameters: | Name | Type | Description | | :---------- | :------ | :---------------------------------------------------- | | `sender` | address | The account from which the transfer will be initiated | | `recipient` | address | The recipient of the transfer | | `amount` | uint256 | The amount of the transfer | #### Return Values: | Type | Description | | :--- | :----------------------------------------------------- | | bool | true for a successful transfer, false for unsuccessful | ## Events ### Transfer ```solidity theme={null} event Transfer( address from, address to, uint256 value ) ``` Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`. #### Parameters: | Name | Type | Description | | :------ | :------ | :---------------------------------------------------------------------- | | `from` | address | The account from which the tokens were sent, i.e. the balance decreased | | `to` | address | The account to which the tokens were sent, i.e. the balance increased | | `value` | uint256 | The amount of tokens that were transferred | ### Approval ```solidity theme={null} event Approval( address owner, address spender, uint256 value ) ``` Event emitted when the approval amount for the spender of a given owner's tokens changes. #### Parameters: | Name | Type | Description | | :-------- | :------ | :-------------------------------------------------------- | | `owner` | address | The account that approved spending of its tokens | | `spender` | address | The account for which the spending allowance was modified | | `value` | uint256 | The new allowance from the owner to the spender | # IRamsesV3Factory Source: https://tech.ramses.xyz/contracts/reference/core/interfaces/IRamsesV3Factory The Ramses V3 Factory facilitates creation of Ramses V3 pools and control over the protocol fees. It uses the AccessHub pattern for governance instead of simple ownership. ## Functions ### tickSpacingInitialFee ```solidity theme={null} function tickSpacingInitialFee( int24 tickSpacing ) external view returns (uint24) ``` Returns the default fee for a given tick spacing, if enabled, or 0 if not enabled #### Parameters: | Name | Type | Description | | :------------ | :---- | :-------------------------- | | `tickSpacing` | int24 | The tick spacing to look up | #### Return Values: | Type | Description | | :----- | :------------------------------------------------------ | | uint24 | The initial fee for the tick spacing (0 if not enabled) | ### getPool ```solidity theme={null} function getPool( address tokenA, address tokenB, int24 tickSpacing ) external view returns (address pool) ``` Returns the pool address for a given pair of tokens and tick spacing, or address 0 if it does not exist tokenA and tokenB may be passed in either token0/token1 or token1/token0 order #### Parameters: | Name | Type | Description | | :------------ | :------ | :---------------------------------------------- | | `tokenA` | address | The contract address of either token0 or token1 | | `tokenB` | address | The contract address of the other token | | `tickSpacing` | int24 | The tick spacing of the pool | #### Return Values: | Name | Type | Description | | :----- | :------ | :--------------- | | `pool` | address | The pool address | ### createPool ```solidity theme={null} function createPool( address tokenA, address tokenB, int24 tickSpacing, uint160 sqrtPriceX96 ) external returns (address pool) ``` Creates a pool for the given two tokens and tick spacing, optionally initializing it with a price tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. The fee is automatically derived from `tickSpacingInitialFee`. The call will revert if the pool already exists or the token arguments are invalid. If `sqrtPriceX96` is non-zero, the pool is initialized with that price. #### Parameters: | Name | Type | Description | | :------------- | :------ | :-------------------------------------------------------------- | | `tokenA` | address | One of the two tokens in the desired pool | | `tokenB` | address | The other of the two tokens in the desired pool | | `tickSpacing` | int24 | The desired tick spacing for the pool | | `sqrtPriceX96` | uint160 | The initial sqrt price of the pool as a Q64.96 (0 to skip init) | #### Return Values: | Name | Type | Description | | :----- | :------ | :------------------------------------ | | `pool` | address | The address of the newly created pool | ### enableTickSpacing ```solidity theme={null} function enableTickSpacing( int24 tickSpacing, uint24 initialFee ) external ``` Enables a tick spacing with the given default fee #### Parameters: | Name | Type | Description | | :------------ | :----- | :--------------------------------------------------------------------- | | `tickSpacing` | int24 | The spacing between ticks to enable | | `initialFee` | uint24 | The default fee amount, denominated in hundredths of a bip (i.e. 1e-6) | ### setFeeProtocol ```solidity theme={null} function setFeeProtocol( uint24 _feeProtocol ) external ``` Sets the default protocol fee for all pools #### Parameters: | Name | Type | Description | | :------------- | :----- | :---------------------------------------------------------- | | `_feeProtocol` | uint24 | The new default protocol fee, denominated in 1e-6 precision | ### setPoolFeeProtocol ```solidity theme={null} function setPoolFeeProtocol( address pool, uint24 _feeProtocol ) external ``` Sets the protocol fee for a specific pool #### Parameters: | Name | Type | Description | | :------------- | :------ | :--------------------------------------------- | | `pool` | address | The pool address to update | | `_feeProtocol` | uint24 | The new protocol fee for the pool (1e-6 basis) | ### gaugeFeeSplitEnable ```solidity theme={null} function gaugeFeeSplitEnable( address pool ) external ``` Enables gauge fee splitting for a pool #### Parameters: | Name | Type | Description | | :----- | :------ | :---------------------------------------- | | `pool` | address | The pool to enable gauge fee splitting on | ### setFeeCollector ```solidity theme={null} function setFeeCollector( address _feeCollector ) external ``` Updates the fee collector address #### Parameters: | Name | Type | Description | | :-------------- | :------ | :---------------------------- | | `_feeCollector` | address | The new fee collector address | ### setVoter ```solidity theme={null} function setVoter( address _voter ) external ``` Updates the voter contract address #### Parameters: | Name | Type | Description | | :------- | :------ | :-------------------- | | `_voter` | address | The new voter address | ### setFee ```solidity theme={null} function setFee( address _pool, uint24 _fee ) external ``` Sets the swap fee for a specific pool #### Parameters: | Name | Type | Description | | :------ | :------ | :--------------------------------------------------------------- | | `_pool` | address | The pool to update | | `_fee` | uint24 | The new swap fee, denominated in hundredths of a bip (i.e. 1e-6) | ### voter ```solidity theme={null} function voter( ) external returns (address) ``` Returns the address of the Voter contract ### feeCollector ```solidity theme={null} function feeCollector( ) external view returns (address) ``` Returns the address of the FeeCollector contract ### feeProtocol ```solidity theme={null} function feeProtocol( ) external view returns (uint24) ``` Returns the default protocol fee ### poolFeeProtocol ```solidity theme={null} function poolFeeProtocol( address pool ) external view returns (uint24) ``` Returns the effective protocol fee for a specific pool ## Events ### PoolCreated ```solidity theme={null} event PoolCreated( address token0, address token1, uint24 fee, int24 tickSpacing, address pool ) ``` Emitted when a pool is created #### Parameters: | Name | Type | Description | | :------------ | :------ | :-------------------------------------------------------------------------------- | | `token0` | address | The first token of the pool by address sort order | | `token1` | address | The second token of the pool by address sort order | | `fee` | uint24 | The fee collected upon every swap in the pool, denominated in hundredths of a bip | | `tickSpacing` | int24 | The minimum number of ticks between initialized ticks | | `pool` | address | The address of the created pool | ### TickSpacingEnabled ```solidity theme={null} event TickSpacingEnabled( int24 tickSpacing, uint24 fee ) ``` Emitted when a new tick spacing is enabled for pool creation via the factory #### Parameters: | Name | Type | Description | | :------------ | :----- | :----------------------------------------------- | | `tickSpacing` | int24 | The tick spacing that was enabled | | `fee` | uint24 | The default fee associated with the tick spacing | ### SetFeeProtocol ```solidity theme={null} event SetFeeProtocol( uint24 feeProtocolOld, uint24 feeProtocolNew ) ``` Emitted when the default protocol fee is changed #### Parameters: | Name | Type | Description | | :--------------- | :----- | :------------------------ | | `feeProtocolOld` | uint24 | The previous protocol fee | | `feeProtocolNew` | uint24 | The updated protocol fee | ### SetPoolFeeProtocol ```solidity theme={null} event SetPoolFeeProtocol( address pool, uint24 feeProtocolOld, uint24 feeProtocolNew ) ``` Emitted when a pool-specific protocol fee is changed #### Parameters: | Name | Type | Description | | :--------------- | :------ | :------------------------ | | `pool` | address | The pool address | | `feeProtocolOld` | uint24 | The previous protocol fee | | `feeProtocolNew` | uint24 | The updated protocol fee | ### FeeAdjustment ```solidity theme={null} event FeeAdjustment( address pool, uint24 newFee ) ``` Emitted when a pool's swap fee is changed ### FeeCollectorChanged ```solidity theme={null} event FeeCollectorChanged( address indexed oldFeeCollector, address indexed newFeeCollector ) ``` Emitted when the fee collector address is changed # IRamsesV3Pool Source: https://tech.ramses.xyz/contracts/reference/core/interfaces/IRamsesV3Pool A Ramses V3 pool facilitates swapping and automated market making between any two assets that strictly conform to the ERC20 specification The pool interface is broken up into many smaller pieces # IRamsesV3PoolDeployer Source: https://tech.ramses.xyz/contracts/reference/core/interfaces/IRamsesV3PoolDeployer A contract that constructs a pool must implement this to pass arguments to the pool This is used to avoid having constructor arguments in the pool contract, which results in the init code hash of the pool being constant allowing the CREATE2 address of the pool to be cheaply computed on-chain ## Functions ### parameters ```solidity theme={null} function parameters( ) external view returns (address factory, address token0, address token1, uint24 fee, int24 tickSpacing) ``` Get the parameters to be used in constructing the pool, set transiently during pool creation. #### Return Values : | Name | Type | Description | | :------------ | :------ | :-------------------------------------------------------------------------------- | | `factory ` | address | The factory address | | `token0` | address | The first token of the pool by address sort order | | `token1` | address | The second token of the pool by address sort order | | `fee ` | uint24 | The fee collected upon every swap in the pool, denominated in hundredths of a bip | | `tickSpacing` | int24 | The minimum number of ticks between initialized ticks | # IUniswapV3FlashCallback Source: https://tech.ramses.xyz/contracts/reference/core/interfaces/callback/IUniswapV3FlashCallback Any contract that calls IRamsesV3PoolActions#flash must implement this interface ## Functions ### uniswapV3FlashCallback ```solidity theme={null} function uniswapV3FlashCallback( uint256 fee0, uint256 fee1, bytes data ) external ``` Called to `msg.sender` after transferring to the recipient from IRamsesV3Pool#flash. In the implementation you must repay the pool the tokens sent by flash plus the computed fee amounts. The caller of this method must be checked to be a RamsesV3Pool deployed by the canonical RamsesV3Factory. #### Parameters: | Name | Type | Description | | :----- | :------ | :---------------------------------------------------------------------------- | | `fee0` | uint256 | The fee amount in token0 due to the pool by the end of the flash | | `fee1` | uint256 | The fee amount in token1 due to the pool by the end of the flash | | `data` | bytes | Any data passed through by the caller via the IRamsesV3PoolActions#flash call | # IUniswapV3MintCallback Source: https://tech.ramses.xyz/contracts/reference/core/interfaces/callback/IUniswapV3MintCallback Any contract that calls IRamsesV3PoolActions#mint must implement this interface ## Functions ### uniswapV3MintCallback ```solidity theme={null} function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes data ) external ``` Called to `msg.sender` after minting liquidity to a position from IRamsesV3Pool#mint. In the implementation you must pay the pool tokens owed for the minted liquidity. The caller of this method must be checked to be a RamsesV3Pool deployed by the canonical RamsesV3Factory. #### Parameters: | Name | Type | Description | | :------------ | :------ | :--------------------------------------------------------------------------- | | `amount0Owed` | uint256 | The amount of token0 due to the pool for the minted liquidity | | `amount1Owed` | uint256 | The amount of token1 due to the pool for the minted liquidity | | `data` | bytes | Any data passed through by the caller via the IRamsesV3PoolActions#mint call | # IUniswapV3SwapCallback Source: https://tech.ramses.xyz/contracts/reference/core/interfaces/callback/IUniswapV3SwapCallback Any contract that calls IRamsesV3PoolActions#swap must implement this interface ## Functions ### uniswapV3SwapCallback ```solidity theme={null} function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes data ) external ``` Called to `msg.sender` after executing a swap via IRamsesV3Pool#swap. In the implementation you must pay the pool tokens owed for the swap. The caller of this method must be checked to be a RamsesV3Pool deployed by the canonical RamsesV3Factory. amount0Delta and amount1Delta can both be 0 if no tokens were swapped. #### Parameters: | Name | Type | Description | | :------------- | :----- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `amount0Delta` | int256 | The amount of token0 that was sent (negative) or must be received (positive) by the pool by the end of the swap. If positive, the callback must send that amount of token0 to the pool. | | `amount1Delta` | int256 | The amount of token1 that was sent (negative) or must be received (positive) by the pool by the end of the swap. If positive, the callback must send that amount of token1 to the pool. | | `data` | bytes | Any data passed through by the caller via the IRamsesV3PoolActions#swap call. | # IRamsesV3PoolActions Source: https://tech.ramses.xyz/contracts/reference/core/interfaces/pool/IRamsesV3PoolActions Contains pool methods that can be called by anyone ## Functions ### initialize ```solidity theme={null} function initialize( uint160 sqrtPriceX96 ) external ``` Sets the initial price for the pool Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value #### Parameters: | Name | Type | Description | | :------------- | :------ | :--------------------------------------------- | | `sqrtPriceX96` | uint160 | the initial sqrt price of the pool as a Q64.96 | ### mint ```solidity theme={null} function mint( address recipient, uint256 index, int24 tickLower, int24 tickUpper, uint128 amount, bytes data ) external returns (uint256 amount0, uint256 amount1) ``` Adds liquidity for the given recipient/index/tickLower/tickUpper position The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends on tickLower, tickUpper, the amount of liquidity, and the current price. #### Parameters: | Name | Type | Description | | :---------- | :------ | :----------------------------------------------------------------------------- | | `recipient` | address | The address for which the liquidity will be created | | `index` | uint256 | The index of the position (distinguishes multiple positions at the same range) | | `tickLower` | int24 | The lower tick of the position in which to add liquidity | | `tickUpper` | int24 | The upper tick of the position in which to add liquidity | | `amount` | uint128 | The amount of liquidity to mint | | `data` | bytes | Any data that should be passed through to the callback | #### Return Values: | Name | Type | Description | | :-------- | :------ | :---------------------------------------------------------------------------------------------------------- | | `amount0` | uint256 | The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback | | `amount1` | uint256 | The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback | ### collect ```solidity theme={null} function collect( address recipient, uint256 index, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1) ``` Collects tokens owed to a position Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. #### Parameters: | Name | Type | Description | | :----------------- | :------ | :------------------------------------------------------- | | `recipient` | address | The address which should receive the fees collected | | `index` | uint256 | The index of the position | | `tickLower` | int24 | The lower tick of the position for which to collect fees | | `tickUpper` | int24 | The upper tick of the position for which to collect fees | | `amount0Requested` | uint128 | How much token0 should be withdrawn from the fees owed | | `amount1Requested` | uint128 | How much token1 should be withdrawn from the fees owed | #### Return Values: | Name | Type | Description | | :-------- | :------ | :------------------------------------- | | `amount0` | uint128 | The amount of fees collected in token0 | | `amount1` | uint128 | The amount of fees collected in token1 | ### burn ```solidity theme={null} function burn( uint256 index, int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1) ``` Burn liquidity from the sender and account tokens owed for the liquidity to the position Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 Fees must be collected separately via a call to #collect #### Parameters: | Name | Type | Description | | :---------- | :------ | :--------------------------------------------------------- | | `index` | uint256 | The index of the position | | `tickLower` | int24 | The lower tick of the position for which to burn liquidity | | `tickUpper` | int24 | The upper tick of the position for which to burn liquidity | | `amount` | uint128 | How much liquidity to burn | #### Return Values: | Name | Type | Description | | :-------- | :------ | :----------------------------------------- | | `amount0` | uint256 | The amount of token0 sent to the recipient | | `amount1` | uint256 | The amount of token1 sent to the recipient | ### swap ```solidity theme={null} function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes data ) external returns (int256 amount0, int256 amount1) ``` Swap token0 for token1, or token1 for token0 The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback #### Parameters: | Name | Type | Description | | :------------------ | :------ | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `recipient` | address | The address to receive the output of the swap | | `zeroForOne` | bool | The direction of the swap, true for token0 to token1, false for token1 to token0 | | `amountSpecified` | int256 | The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) | | `sqrtPriceLimitX96` | uint160 | The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this value after the swap. If one for zero, the price cannot be greater than this value after the swap | | `data` | bytes | Any data passed through to the callback | #### Return Values: | Name | Type | Description | | :-------- | :----- | :----------------------------------------------------------------------------------------- | | `amount0` | int256 | The delta of the balance of token0 of the pool, exact when negative, minimum when positive | | `amount1` | int256 | The delta of the balance of token1 of the pool, exact when negative, minimum when positive | ### flash ```solidity theme={null} function flash( address recipient, uint256 amount0, uint256 amount1, bytes data ) external ``` Receive token0 and/or token1 and pay it back, plus a fee, in the callback The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling with 0 amount and sending the donation amount(s) from the callback #### Parameters: | Name | Type | Description | | :---------- | :------ | :----------------------------------------------------------- | | `recipient` | address | The address which will receive the token0 and token1 amounts | | `amount0` | uint256 | The amount of token0 to send | | `amount1` | uint256 | The amount of token1 to send | | `data` | bytes | Any data to be passed through to the callback | ### increaseObservationCardinalityNext ```solidity theme={null} function increaseObservationCardinalityNext( uint16 observationCardinalityNext ) external ``` Increase the maximum number of price and liquidity observations that this pool will store This method is no-op if the pool already has an observationCardinalityNext greater than or equal to the input observationCardinalityNext. #### Parameters: | Name | Type | Description | | :--------------------------- | :----- | :--------------------------------------------------------------- | | `observationCardinalityNext` | uint16 | The desired minimum number of observations for the pool to store | # IRamsesV3PoolDerivedState Source: https://tech.ramses.xyz/contracts/reference/core/interfaces/pool/IRamsesV3PoolDerivedState Contains view functions to provide information about the pool that is computed rather than stored on the blockchain. The functions here may have variable gas costs. ## Functions ### observe ```solidity theme={null} function observe( uint32[] secondsAgos ) external view returns (int56[] tickCumulatives, uint160[] secondsPerLiquidityCumulativeX128s) ``` Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, you must call it with secondsAgos = \[3600, 0]. The time weighted average tick represents the geometric time weighted average price of the pool, in log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. #### Parameters: | Name | Type | Description | | :------------ | :-------- | :---------------------------------------------------------------------------- | | `secondsAgos` | uint32\[] | From how long ago each cumulative tick and liquidity value should be returned | #### Return Values: | Name | Type | Description | | :----------------------------------- | :--------- | :---------------------------------------------------------------------------------------------- | | `tickCumulatives` | int56\[] | Cumulative tick values as of each `secondsAgos` from the current block timestamp | | `secondsPerLiquidityCumulativeX128s` | uint160\[] | Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block | timestamp ### snapshotCumulativesInside ```solidity theme={null} function snapshotCumulativesInside( int24 tickLower, int24 tickUpper ) external view returns (int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside) ``` Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range Snapshots must only be compared to other snapshots, taken over a period for which a position existed. I.e., snapshots cannot be compared if a position is not held for the entire period between when the first snapshot is taken and the second snapshot is taken. #### Parameters: | Name | Type | Description | | :---------- | :---- | :-------------------------- | | `tickLower` | int24 | The lower tick of the range | | `tickUpper` | int24 | The upper tick of the range | #### Return Values: | Name | Type | Description | | :------------------------------ | :------ | :-------------------------------------------------- | | `tickCumulativeInside` | int56 | The snapshot of the tick accumulator for the range | | `secondsPerLiquidityInsideX128` | uint160 | The snapshot of seconds per liquidity for the range | | `secondsInside` | uint32 | The snapshot of seconds per liquidity for the range | # IRamsesV3PoolEvents Source: https://tech.ramses.xyz/contracts/reference/core/interfaces/pool/IRamsesV3PoolEvents Contains all events emitted by the pool ## Events ### Initialize ```solidity theme={null} event Initialize( uint160 sqrtPriceX96, int24 tick ) ``` Emitted exactly once by a pool when #initialize is first called on the pool Mint/Burn/Swap cannot be emitted by the pool before Initialize #### Parameters: | Name | Type | Description | | :------------- | :------ | :----------------------------------------------------------------------------------- | | `sqrtPriceX96` | uint160 | The initial sqrt price of the pool, as a Q64.96 | | `tick` | int24 | The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool | ### Mint ```solidity theme={null} event Mint( address sender, address indexed owner, uint256 index, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ) ``` Emitted when liquidity is minted for a given position #### Parameters: | Name | Type | Description | | :---------- | :------ | :-------------------------------------------------------------- | | `sender` | address | The address that minted the liquidity | | `owner` | address | The owner of the position and recipient of any minted liquidity | | `index` | uint256 | The index of the position | | `tickLower` | int24 | The lower tick of the position | | `tickUpper` | int24 | The upper tick of the position | | `amount` | uint128 | The amount of liquidity minted to the position range | | `amount0` | uint256 | How much token0 was required for the minted liquidity | | `amount1` | uint256 | How much token1 was required for the minted liquidity | ### Collect ```solidity theme={null} event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ) ``` Emitted when fees are collected by the owner of a position Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees #### Parameters: | Name | Type | Description | | :---------- | :------ | :----------------------------------------------------- | | `owner` | address | The owner of the position for which fees are collected | | `recipient` | address | The address that received the collected fees | | `tickLower` | int24 | The lower tick of the position | | `tickUpper` | int24 | The upper tick of the position | | `amount0` | uint128 | The amount of token0 fees collected | | `amount1` | uint128 | The amount of token1 fees collected | ### Burn ```solidity theme={null} event Burn( address owner, int24 tickLower, int24 tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ) ``` Emitted when a position's liquidity is removed Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect #### Parameters: | Name | Type | Description | | :---------- | :------ | :------------------------------------------------------- | | `owner` | address | The owner of the position for which liquidity is removed | | `tickLower` | int24 | The lower tick of the position | | `tickUpper` | int24 | The upper tick of the position | | `amount` | uint128 | The amount of liquidity to remove | | `amount0` | uint256 | The amount of token0 withdrawn | | `amount1` | uint256 | The amount of token1 withdrawn | ### Swap ```solidity theme={null} event Swap( address sender, address recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ) ``` Emitted by the pool for any swaps between token0 and token1 #### Parameters: | Name | Type | Description | | :------------- | :------ | :----------------------------------------------------------------------- | | `sender` | address | The address that initiated the swap call, and that received the callback | | `recipient` | address | The address that received the output of the swap | | `amount0` | int256 | The delta of the token0 balance of the pool | | `amount1` | int256 | The delta of the token1 balance of the pool | | `sqrtPriceX96` | uint160 | The sqrt(price) of the pool after the swap, as a Q64.96 | | `liquidity` | uint128 | The liquidity of the pool after the swap | | `tick` | int24 | The log base 1.0001 of price of the pool after the swap | ### Flash ```solidity theme={null} event Flash( address sender, address recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ) ``` Emitted by the pool for any flashes of token0/token1 #### Parameters: | Name | Type | Description | | :---------- | :------ | :--------------------------------------------------------------------------------- | | `sender` | address | The address that initiated the swap call, and that received the callback | | `recipient` | address | The address that received the tokens from flash | | `amount0` | uint256 | The amount of token0 that was flashed | | `amount1` | uint256 | The amount of token1 that was flashed | | `paid0` | uint256 | The amount of token0 paid for the flash, which can exceed the amount0 plus the fee | | `paid1` | uint256 | The amount of token1 paid for the flash, which can exceed the amount1 plus the fee | ### IncreaseObservationCardinalityNext ```solidity theme={null} event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ) ``` Emitted by the pool for increases to the number of observations that can be stored observationCardinalityNext is not the observation cardinality until an observation is written at the index just before a mint/swap/burn. #### Parameters: | Name | Type | Description | | :------------------------------ | :----- | :----------------------------------------------------- | | `observationCardinalityNextOld` | uint16 | The previous value of the next observation cardinality | | `observationCardinalityNextNew` | uint16 | The updated value of the next observation cardinality | ### SetFeeProtocol ```solidity theme={null} event SetFeeProtocol( uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New ) ``` Emitted when the protocol fee is changed by the pool #### Parameters: | Name | Type | Description | | :---------------- | :---- | :-------------------------------------------- | | `feeProtocol0Old` | uint8 | The previous value of the token0 protocol fee | | `feeProtocol1Old` | uint8 | The previous value of the token1 protocol fee | | `feeProtocol0New` | uint8 | The updated value of the token0 protocol fee | | `feeProtocol1New` | uint8 | The updated value of the token1 protocol fee | ### CollectProtocol ```solidity theme={null} event CollectProtocol( address sender, address recipient, uint128 amount0, uint128 amount1 ) ``` Emitted when the collected protocol fees are withdrawn by the factory owner #### Parameters: | Name | Type | Description | | :---------- | :------ | :---------------------------------------------------- | | `sender` | address | The address that collects the protocol fees | | `recipient` | address | The address that receives the collected protocol fees | | `amount0` | uint128 | The amount of token0 protocol fees that is withdrawn | | `amount1` | uint128 | The amount of token1 protocol fees that is withdrawn | # IRamsesV3PoolImmutables Source: https://tech.ramses.xyz/contracts/reference/core/interfaces/pool/IRamsesV3PoolImmutables These parameters are fixed for a pool forever, i.e., the methods will always return the same values ## Functions ### factory ```solidity theme={null} function factory( ) external view returns (address) ``` The contract that deployed the pool, which must adhere to the IRamsesV3Factory interface #### Return Values: | Type | Description | | :------ | :--------------- | | address | contract address | ### token0 ```solidity theme={null} function token0( ) external view returns (address) ``` The first of the two tokens of the pool, sorted by address #### Return Values: | Type | Description | | :------ | :--------------------- | | address | token contract address | ### token1 ```solidity theme={null} function token1( ) external view returns (address) ``` The second of the two tokens of the pool, sorted by address #### Return Values: | Type | Description | | :------ | :--------------------- | | address | token contract address | ### fee ```solidity theme={null} function fee( ) external view returns (uint24) ``` The pool's fee in hundredths of a bip, i.e. 1e-6 #### Return Values: | Type | Description | | :----- | :---------- | | uint24 | fee | ### tickSpacing ```solidity theme={null} function tickSpacing( ) external view returns (int24) ``` The pool tick spacing Ticks can only be used at multiples of this value, minimum of 1 and always positive e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... This value is an int24 to avoid casting even though it is always positive. #### Return Values: | Type | Description | | :---- | :----------- | | int24 | tick spacing | ### maxLiquidityPerTick ```solidity theme={null} function maxLiquidityPerTick( ) external view returns (uint128) ``` The maximum amount of position liquidity that can use any tick in the range This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool #### Return Values: | Type | Description | | :------ | :------------------------------- | | uint128 | max amount of liquidity per tick | # IRamsesV3PoolOwnerActions Source: https://tech.ramses.xyz/contracts/reference/core/interfaces/pool/IRamsesV3PoolOwnerActions Contains pool methods that may only be called by the factory owner ## Functions ### setFeeProtocol ```solidity theme={null} function setFeeProtocol( ) external ``` Syncs the pool's protocol fee from the factory. Called by the factory when the global or pool-specific fee protocol is updated. Takes no parameters -- reads the fee directly from `IRamsesV3Factory.poolFeeProtocol(address(this))`. ### collectProtocol ```solidity theme={null} function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1) ``` Collect the protocol fee accrued to the pool #### Parameters: | Name | Type | Description | | :----------------- | :------ | :---------------------------------------------------------------------------- | | `recipient` | address | The address to which collected protocol fees should be sent | | `amount0Requested` | uint128 | The maximum amount of token0 to send, can be 0 to collect fees in only token1 | | `amount1Requested` | uint128 | The maximum amount of token1 to send, can be 0 to collect fees in only token0 | #### Return Values: | Name | Type | Description | | :-------- | :------ | :----------------------------------- | | `amount0` | uint128 | The protocol fee collected in token0 | | `amount1` | uint128 | The protocol fee collected in token1 | ### setFee ```solidity theme={null} function setFee( uint24 _fee ) external ``` Sets the pool's swap fee. Can only be called by the factory. Ramses-specific addition allowing governance to adjust fees per pool. #### Parameters: | Name | Type | Description | | :----- | :----- | :--------------------------------------------------------------- | | `_fee` | uint24 | The new swap fee, denominated in hundredths of a bip (i.e. 1e-6) | # IRamsesV3PoolState Source: https://tech.ramses.xyz/contracts/reference/core/interfaces/pool/IRamsesV3PoolState These methods compose the pool's state, and can change with any frequency including multiple times per transaction ## Functions ### slot0 ```solidity theme={null} function slot0( ) external view returns (uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint24 feeProtocol, bool unlocked) ``` The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas when accessed externally. #### Return Values: | Name | Type | Description | | :--------------------------- | :------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `sqrtPriceX96` | uint160 | The current price of the pool as a sqrt(token1/token0) Q64.96 value | | `tick` | int24 | The current tick of the pool, i.e. according to the last tick transition that was run. This value may not always be equal to SqrtTickMath getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick boundary. | | `observationIndex` | uint16 | The index of the last oracle observation that was written, | | `observationCardinality` | uint16 | The current maximum number of observations stored in the pool, | | `observationCardinalityNext` | uint16 | The next maximum number of observations, to be updated when the observation. | | `feeProtocol` | uint24 | The protocol fee for the pool, denominated in 1e-6 precision. Determines the fraction of swap fees directed to the protocol. | | `unlocked` | bool | Whether the pool is currently locked to reentrancy | ### feeGrowthGlobal0X128 ```solidity theme={null} function feeGrowthGlobal0X128( ) external view returns (uint256) ``` The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool This value can overflow the uint256 ### feeGrowthGlobal1X128 ```solidity theme={null} function feeGrowthGlobal1X128( ) external view returns (uint256) ``` The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool This value can overflow the uint256 ### grossFeeGrowthGlobal0X128 ```solidity theme={null} function grossFeeGrowthGlobal0X128( ) external view returns (uint256) ``` The gross fee growth of token0 as a Q128.128, tracking fees before protocol fee deduction. Ramses-specific. ### grossFeeGrowthGlobal1X128 ```solidity theme={null} function grossFeeGrowthGlobal1X128( ) external view returns (uint256) ``` The gross fee growth of token1 as a Q128.128, tracking fees before protocol fee deduction. Ramses-specific. ### protocolFees ```solidity theme={null} function protocolFees( ) external view returns (uint128 token0, uint128 token1) ``` The amounts of token0 and token1 that are owed to the protocol Protocol fees will never exceed uint128 max in either token ### liquidity ```solidity theme={null} function liquidity( ) external view returns (uint128) ``` The currently in range liquidity available to the pool This value has no relationship to the total liquidity across all ticks ### ticks ```solidity theme={null} function ticks( int24 tick ) external view returns (uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized) ``` Look up information about a specific tick in the pool #### Parameters: | Name | Type | Description | | :----- | :---- | :------------------ | | `tick` | int24 | The tick to look up | #### Return Values: | Name | Type | Description | | :------------------------------- | :------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `liquidityGross` | uint128 | the total amount of position liquidity that uses the pool either as tick lower or tick upper, | | `liquidityNet` | int128 | how much liquidity changes when the pool price crosses the tick, | | `feeGrowthOutside0X128` | uint256 | the fee growth on the other side of the tick from the current tick in token0, | | `feeGrowthOutside1X128` | uint256 | the fee growth on the other side of the tick from the current tick in token1, feeGrowthOutsideX128 values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. In addition, these values are only relative and are used to compute snapshots. | | `tickCumulativeOutside` | int56 | | | `secondsPerLiquidityOutsideX128` | uint160 | | | `secondsOutside` | uint32 | | | `initialized` | bool | | a specific position. ### tickBitmap ```solidity theme={null} function tickBitmap( int16 wordPosition ) external view returns (uint256) ``` Returns 256 packed tick initialized boolean values. See TickBitmap for more information ### positions ```solidity theme={null} function positions( bytes32 key ) external view returns (uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1) ``` Returns the information about a position by the position's key In Ramses V3, the position key is computed as: `keccak256(abi.encodePacked(owner, index, tickLower, tickUpper))` -- note the extra `index` parameter compared to Uniswap V3. #### Parameters: | Name | Type | Description | | :---- | :------ | :----------------------------------------------------------------------------------------------- | | `key` | bytes32 | The position's key is a hash of a preimage composed by the owner, index, tickLower and tickUpper | #### Return Values: | Name | Type | Description | | :------------------------- | :------ | :-------------------------------------------------------------------------------- | | `liquidity` | uint128 | The amount of liquidity in the position, | | `feeGrowthInside0LastX128` | uint256 | fee growth of token0 inside the tick range as of the last mint/burn/poke, | | `feeGrowthInside1LastX128` | uint256 | fee growth of token1 inside the tick range as of the last mint/burn/poke, | | `tokensOwed0` | uint128 | the computed amount of token0 owed to the position as of the last mint/burn/poke, | | `tokensOwed1` | uint128 | the computed amount of token1 owed to the position as of the last mint/burn/poke | ### observations ```solidity theme={null} function observations( uint256 index ) external view returns (uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized) ``` Returns data about a specific observation index You most likely want to use #observe() instead of this method to get an observation as of some amount of time ago, rather than at a specific index in the array. #### Parameters: | Name | Type | Description | | :------ | :------ | :--------------------------------------------- | | `index` | uint256 | The element of the observations array to fetch | #### Return Values: | Name | Type | Description | | :---------------------------------- | :------ | :----------------------------------------------------------------------------------------------- | | `blockTimestamp` | uint256 | The timestamp of the observation, | | `tickCumulative` | int56 | the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, | | `secondsPerLiquidityCumulativeX128` | uint160 | the seconds per in range liquidity for the life of the pool as of the observation timestamp | | `initialized` | bool | whether the observation has been initialized and the values are safe to use | ### positionPeriodSecondsInRange ```solidity theme={null} function positionPeriodSecondsInRange( uint256 period, address owner, uint256 index, int24 tickLower, int24 tickUpper ) external view returns (uint256 periodSecondsInsideX96) ``` Returns the seconds a specific position was in range during a given period. Used by GaugeV3 for proportional reward distribution. #### Parameters: | Name | Type | Description | | :---------- | :------ | :------------------------- | | `period` | uint256 | The period number | | `owner` | address | The position owner address | | `index` | uint256 | The position index | | `tickLower` | int24 | Lower bound of range | | `tickUpper` | int24 | Upper bound of range | #### Return Values: | Name | Type | Description | | :----------------------- | :------ | :----------------------------------------------- | | `periodSecondsInsideX96` | uint256 | Seconds the position was in range for the period | ### periods The pool maintains an array of period snapshots that store cumulative data per weekly epoch. These are used by the GaugeV3 contract to distribute rewards proportionally based on time-weighted in-range liquidity during each period. # BitMath Source: https://tech.ramses.xyz/contracts/reference/core/libraries/BitMath This library provides functionality for computing bit properties of an unsigned integer ## Functions ### mostSignificantBit ```solidity theme={null} function mostSignificantBit( uint256 x ) internal pure returns (uint8 r) ``` Returns the index of the most significant bit of the number, where the least significant bit is at index 0 and the most significant bit is at index 255 The function satisfies the property: x >= 2**mostSignificantBit(x) and x \< 2**(mostSignificantBit(x)+1) #### Parameters: | Name | Type | Description | | :--- | :------ | :------------------------------------------------------------------------------ | | `x` | uint256 | the value for which to compute the most significant bit, must be greater than 0 | #### Return Values: | Name | Type | Description | | :--- | :---- | :------------------------------------ | | `r` | uint8 | the index of the most significant bit | ### leastSignificantBit ```solidity theme={null} function leastSignificantBit( uint256 x ) internal pure returns (uint8 r) ``` Returns the index of the least significant bit of the number, where the least significant bit is at index 0 and the most significant bit is at index 255 The function satisfies the property: (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0) #### Parameters: | Name | Type | Description | | :--- | :------ | :------------------------------------------------------------------------------- | | `x` | uint256 | the value for which to compute the least significant bit, must be greater than 0 | #### Return Values: | Name | Type | Description | | :--- | :---- | :------------------------------------- | | `r` | uint8 | the index of the least significant bit | # FixedPoint128 Source: https://tech.ramses.xyz/contracts/reference/core/libraries/FixedPoint128 A library for handling binary fixed point numbers, see [https://en.wikipedia.org/wiki/Q\_(number\_format)](https://en.wikipedia.org/wiki/Q_\(number_format\)) # FixedPoint96 Source: https://tech.ramses.xyz/contracts/reference/core/libraries/FixedPoint96 A library for handling binary fixed point numbers, see [https://en.wikipedia.org/wiki/Q\_(number\_format)](https://en.wikipedia.org/wiki/Q_\(number_format\)) Used in SqrtPriceMath.sol # FullMath Source: https://tech.ramses.xyz/contracts/reference/core/libraries/FullMath Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits ## Functions ### mulDiv ```solidity theme={null} function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) ``` Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 Credit to Remco Bloemen under MIT license [https://xn--2-umb.com/21/muldiv](https://xn--2-umb.com/21/muldiv) #### Parameters: | Name | Type | Description | | :------------ | :------ | :--------------- | | `a` | uint256 | The multiplicand | | `b` | uint256 | The multiplier | | `denominator` | uint256 | The divisor | #### Return Values: | Name | Type | Description | | :------- | :------ | :----------------- | | `result` | uint256 | The 256-bit result | ### mulDivRoundingUp ```solidity theme={null} function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) ``` Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 #### Parameters: | Name | Type | Description | | :------------ | :------ | :--------------- | | `a` | uint256 | The multiplicand | | `b` | uint256 | The multiplier | | `denominator` | uint256 | The divisor | #### Return Values: | Name | Type | Description | | :------- | :------ | :----------------- | | `result` | uint256 | The 256-bit result | # Oracle Source: https://tech.ramses.xyz/contracts/reference/core/libraries/Oracle Provides price and liquidity data useful for a wide variety of system designs Instances of stored oracle data, "observations", are collected in the oracle array Every pool is initialized with an oracle array length of 1. Anyone can pay the SSTOREs to increase the maximum length of the oracle array. New slots will be added when the array is fully populated. Observations are overwritten when the full length of the oracle array is populated. The most recent observation is available, independent of the length of the oracle array, by passing 0 to observe() ## Functions ### initialize ```solidity theme={null} function initialize( struct Oracle.Observation[65535] self, uint32 time ) internal returns (uint16 cardinality, uint16 cardinalityNext) ``` Initialize the oracle array by writing the first slot. Called once for the lifecycle of the observations array #### Parameters: | Name | Type | Description | | :----- | :-------------------------------- | :----------------------------------------------------------------------------- | | `self` | struct Oracle.Observation\[65535] | The stored oracle array | | `time` | uint32 | The time of the oracle initialization, via block.timestamp truncated to uint32 | #### Return Values: | Name | Type | Description | | :---------------- | :----- | :------------------------------------------------------------ | | `cardinality` | uint16 | The number of populated elements in the oracle array | | `cardinalityNext` | uint16 | The new length of the oracle array, independent of population | ### write ```solidity theme={null} function write( struct Oracle.Observation[65535] self, uint16 index, uint32 blockTimestamp, int24 tick, uint128 liquidity, uint16 cardinality, uint16 cardinalityNext ) internal returns (uint16 indexUpdated, uint16 cardinalityUpdated) ``` Writes an oracle observation to the array Writable at most once per block. Index represents the most recently written element. cardinality and index must be tracked externally. If the index is at the end of the allowable array length (according to cardinality), and the next cardinality is greater than the current one, cardinality may be increased. This restriction is created to preserve ordering. #### Parameters: | Name | Type | Description | | :---------------- | :-------------------------------- | :-------------------------------------------------------------- | | `self` | struct Oracle.Observation\[65535] | The stored oracle array | | `index` | uint16 | The location of the most recently updated observation | | `blockTimestamp` | uint32 | The timestamp of the new observation | | `tick` | int24 | The active tick at the time of the new observation | | `liquidity` | uint128 | The total in-range liquidity at the time of the new observation | | `cardinality` | uint16 | The number of populated elements in the oracle array | | `cardinalityNext` | uint16 | The new length of the oracle array, independent of population | #### Return Values: | Name | Type | Description | | :------------------- | :----- | :--------------------------------------------------------------------- | | `indexUpdated` | uint16 | The new index of the most recently written element in the oracle array | | `cardinalityUpdated` | uint16 | The new cardinality of the oracle array | ### grow ```solidity theme={null} function grow( struct Oracle.Observation[65535] self, uint16 current, uint16 next ) internal returns (uint16) ``` Prepares the oracle array to store up to `next` observations #### Parameters: | Name | Type | Description | | :-------- | :-------------------------------- | :------------------------------------------------------------------------ | | `self` | struct Oracle.Observation\[65535] | The stored oracle array | | `current` | uint16 | The current next cardinality of the oracle array | | `next` | uint16 | The proposed next cardinality which will be populated in the oracle array | #### Return Values: | Name | Type | Description | | :----- | :----- | :--------------------------------------------------------------- | | `next` | uint16 | The next cardinality which will be populated in the oracle array | ### observe ```solidity theme={null} function observe( struct Oracle.Observation[65535] self, uint32 time, uint32[] secondsAgos, int24 tick, uint16 index, uint128 liquidity, uint16 cardinality ) internal view returns (int56[] tickCumulatives, uint160[] liquidityCumulatives) ``` Returns the accumulator values as of each time seconds ago from the given time in the array of `secondsAgos` Reverts if `secondsAgos` > oldest observation #### Parameters: | Name | Type | Description | | :------------ | :-------------------------------- | :------------------------------------------------------------------------------------ | | `self` | struct Oracle.Observation\[65535] | The stored oracle array | | `time` | uint32 | The current block.timestamp | | `secondsAgos` | uint32\[] | Each amount of time to look back, in seconds, at which point to return an observation | | `tick` | int24 | The current tick | | `index` | uint16 | The location of a given observation within the oracle array | | `liquidity` | uint128 | The current in-range pool liquidity | | `cardinality` | uint16 | The number of populated elements in the oracle array | #### Return Values: | Name | Type | Description | | :--------------------- | :--------- | :------------------------------------------------------------------------------------------ | | `tickCumulatives` | int56\[] | The tick \* time elapsed since the pool was first initialized, as of each `secondsAgo` | | `liquidityCumulatives` | uint160\[] | The liquidity \* time elapsed since the pool was first initialized, as of each `secondsAgo` | # Position Source: https://tech.ramses.xyz/contracts/reference/core/libraries/Position Positions represent an owner address' liquidity between a lower and upper tick boundary Positions store additional state for tracking fees owed to the position ## Functions ### get ```solidity theme={null} function get( mapping(bytes32 => PositionInfo) storage self, address owner, uint256 index, int24 tickLower, int24 tickUpper ) internal view returns (PositionInfo storage position) ``` Returns the Info struct of a position, given an owner and position boundaries #### Parameters: | Name | Type | Description | | :---------- | :--------------------------------------- | :---------------------------------------- | | `self` | mapping(bytes32 => PositionInfo) storage | The mapping containing all user positions | | `owner` | address | The address of the position owner | | `index` | uint256 | The index of the position | | `tickLower` | int24 | The lower tick boundary of the position | | `tickUpper` | int24 | The upper tick boundary of the position | #### Return Values: | Name | Type | Description | | :--------- | :------------------- | :----------------------------------------------------- | | `position` | PositionInfo storage | The position info struct of the given owners' position | ### update ```solidity theme={null} function update( PositionInfo storage self, int128 liquidityDelta, uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128, bytes32 _positionHash, uint256 period, uint160 secondsPerLiquidityPeriodX128 ) internal ``` Credits accumulated fees to a user's position and updates period-based reward accounting #### Parameters: | Name | Type | Description | | :------------------------------ | :------------------- | :---------------------------------------------------------------------------------------------- | | `self` | PositionInfo storage | The individual position to update | | `liquidityDelta` | int128 | The change in pool liquidity as a result of the position update | | `feeGrowthInside0X128` | uint256 | The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries | | `feeGrowthInside1X128` | uint256 | The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries | | `_positionHash` | bytes32 | The hash of the position key (owner, index, tickLower, tickUpper) | | `period` | uint256 | The current period (weekly epoch) | | `secondsPerLiquidityPeriodX128` | uint160 | The seconds per liquidity for the current period inside the position's tick boundaries | ### positionHash ```solidity theme={null} function positionHash( address owner, uint256 index, int24 tickLower, int24 tickUpper ) internal pure returns (bytes32) ``` Returns the hash used to store positions in a mapping: `keccak256(abi.encodePacked(owner, index, tickLower, tickUpper))` #### Parameters: | Name | Type | Description | | :---------- | :------ | :-------------------------------------- | | `owner` | address | The address of the position owner | | `index` | uint256 | The index of the position | | `tickLower` | int24 | The lower tick boundary of the position | | `tickUpper` | int24 | The upper tick boundary of the position | # SafeCast Source: https://tech.ramses.xyz/contracts/reference/core/libraries/SafeCast Contains methods for safely casting between types ## Functions ### toUint160 ```solidity theme={null} function toUint160( uint256 y ) internal pure returns (uint160 z) ``` Cast a uint256 to a uint160, revert on overflow #### Parameters: | Name | Type | Description | | :--- | :------ | :--------------------------- | | `y` | uint256 | The uint256 to be downcasted | #### Return Values: | Name | Type | Description | | :--- | :------ | :--------------------------------------- | | `z` | uint160 | The downcasted integer, now type uint160 | ### toInt128 ```solidity theme={null} function toInt128( int256 y ) internal pure returns (int128 z) ``` Cast a int256 to a int128, revert on overflow or underflow #### Parameters: | Name | Type | Description | | :--- | :----- | :-------------------------- | | `y` | int256 | The int256 to be downcasted | #### Return Values: | Name | Type | Description | | :--- | :----- | :-------------------------------------- | | `z` | int128 | The downcasted integer, now type int128 | ### toInt256 ```solidity theme={null} function toInt256( uint256 y ) internal pure returns (int256 z) ``` Cast a uint256 to a int256, revert on overflow #### Parameters: | Name | Type | Description | | :--- | :------ | :----------------------- | | `y` | uint256 | The uint256 to be casted | #### Return Values: | Name | Type | Description | | :--- | :----- | :---------------------------------- | | `z` | int256 | The casted integer, now type int256 | # SqrtPriceMath Source: https://tech.ramses.xyz/contracts/reference/core/libraries/SqrtPriceMath Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas ## Functions ### getNextSqrtPriceFromAmount0RoundingUp ```solidity theme={null} function getNextSqrtPriceFromAmount0RoundingUp( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) ``` Gets the next sqrt price given a delta of token0 Always rounds up, because in the exact output case (increasing price) we need to move the price at least far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the price less in order to not send too much output. The most precise formula for this is *liquidity \* sqrtPX96 / (liquidity +- amount \* sqrtPX96)*, if this is impossible because of overflow, we calculate *liquidity / (liquidity / sqrtPX96 +- amount)*. #### Parameters: | Name | Type | Description | | :---------- | :------ | :-------------------------------------------------------------- | | `sqrtPX96` | uint160 | The starting price, i.e. before accounting for the token0 delta | | `liquidity` | uint128 | The amount of usable liquidity | | `amount` | uint256 | How much of token0 to add or remove from virtual reserves | | `add` | bool | Whether to add or remove the amount of token0 | #### Return Values: | Type | Description | | :------ | :------------------------------------------------------ | | uint160 | price after adding or removing amount, depending on add | ### getNextSqrtPriceFromAmount1RoundingDown ```solidity theme={null} function getNextSqrtPriceFromAmount1RoundingDown( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) ``` Gets the next sqrt price given a delta of token1 Always rounds down, because in the exact output case (decreasing price) we need to move the price at least far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the price less in order to not send too much output. The formula we compute is within \<1 wei of the lossless version: *sqrtPX96 +- amount / liquidity* #### Parameters: | Name | Type | Description | | :---------- | :------ | :--------------------------------------------------------------- | | `sqrtPX96` | uint160 | The starting price, i.e., before accounting for the token1 delta | | `liquidity` | uint128 | The amount of usable liquidity | | `amount` | uint256 | How much of token1 to add, or remove, from virtual reserves | | `add` | bool | Whether to add, or remove, the amount of token1 | #### Return Values: | Type | Description | | :------ | :-------------------------------------- | | uint160 | price after adding or removing `amount` | ### getNextSqrtPriceFromInput ```solidity theme={null} function getNextSqrtPriceFromInput( uint160 sqrtPX96, uint128 liquidity, uint256 amountIn, bool zeroForOne ) internal pure returns (uint160 sqrtQX96) ``` Gets the next sqrt price given an input amount of token0 or token1 Throws if price or liquidity are 0, or if the next price is out of bounds #### Parameters: | Name | Type | Description | | :----------- | :------ | :--------------------------------------------------------------- | | `sqrtPX96` | uint160 | The starting price, i.e., before accounting for the input amount | | `liquidity` | uint128 | The amount of usable liquidity | | `amountIn` | uint256 | How much of token0, or token1, is being swapped in | | `zeroForOne` | bool | Whether the amount in is token0 or token1 | #### Return Values: | Name | Type | Description | | :--------- | :------ | :---------------------------------------------------------- | | `sqrtQX96` | uint160 | The price after adding the input amount to token0 or token1 | ### getNextSqrtPriceFromOutput ```solidity theme={null} function getNextSqrtPriceFromOutput( uint160 sqrtPX96, uint128 liquidity, uint256 amountOut, bool zeroForOne ) internal pure returns (uint160 sqrtQX96) ``` Gets the next sqrt price given an output amount of token0 or token1 Throws if price or liquidity are 0 or the next price is out of bounds #### Parameters: | Name | Type | Description | | :----------- | :------ | :--------------------------------------------------------- | | `sqrtPX96` | uint160 | The starting price before accounting for the output amount | | `liquidity` | uint128 | The amount of usable liquidity | | `amountOut` | uint256 | How much of token0, or token1, is being swapped out | | `zeroForOne` | bool | Whether the amount out is token0 or token1 | #### Return Values: | Name | Type | Description | | :--------- | :------ | :------------------------------------------------------------- | | `sqrtQX96` | uint160 | The price after removing the output amount of token0 or token1 | ### getAmount0Delta ```solidity theme={null} function getAmount0Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) internal pure returns (uint256 amount0) ``` Gets the amount0 delta between two prices Calculates *liquidity / sqrt(lower) - liquidity / sqrt(upper)*, i.e. *liquidity \* (sqrt(upper) - sqrt(lower)) / (sqrt(upper) \* sqrt(lower))* #### Parameters: | Name | Type | Description | | :-------------- | :------ | :------------------------------------- | | `sqrtRatioAX96` | uint160 | A sqrt price | | `sqrtRatioBX96` | uint160 | Another sqrt price | | `liquidity` | uint128 | The amount of usable liquidity | | `roundUp` | bool | Whether to round the amount up or down | #### Return Values: | Name | Type | Description | | :-------- | :------ | :-------------------------------------------------------------------------------------------- | | `amount0` | uint256 | Amount of token0 required to cover a position of size liquidity between the two passed prices | ### getAmount1Delta ```solidity theme={null} function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) internal pure returns (uint256 amount1) ``` Gets the amount1 delta between two prices Calculates *liquidity \* (sqrt(upper) - sqrt(lower))* #### Parameters: | Name | Type | Description | | :-------------- | :------ | :-------------------------------------- | | `sqrtRatioAX96` | uint160 | A sqrt price | | `sqrtRatioBX96` | uint160 | Another sqrt price | | `liquidity` | uint128 | The amount of usable liquidity | | `roundUp` | bool | Whether to round the amount up, or down | #### Return Values: | Name | Type | Description | | :-------- | :------ | :-------------------------------------------------------------------------------------------- | | `amount1` | uint256 | Amount of token1 required to cover a position of size liquidity between the two passed prices | ### getAmount0Delta ```solidity theme={null} function getAmount0Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, int128 liquidity ) internal pure returns (int256 amount0) ``` Helper that gets signed token0 delta #### Parameters: | Name | Type | Description | | :-------------- | :------ | :------------------------------------------------------------- | | `sqrtRatioAX96` | uint160 | A sqrt price | | `sqrtRatioBX96` | uint160 | Another sqrt price | | `liquidity` | int128 | The change in liquidity for which to compute the amount0 delta | #### Return Values: | Name | Type | Description | | :-------- | :----- | :--------------------------------------------------------------------------------- | | `amount0` | int256 | Amount of token0 corresponding to the passed liquidityDelta between the two prices | ### getAmount1Delta ```solidity theme={null} function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, int128 liquidity ) internal pure returns (int256 amount1) ``` Helper that gets signed token1 delta #### Parameters: | Name | Type | Description | | :-------------- | :------ | :------------------------------------------------------------- | | `sqrtRatioAX96` | uint160 | A sqrt price | | `sqrtRatioBX96` | uint160 | Another sqrt price | | `liquidity` | int128 | The change in liquidity for which to compute the amount1 delta | #### Return Values: | Name | Type | Description | | :-------- | :----- | :--------------------------------------------------------------------------------- | | `amount1` | int256 | Amount of token1 corresponding to the passed liquidityDelta between the two prices | # SwapMath Source: https://tech.ramses.xyz/contracts/reference/core/libraries/SwapMath Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick. ## Functions ### computeSwapStep ```solidity theme={null} function computeSwapStep( uint160 sqrtRatioCurrentX96, uint160 sqrtRatioTargetX96, uint128 liquidity, int256 amountRemaining, uint24 feePips ) internal pure returns (uint160 sqrtRatioNextX96, uint256 amountIn, uint256 amountOut, uint256 feeAmount) ``` Computes the result of swapping some amount in, or amount out, given the parameters of the swap The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive #### Parameters: | Name | Type | Description | | :-------------------- | :------ | :---------------------------------------------------------------------------------- | | `sqrtRatioCurrentX96` | uint160 | The current sqrt price of the pool | | `sqrtRatioTargetX96` | uint160 | The price that cannot be exceeded, from which the direction of the swap is inferred | | `liquidity` | uint128 | The usable liquidity | | `amountRemaining` | int256 | How much input or output amount is remaining to be swapped in/out | | `feePips` | uint24 | The fee taken from the input amount, expressed in hundredths of a bip | #### Return Values: | Name | Type | Description | | :----------------- | :------ | :------------------------------------------------------------------------------------------ | | `sqrtRatioNextX96` | uint160 | The price after swapping the amount in/out, not to exceed the price target | | `amountIn` | uint256 | The amount to be swapped in, of either token0 or token1, based on the direction of the swap | | `amountOut` | uint256 | The amount to be received, of either token0 or token1, based on the direction of the swap | | `feeAmount` | uint256 | The amount of input that will be taken as a fee | # Tick Source: https://tech.ramses.xyz/contracts/reference/core/libraries/Tick Contains functions for managing tick processes and relevant calculations ## Functions ### tickSpacingToMaxLiquidityPerTick ```solidity theme={null} function tickSpacingToMaxLiquidityPerTick( int24 tickSpacing ) internal pure returns (uint128) ``` Derives max liquidity per tick from given tick spacing Executed within the pool constructor #### Parameters: | Name | Type | Description | | :------------ | :---- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tickSpacing` | int24 | The amount of required tick separation, realized in multiples of `tickSpacing` e.g., a tickSpacing of 3 requires ticks to be initialized every 3rd tick i.e., ..., -6, -3, 0, 3, 6, ... | #### Return Values: | Type | Description | | :------ | :--------------------- | | uint128 | max liquidity per tick | ### getFeeGrowthInside ```solidity theme={null} function getFeeGrowthInside( mapping(int24 => struct Tick.Info) self, int24 tickLower, int24 tickUpper, int24 tickCurrent, uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128 ) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) ``` Retrieves fee growth data #### Parameters: | Name | Type | Description | | :--------------------- | :--------------------------------- | :---------------------------------------------------------------- | | `self` | mapping(int24 => struct Tick.Info) | The mapping containing all tick information for initialized ticks | | `tickLower` | int24 | The lower tick boundary of the position | | `tickUpper` | int24 | The upper tick boundary of the position | | `tickCurrent` | int24 | The current tick | | `feeGrowthGlobal0X128` | uint256 | The all-time global fee growth, per unit of liquidity, in token0 | | `feeGrowthGlobal1X128` | uint256 | The all-time global fee growth, per unit of liquidity, in token1 | #### Return Values: | Name | Type | Description | | :--------------------- | :------ | :---------------------------------------------------------------------------------------------- | | `feeGrowthInside0X128` | uint256 | The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries | | `feeGrowthInside1X128` | uint256 | The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries | ### update ```solidity theme={null} function update( mapping(int24 => struct Tick.Info) self, int24 tick, int24 tickCurrent, int128 liquidityDelta, uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128, bool upper, uint128 maxLiquidity ) internal returns (bool flipped) ``` Updates a tick and returns true if the tick was flipped from initialized to uninitialized, or vice versa #### Parameters: | Name | Type | Description | | :--------------------- | :--------------------------------- | :--------------------------------------------------------------------------------------------------------- | | `self` | mapping(int24 => struct Tick.Info) | The mapping containing all tick information for initialized ticks | | `tick` | int24 | The tick that will be updated | | `tickCurrent` | int24 | The current tick | | `liquidityDelta` | int128 | A new amount of liquidity to be added (subtracted) when tick is crossed from left to right (right to left) | | `feeGrowthGlobal0X128` | uint256 | The all-time global fee growth, per unit of liquidity, in token0 | | `feeGrowthGlobal1X128` | uint256 | The all-time global fee growth, per unit of liquidity, in token1 | | `upper` | bool | true for updating a position's upper tick, or false for updating a position's lower tick | | `maxLiquidity` | uint128 | The maximum liquidity allocation for a single tick | #### Return Values: | Name | Type | Description | | :-------- | :--- | :---------------------------------------------------------------------------- | | `flipped` | bool | Whether the tick was flipped from initialized to uninitialized, or vice versa | ### clear ```solidity theme={null} function clear( mapping(int24 => struct Tick.Info) self, int24 tick ) internal ``` Clears tick data #### Parameters: | Name | Type | Description | | :----- | :--------------------------------- | :---------------------------------------------------------------------------- | | `self` | mapping(int24 => struct Tick.Info) | The mapping containing all initialized tick information for initialized ticks | | `tick` | int24 | The tick that will be cleared | ### cross ```solidity theme={null} function cross( mapping(int24 => struct Tick.Info) self, int24 tick, uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128 ) internal returns (int128 liquidityNet) ``` Transitions to next tick as needed by price movement #### Parameters: | Name | Type | Description | | :--------------------- | :--------------------------------- | :---------------------------------------------------------------- | | `self` | mapping(int24 => struct Tick.Info) | The mapping containing all tick information for initialized ticks | | `tick` | int24 | The destination tick of the transition | | `feeGrowthGlobal0X128` | uint256 | The all-time global fee growth, per unit of liquidity, in token0 | | `feeGrowthGlobal1X128` | uint256 | The all-time global fee growth, per unit of liquidity, in token1 | #### Return Values: | Name | Type | Description | | :------------- | :----- | :------------------------------------------------------------------------------------------------- | | `liquidityNet` | int128 | The amount of liquidity added (subtracted) when tick is crossed from left to right (right to left) | # TickBitmap Source: https://tech.ramses.xyz/contracts/reference/core/libraries/TickBitmap Stores a packed mapping of tick index to its initialized state The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word. ## Functions ### flipTick ```solidity theme={null} function flipTick( mapping(int16 => uint256) self, int24 tick, int24 tickSpacing ) internal ``` Flips the initialized state for a given tick from false to true, or vice versa #### Parameters: | Name | Type | Description | | :------------ | :------------------------ | :------------------------------------ | | `self` | mapping(int16 => uint256) | The mapping in which to flip the tick | | `tick` | int24 | The tick to flip | | `tickSpacing` | int24 | The spacing between usable ticks | ### nextInitializedTickWithinOneWord ```solidity theme={null} function nextInitializedTickWithinOneWord( mapping(int16 => uint256) self, int24 tick, int24 tickSpacing, bool lte ) internal view returns (int24 next, bool initialized) ``` Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either to the left (less than or equal to) or right (greater than) of the given tick #### Parameters: | Name | Type | Description | | :------------ | :------------------------ | :---------------------------------------------------------------------------------------------------- | | `self` | mapping(int16 => uint256) | The mapping in which to compute the next initialized tick | | `tick` | int24 | The starting tick | | `tickSpacing` | int24 | The spacing between usable ticks | | `lte` | bool | Whether to search for the next initialized tick to the left (less than or equal to the starting tick) | #### Return Values: | Name | Type | Description | | :------------ | :---- | :----------------------------------------------------------------------------------------- | | `next` | int24 | The next initialized or uninitialized tick up to 256 ticks away from the current tick | | `initialized` | bool | Whether the next tick is initialized, as the function only searches within up to 256 ticks | # TickMath Source: https://tech.ramses.xyz/contracts/reference/core/libraries/TickMath Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports prices between 2\*\*-128 and 2\*\*128 ## Functions ### getSqrtRatioAtTick ```solidity theme={null} function getSqrtRatioAtTick( int24 tick ) internal pure returns (uint160 sqrtPriceX96) ``` Calculates sqrt(1.0001^tick) \* 2^96 Throws if |tick| > max tick #### Parameters: | Name | Type | Description | | :----- | :---- | :----------------------------------- | | `tick` | int24 | The input tick for the above formula | #### Return Values: | Name | Type | Description | | :------------- | :------ | :----------------------------------------------------------------------------------------------- | | `sqrtPriceX96` | uint160 | A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) | at the given tick ### getTickAtSqrtRatio ```solidity theme={null} function getTickAtSqrtRatio( uint160 sqrtPriceX96 ) internal pure returns (int24 tick) ``` Calculates the greatest tick value such that getRatioAtTick(tick) \<= ratio Throws in case sqrtPriceX96 \< MIN\_SQRT\_RATIO, as MIN\_SQRT\_RATIO is the lowest value getRatioAtTick may ever return. #### Parameters: | Name | Type | Description | | :------------- | :------ | :------------------------------------------------------- | | `sqrtPriceX96` | uint160 | The sqrt ratio for which to compute the tick as a Q64.96 | #### Return Values: | Name | Type | Description | | :----- | :---- | :----------------------------------------------------------------------------- | | `tick` | int24 | The greatest tick for which the ratio is less than or equal to the input ratio | # TransferHelper Source: https://tech.ramses.xyz/contracts/reference/core/libraries/TransferHelper Contains helper methods for interacting with ERC20 tokens that do not consistently return true/false ## Functions ### safeTransfer ```solidity theme={null} function safeTransfer( address token, address to, uint256 value ) internal ``` Transfers tokens from msg.sender to a recipient Calls transfer on token contract, errors with TF if transfer fails #### Parameters: | Name | Type | Description | | :------ | :------ | :---------------------------------------------------------- | | `token` | address | The contract address of the token which will be transferred | | `to` | address | The recipient of the transfer | | `value` | uint256 | The value of the transfer | # UnsafeMath Source: https://tech.ramses.xyz/contracts/reference/core/libraries/UnsafeMath Contains methods that perform common math functions but do not do any overflow or underflow checks ## Functions ### divRoundingUp ```solidity theme={null} function divRoundingUp( uint256 x, uint256 y ) internal pure returns (uint256 z) ``` Returns ceil(x / y) panics if y == 0 #### Parameters: | Name | Type | Description | | :--- | :------ | :----------- | | `x` | uint256 | The dividend | | `y` | uint256 | The divisor | #### Return Values: | Name | Type | Description | | :--- | :------ | :------------------------ | | `z` | uint256 | The quotient, ceil(x / y) | # Deployment Addresses Source: https://tech.ramses.xyz/contracts/reference/deployments/deployments # Ramses Contract Deployments The Ramses Protocol is adapted and utilized by many protocols throughout different networks. Please do not assume contracts are deployed to the same addresses across chains, and be extremely careful to confirm addresses before using a contract. Below are official and authorized instances of Ramses: * [`Shadow`](https://shadow.so) — Sonic * [`Pharaoh`](https://phar.gg) — Avalanche C-Chain * [`Ramses`](https://ramses.xyz) — HyperEVM, Arbitrum, Robinhood Chain, and Polygon (multichain) * [`Etherex`](https://etherex.finance) — Linea # Ramses Pool Deployments Each Ramses concentrated-liquidity pool is a unique `RamsesV3Pool` deployment. Confirm both the address and verified source on the relevant chain explorer. DLMM pools are separate deterministic `DLMMPool` clones discovered through `DLMMFactory`. A token pair may have multiple DLMM pools with different bin steps. ## Robinhood DLMM Robinhood Chain uses chain ID `4663`. At the [block 22,674,244 snapshot](/contracts/reference/dlmm/deployments), its DLMM deployment was fee-only and was not connected to `Voter`. | Contract | Address | | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | Factory | [`0xdcD5F77697914E27f56FD263EF82923C8524AbAc`](https://robinhoodchain.blockscout.com/address/0xdcD5F77697914E27f56FD263EF82923C8524AbAc) | | Fee Collector | [`0xcc543a9EDBa25cEB2922b165047b6A7bE861C55b`](https://robinhoodchain.blockscout.com/address/0xcc543a9EDBa25cEB2922b165047b6A7bE861C55b) | | Router | [`0xd0019e86edB35E1fedaaB03aED5c3c60f115d28b`](https://robinhoodchain.blockscout.com/address/0xd0019e86edB35E1fedaaB03aED5c3c60f115d28b) | | Quoter | [`0xb722efaAbe807FAeA16068f595EaA9aa1a62CECD`](https://robinhoodchain.blockscout.com/address/0xb722efaAbe807FAeA16068f595EaA9aa1a62CECD) | | Sarcophagus | [`0x712567e71a93Fb111510A790cAf3469677aAba3e`](https://robinhoodchain.blockscout.com/address/0x712567e71a93Fb111510A790cAf3469677aAba3e) | See [Robinhood DLMM Deployments](/contracts/reference/dlmm/deployments) for live wiring, quote assets, presets, and verification requirements. See the [Sarcophagus reference and searcher guide](/contracts/reference/sarcophagus) for the live claim parameters, contract interface, execution flow, and integration requirements. # Robinhood DLMM Deployments Source: https://tech.ramses.xyz/contracts/reference/dlmm/deployments Live Robinhood Chain addresses, presets, wiring, and integration boundaries. # Robinhood DLMM Deployments Contract addresses and mutable configuration must be verified on-chain before every production integration. This page records a live read taken at Robinhood block `22,674,244` on July 29, 2026. ## Network | Field | Value | | ------------ | ------------------------------------------------------------------- | | Network | Robinhood Chain | | Chain ID | `4663` | | Native asset | ETH | | Public RPC | `https://rpc.mainnet.chain.robinhood.com` | | Explorer | [Robinhood Chain Blockscout](https://robinhoodchain.blockscout.com) | ## Contracts | Contract | Address | | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- | | AccessHub | [`0x83341F891f898cb5E0cacC8a70501BBa83d9CecF`](https://robinhoodchain.blockscout.com/address/0x83341F891f898cb5E0cacC8a70501BBa83d9CecF) | | DLMM Factory | [`0xdcD5F77697914E27f56FD263EF82923C8524AbAc`](https://robinhoodchain.blockscout.com/address/0xdcD5F77697914E27f56FD263EF82923C8524AbAc) | | DLMM Pool Implementation | [`0x4e857A78bcE4FcF41677f21Bfaf3e77890d5042b`](https://robinhoodchain.blockscout.com/address/0x4e857A78bcE4FcF41677f21Bfaf3e77890d5042b) | | DLMM Fee Collector | [`0xcc543a9EDBa25cEB2922b165047b6A7bE861C55b`](https://robinhoodchain.blockscout.com/address/0xcc543a9EDBa25cEB2922b165047b6A7bE861C55b) | | DLMM Router | [`0xd0019e86edB35E1fedaaB03aED5c3c60f115d28b`](https://robinhoodchain.blockscout.com/address/0xd0019e86edB35E1fedaaB03aED5c3c60f115d28b) | | DLMM Quoter | [`0xb722efaAbe807FAeA16068f595EaA9aa1a62CECD`](https://robinhoodchain.blockscout.com/address/0xb722efaAbe807FAeA16068f595EaA9aa1a62CECD) | Discover individual pool addresses through the factory. Do not assume one pool per token pair because separate bin steps create separate pools. ## Quote assets The live factory quote-asset whitelist contains: | Asset | Address | | ----- | ---------------------------------------------------------------------------------------------------------------------------------------- | | WETH | [`0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73`](https://robinhoodchain.blockscout.com/address/0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73) | | USDG | [`0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168`](https://robinhoodchain.blockscout.com/address/0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168) | For permissionless creation, the desired `tokenY` must already be on this whitelist. ## Live wiring | Read | Value | Meaning | | -------------------------- | ------------------------- | ------------------------------------------------------------------------------------------ | | `factory.owner()` | AccessHub | AccessHub controls factory-owner operations | | `factory.feeCollector()` | DLMM Fee Collector | Protocol portions are collected there | | `factory.voter()` | Zero address | No live DLMM voter/rewarder integration | | `feeCollector.accessHub()` | AccessHub | Collector configuration is AccessHub-gated | | `feeCollector.voter()` | Zero address | Collected protocol fees are not routed to voters | | `feeCollector.treasury()` | Ramses Safe | The current fee-only protocol portion is sent to treasury | | `accessHub.voter()` | Voter | AccessHub is wired to the wider Ramses voting system | | `voter.dlmmFactory()` | DLMM Factory | The Voter recognizes this factory, although the factory is not yet wired back to the Voter | | `factory.getAllBinSteps()` | `1, 2, 5, 10, 15, 20, 25` | Available presets | Sampled live pools reported: * `protocolShare = 500`, or 5% of swap fees * No hook parameters * LP-retained fees remain in bin reserves and compound into LP share value The current open presets and sampled pools implement the fee-only split: 95% of swap fees remain for LPs and 5% is routed to protocol treasury. ## Administration and custody boundaries | Component | Live value | | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- | | AccessHub implementation | [`0x9DC2d94B3979f85d875557f212461685eaA23873`](https://robinhoodchain.blockscout.com/address/0x9DC2d94B3979f85d875557f212461685eaA23873) | | Voter | [`0x30032D41868906f0376eC4D87B3D3Ac4064e7A97`](https://robinhoodchain.blockscout.com/address/0x30032D41868906f0376eC4D87B3D3Ac4064e7A97) | | Treasury and Ramses Safe | [`0x20D630cF1f5628285BfB91DfaC8C89eB9087BE1A`](https://robinhoodchain.blockscout.com/address/0x20D630cF1f5628285BfB91DfaC8C89eB9087BE1A) | | Timelock | [`0xE41c07CcD69A0f19A2186f3Ad30409BD585436CE`](https://robinhoodchain.blockscout.com/address/0xE41c07CcD69A0f19A2186f3Ad30409BD585436CE) | | ProxyAdmin | [`0xA203A21dCCB461E415DaA342E8e635B6CeE0cCb3`](https://robinhoodchain.blockscout.com/address/0xA203A21dCCB461E415DaA342E8e635B6CeE0cCb3) | At the verification block, the Safe was 1-of-1 and its sole owner was the same EOA that directly held the `PROTOCOL_OPERATOR` and `SWAP_FEE_SETTER` roles. The timelock's minimum delay was zero, and the ProxyAdmin was Safe-owned. This is an early-stage operating model with immediate administrative controls, not a fully delayed governance configuration. Ramses intends to move these controls toward timelocked administration over time. These controls can change economic configuration, hooks, presets, routing status, future pool implementation, and rewarder settings. They do not expose a general administrator withdrawal function for user liquidity: a bin position can be burned only by its holder or an operator that holder approved. Existing pool clones are immutable; changing the factory's implementation address affects only future pools. This custody boundary does not remove the execution and economic risks created by privileged configuration. ## Live open presets All listed presets were open at the verification block. Values are mutable. | Bin step | Base factor | Base fee | Filter | Decay | Reduction | Variable control | Max accumulator | Protocol share | | -------: | ----------: | -------: | -----: | ----: | --------: | ---------------: | --------------: | -------------: | | 1 | 20,000 | 2 bps | 10s | 120s | 50% | 2,000,000 | 100,000 | 5% | | 2 | 15,000 | 3 bps | 10s | 120s | 50% | 500,000 | 250,000 | 5% | | 5 | 8,000 | 4 bps | 30s | 600s | 50% | 120,000 | 300,000 | 5% | | 10 | 10,000 | 10 bps | 30s | 600s | 50% | 40,000 | 350,000 | 5% | | 15 | 10,000 | 15 bps | 30s | 600s | 50% | 30,000 | 350,000 | 5% | | 20 | 10,000 | 20 bps | 30s | 600s | 50% | 20,000 | 350,000 | 5% | | 25 | 10,000 | 25 bps | 30s | 600s | 50% | 15,000 | 350,000 | 5% | The base fee is only the static floor. The on-chain variable fee may increase the trader-paid fee as swaps move across bins. ## Factory constant versus live policy The deployed factory exposes: ```text theme={null} defaultProtocolShare() = 2,500 gaugedProtocolShare() = 10,000 ``` Its current open presets and sampled fee-only pools use `500`, not `2,500`. Read the pool's `protocolShare` from `getStaticFeeParameters()`. The factory's generic default constant, the current creation preset, and an individual pool's mutable value are separate pieces of state. The Ramses gauged architecture sets a live rewarder's pool to `10,000`, routing 100% of swap fees into `DLMMFeeCollector` while RAM emissions reward eligible LP bins. Voters receive the collector amount remaining after its independently mutable `treasuryFees` skim; the 100%-to-voters policy requires that skim to be zero. This architecture is not currently connected on Robinhood because `factory.voter()` is zero and no rewarder factory is listed for this deployment. ## Production checks Before integrating: 1. Assert chain ID `4663`. 2. Read the factory owner, fee collector, voter, presets, and quote assets. 3. Discover and validate the pool with `factory.isPool(pool)`. 4. Read pool token order, active ID, static fee parameters, and hook parameters. 5. Quote against live bin reserves. 6. Simulate with the current router before sending. ## Additional resources * [DLMM & Liquidity Bins](/concepts/protocol/dlmm) * [DLMM Integration Guide](/contracts/guides/dlmm/integration) * [DLMM Contract Architecture](/contracts/reference/dlmm/overview) * [General Contract Addresses](https://docs.ramses.xyz/pages/contract-addresses) # DLMM Contract Architecture Source: https://tech.ramses.xyz/contracts/reference/dlmm/overview Core pools, periphery, fee routing, optional rewards, events, and privileged controls. # DLMM Contract Architecture Ramses DLMM is an LFJ v2.2-style Liquidity Book implementation integrated with Ramses fee routing and optional voter-directed rewards. ## Contract map | Contract | Responsibility | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `DLMMFactory` | Deploys deterministic pools, stores fee presets and quote assets, manages routing state, pool parameters, protocol share, and hooks | | `DLMMPool` | Holds reserves, executes swaps, tracks bins and active ID, accrues fees, stores oracle state, and issues per-bin LP shares | | `DLMMToken` | ERC1155-like per-bin share accounting embedded in each pool | | `DLMMRouter` | User-facing pool creation, liquidity, swap, native-asset, and slippage/deadline flows | | `DLMMQuoter` | Searches registered, non-ignored bin steps for exact-input and exact-output routes | | `DLMMFeeCollector` | Pulls the protocol share from pools and sends it to treasury or a live pool `FeeDistributor` | | `DLMMBaseHooks` | Base validation and callback surface for pool hooks | | `DLMMRewarder` | Optional RAM emission hook with rewarded-bin and anti-JIT accounting | | `DLMMRewarderFactory` | Deploys beacon-proxy rewarders and links pool-to-rewarder state | ```text theme={null} DLMMFactory ──creates──> DLMMPool / DLMMToken │ │ ├──used by──> DLMMRouter│<──quotes── DLMMQuoter │ │ └──fee recipient──> DLMMFeeCollector │ ├──ungauged/dead──> Treasury └──alive rewarder──> FeeDistributor Voter ──RAM emissions──> DLMMRewarder ──hooked to──> DLMMPool ``` ## Factory ### Pool identity There is at most one pool for an unordered token pair and bin step. The factory sorts tokens for storage, but initialization preserves the supplied `tokenX` and `tokenY` order. Key reads: ```solidity theme={null} getLBPairInformation(tokenX, tokenY, binStep) getAllLBPairs(tokenX, tokenY) getLBPairAtIndex(index) getNumberOfLBPairs() isPool(pool) getAllBinSteps() getOpenBinSteps() getPreset(binStep) getLBPairImplementation() ``` Pools are deterministic immutable clones. Updating `getLBPairImplementation()` changes the implementation used for future pools; it does not upgrade an existing clone. ### Creation constraints `createLBPair(tokenX, tokenY, activeId, binStep)` requires: * An existing preset for `binStep` * An open preset unless the caller is the factory owner * A whitelisted `tokenY` quote asset * Distinct, non-zero tokens * No existing pool for that token pair and bin step * A valid active-bin price The `LBPairCreated` event is the canonical discovery event. ### Mutable configuration The factory owner controls: * Preset parameters and whether a preset is open * Fee parameters on an existing pool * Pool protocol share * Quote-asset membership * Routing-ignore state * Hook installation and removal through the hook-manager role * Fee recipient and flash-loan fee * Forced volatility decay * The implementation used for future pools The owner or configured `Voter` may change an existing pool's `protocolShare`. ## Pool ### Core reads ```solidity theme={null} getTokenX() getTokenY() getBinStep() getReserves() getActiveId() getBin(id) getNextNonEmptyBin(swapForY, id) getProtocolFees() getStaticFeeParameters() getVariableFeeParameters() getLBHooksParameters() getPriceFromId(id) getIdFromPrice(price) getSwapIn(amountOut, swapForY) getSwapOut(amountIn, swapForY) ``` `getReserves()` reports pool reserves net of accrued protocol fees. `getBin(id)` reports the token reserves assigned to one bin. ### State-changing entrypoints ```solidity theme={null} swap(swapForY, to) mint(to, liquidityConfigs, refundTo) burn(from, to, ids, amountsToBurn) flashLoan(receiver, amounts, data) collectProtocolFees() increaseOracleLength(newLength) ``` These core functions are low-level. `swap()` relies on pre-transferred input and `mint()` expects packed liquidity configurations. Public integrations should normally use `DLMMRouter`. ### LP share behavior Each bin ID has independent `balanceOf()` and `totalSupply()` accounting. Initial shares are derived from the square root of bin liquidity; later deposits mint proportionally to the bin's existing reserves and supply. `DLMMToken` is ERC1155-like, but: * It does not call receiver hooks * It has no URI surface * Operator approval for all bin IDs uses `approveForAll()` * A linked rewarder hook can disable batch transfers Burning requires the holder or an approved operator. The reviewed pool contracts do not expose an administrator function that withdraws arbitrary user LP principal. ## Router and quoter `DLMMRouter` is the intended safety boundary for end-user transactions. It adds: * Deadlines * Token and active-ID slippage checks * ERC20 and native-asset handling * Refund routing * A caller-only LP recipient check on public add-liquidity functions * Exact-input and exact-output swaps * Fee-on-transfer swap variants * Batched per-bin liquidity operations The router's current executable path version is `V2_1`. Its `V1` and `V2` enum members are compatibility placeholders. `DLMMQuoter` evaluates every registered, non-ignored bin-step candidate for a hop and returns the best complete fill. It catches failing candidates, so callers must still verify that every selected pair and amount is non-zero. ## Fees Pool static parameters are: ```solidity theme={null} baseFactor filterPeriod decayPeriod reductionFactor variableFeeControl protocolShare maxVolatilityAccumulator ``` The base fee scales linearly with `baseFactor × binStep`. The variable fee scales quadratically with `volatilityAccumulator × binStep` and is capped. The maximum total swap fee is `10%`. `protocolShare` is measured out of `10,000` and applies to the swap fee, not to trade notional: ```text theme={null} protocol fee amount = total swap fee × protocolShare / 10,000 ``` The remainder stays in bin reserves and compounds into LP share value. `DLMMFeeCollector.collectProtocolFees(pool)`: 1. Pulls the pool's accrued protocol fees 2. Sends them to treasury if no live rewarder exists 3. Otherwise applies its configured treasury skim and notifies the rewarder's `FeeDistributor` Ramses gauged policy targets a zero skim so 100% of collected pool fees reach voters. Rewarder creation does not enforce that collector setting, and it remains independently configurable, so integrations must verify live state. Protocol-fee collection intentionally leaves one smallest unit of each non-zero token in the pool. Flash-loan fees are entirely protocol fees. The factory owner can set the flash-loan fee up to `10%`. ## Oracle Each pool contains an oracle of cumulative active ID, volatility, and bins crossed. It remains inactive until `increaseOracleLength()` allocates storage. ```solidity theme={null} getOracleParameters() getOracleSampleAt(lookupTimestamp) increaseOracleLength(newLength) ``` Samples have a 120-second maximum lifetime. Integrations must inspect oracle parameters before assuming historical observations are available. ## Hooks and rewards Hooks can execute before or after swaps, flash loans, mints, burns, and batch transfers. Hook calls are synchronous; an enabled hook that reverts or returns an invalid selector can block the corresponding pool operation until governance replaces or removes it. `DLMMRewarder` enables Ramses voter-directed emissions: * `Voter` treats the rewarder as the pool's emission target * RAM streams over a configurable, upper-exclusive range of at most 11 bins * The default `(0, 1)` range rewards only the active bin * Reward weight is calculated from bin liquidity at the active-bin price * Each bin then distributes pro rata to its share holders * Owners claim only for their own address Anti-JIT controls can forfeit newly accrued rewards for recently modified positions. Burns remain possible and principal is not forfeited. Rewarders are beacon proxies. Updating the factory's rewarder implementation can change all existing rewarders. Removing or replacing a rewarder hook makes the old rewarder unlinked; its pending-reward view returns zero and claims revert until linkage is restored. At the [Robinhood snapshot at block 22,674,244](/contracts/reference/dlmm/deployments), the factory reported `voter() == address(0)` and sampled pools had no hook. Do not expose RAM claims or gauged fee behavior unless a newer live read confirms that state changed. ## Voter and AccessHub integration When configured, `Voter` reuses its existing pool/gauge mappings: | Mapping | DLMM value | | ---------------------------------- | ---------------------------------------- | | `gaugeForPool[pool]` | `DLMMRewarder` | | `poolForGauge[rewarder]` | `DLMMPool` | | `feeDistributorForGauge[rewarder]` | Pool `FeeDistributor` | | `isAlive[rewarder]` | Controls emissions and voter fee routing | `AccessHub` exposes dedicated DLMM operations for pool and rewarder creation, fee changes, hook managers, reward ranges, fee collector settings, and factory ownership. Regular users call an open factory preset directly; protocol operators use `createDLMMPool()`. ## Events ### Factory ```solidity theme={null} LBPairCreated PresetSet PresetOpenStateChanged LBPairIgnoredStateChanged QuoteAssetAdded QuoteAssetRemoved DLMMVoterSet ``` ### Pool ```solidity theme={null} Swap DepositedToBins WithdrawnFromBins TransferBatch CompositionFees CollectedProtocolFees StaticFeeParametersSet HooksParametersSet FlashLoan OracleLengthIncreased ForcedDecay ``` ### Rewards and fee routing ```solidity theme={null} DLMMRewarderCreated NotifyReward ClaimRewards FeesCollected ``` ## Integration invariants * `binStep = 1` means one basis point, or `0.01%` * Prices are unsigned 128.128 fixed-point values * `destinationBin = liveActiveId + deltaId`; `activeIdDesired` is the slippage anchor * `refundTo` receives unused mint inputs * Public router adds require `to == msg.sender` * Router paths execute `Version.V2_1` * `protocolShare` is basis points of swap fees * Pool settings and hook state are mutable * Current deployment state takes precedence over generic factory constants or documentation labels ## Additional resources * [DLMM & Liquidity Bins](/concepts/protocol/dlmm) * [DLMM Integration Guide](/contracts/guides/dlmm/integration) * [Robinhood DLMM Deployments](/contracts/reference/dlmm/deployments) # Error Codes Source: https://tech.ramses.xyz/contracts/reference/error-codes # Custom Errors (Errors.sol) The protocol uses a centralized `Errors` library for custom error definitions across all contracts. ## Voter Errors | Error | Parameters | Description | | ---------------------- | ------------------------------- | ---------------------------------------------------- | | `ACTIVE_GAUGE` | `address gauge` | Attempting to interact with an already active gauge | | `GAUGE_INACTIVE` | `address gauge` | Attempting to interact with an inactive gauge | | `ALREADY_WHITELISTED` | `address token` | Attempting to whitelist an already whitelisted token | | `NOT_AUTHORIZED` | `address caller` | Caller is not authorized to perform the action | | `NOT_WHITELISTED` | `address token` | Token is not whitelisted | | `BOTH_NOT_WHITELISTED` | — | Both tokens in a pair are not whitelisted | | `NOT_POOL` | `address pool` | Address is not a valid pool | | `NOT_INIT` | — | Contract is not initialized | | `LENGTH_MISMATCH` | — | Array lengths don't match | | `NO_GAUGE` | `address pool` | Pool doesn't have an associated gauge | | `ALREADY_DISTRIBUTED` | `address gauge, uint256 period` | Rewards are already distributed for the period | | `ZERO_VOTE` | `address pool` | Attempting to vote with zero amount | | `RATIO_TOO_HIGH` | `uint256 _xRatio` | Ratio exceeds maximum allowed | | `VOTE_UNSUCCESSFUL` | — | Vote operation failed | ## Gauge V3 Errors | Error | Parameters | Description | | ------------------------ | ---------------- | --------------------------------------------------------------------- | | `GAUGE_EXISTS` | `address pool` | Pool already has a gauge | | `NOT_VOTER` | `address caller` | Caller is not the voter contract | | `NOT_GT_ZERO` | `uint256 amt` | Amount is not greater than zero | | `CANT_CLAIM_FUTURE` | — | Attempting to claim future rewards | | `CANT_REWARD_PAST` | — | Attempting to reward past periods | | `NEED_TEAM_TO_UPDATE` | — | Gauge can't determine if using `secondsInRange` from the pool is safe | | `NOT_AUTHORIZED_CLAIMER` | `address owner` | Owner is not an authorized NFP manager | ## Gauge Errors | Error | Parameters | Description | | ---------------------------- | ----------------------------------- | -------------------------------- | | `ZERO_AMOUNT` | — | Amount is zero | | `CANT_NOTIFY_STAKE` | — | Stake notification failed | | `REWARD_TOO_HIGH` | — | Reward amount is too high | | `NOT_GREATER_THAN_REMAINING` | `uint256 amount, uint256 remaining` | Amount exceeds remaining balance | | `TOKEN_ERROR` | `address token` | Token operation failed | | `NOT_NFP_MANAGER` | `address nfpManager` | Address is not an NfpManager | ## Fee Distributor Errors | Error | Parameters | Description | | ------------------------------ | --------------------- | ---------------------------------------------------------------- | | `NOT_FINALIZED` | `uint256 period` | Period is not finalized | | `NOT_FEE_DISTRIBUTOR` | `address destination` | Redirect destination is not a FeeDistributor | | `DIFFERENT_DESTINATION_TOKENS` | — | Redirect destination's pool/pair has completely different tokens | ## Pair Errors | Error | Parameters | Description | | ------------------------------- | ---------- | ----------------------------- | | `UNSTABLE_RATIO` | — | Ratio is unstable | | `SAFE_TRANSFER_FAILED` | — | Safe transfer failed | | `OVERFLOW` | — | Arithmetic overflow | | `SKIM_DISABLED` | — | Skim operation is disabled | | `INSUFFICIENT_LIQUIDITY_MINTED` | — | Insufficient liquidity minted | | `INSUFFICIENT_LIQUIDITY_BURNED` | — | Insufficient liquidity burned | | `INSUFFICIENT_OUTPUT_AMOUNT` | — | Output amount is insufficient | | `INSUFFICIENT_INPUT_AMOUNT` | — | Input amount is insufficient | | `INSUFFICIENT_LIQUIDITY` | — | Insufficient liquidity | | `INVALID_TRANSFER` | — | Invalid transfer | | `K` | — | K invariant violation in AMM | ## Pair Factory Errors | Error | Parameters | Description | | -------------------- | ---------- | --------------------------- | | `FEE_TOO_HIGH` | — | Fee is too high | | `ZERO_FEE` | — | Fee is zero | | `INVALID_ASSORTMENT` | — | Token assortment is invalid | | `ZERO_ADDRESS` | — | Address is zero | | `PAIR_EXISTS` | — | Pair already exists | | `INVALID_FEE_SPLIT` | — | Fee split is invalid | ## Fee Recipient Factory Errors | Error | Parameters | Description | | ---------------------- | ---------- | ----------------------- | | `INVALID_TREASURY_FEE` | — | Treasury fee is invalid | ## Router Errors | Error | Parameters | Description | | ------------------------ | ---------- | ------------------------------ | | `EXPIRED` | — | Deadline has expired | | `IDENTICAL` | — | Tokens are identical | | `INSUFFICIENT_AMOUNT` | — | Amount is insufficient | | `INVALID_PATH` | — | Path is invalid | | `INSUFFICIENT_B_AMOUNT` | — | Token B amount is insufficient | | `INSUFFICIENT_A_AMOUNT` | — | Token A amount is insufficient | | `EXCESSIVE_INPUT_AMOUNT` | — | Input amount is excessive | | `ETH_TRANSFER_FAILED` | — | ETH transfer failed | | `INVALID_RESERVES` | — | Reserves are invalid | ## Minter Errors | Error | Parameters | Description | | -------------------------------- | ---------- | --------------------------------------------------------- | | `STARTED` | — | Epoch 0 has already started | | `EMISSIONS_NOT_STARTED` | — | Emissions haven't started | | `TOO_HIGH` | — | Deviation is too high | | `NO_CHANGE` | — | No value change detected | | `SAME_PERIOD` | — | Updating emissions in same period | | `INVALID_CONTRACT` | — | Contract setup is invalid | | `FEE_SPLIT_WHEN_NO_GAUGE_IS_OFF` | — | Legacy factory doesn't have `feeSplitWhenNoGauge` enabled | ## Access Hub Errors | Error | Parameters | Description | | -------------------------- | ---------------- | ----------------------------------------- | | `SAME_ADDRESS` | — | Addresses are identical | | `NOT_TIMELOCK` | `address caller` | Caller is not the timelock | | `MANUAL_EXECUTION_FAILURE` | `bytes reason` | Manual execution failed | | `KICK_FORBIDDEN` | `address target` | Kick operation is forbidden | | `FUNCTION_NOT_FOUND` | — | Function called on AccessHub is not found | | `FAILED_TO_ADD` | — | Expansion pack can't be added | | `FAILED_TO_REMOVE` | — | Expansion pack can't be removed | | `NOT_X33_ADAPTER` | — | Caller is not the x33Adapter | ## Vote Module Errors | Error | Parameters | Description | | ----------------- | ---------- | ------------------------------- | | `NOT_XRAM` | — | Caller is not xRAM | | `COOLDOWN_ACTIVE` | — | Cooldown period is still active | | `NOT_VOTEMODULE` | — | Caller is not the vote module | | `UNAUTHORIZED` | — | Caller is unauthorized | | `NOT_ACCESSHUB` | — | Caller is not the access hub | | `INVALID_ADDRESS` | — | Address is invalid | ## x33 Errors | Error | Parameters | Description | | ---------------------------- | -------------------- | ------------------------------ | | `ZERO` | — | Value is zero | | `NOT_ENOUGH` | — | Amount is insufficient | | `NOT_CONFORMED_TO_SCALE` | `uint256 value` | Value doesn't conform to scale | | `LOCKED` | — | Contract is locked | | `REBASE_IN_PROGRESS` | — | Rebase is in progress | | `AGGREGATOR_REVERTED` | `bytes reason` | Aggregator reverted | | `AMOUNT_OUT_TOO_LOW` | `uint256 amount` | Output amount is too low | | `AGGREGATOR_NOT_WHITELISTED` | `address aggregator` | Aggregator is not whitelisted | | `FORBIDDEN_TOKEN` | `address token` | Token is forbidden | ## xRAM Errors | Error | Parameters | Description | | ---------------- | ---------- | ------------------------------- | | `NOT_MINTER` | — | Caller is not the minter | | `NO_VEST` | — | No vest exists | | `ALREADY_EXEMPT` | — | Already exempt | | `NOT_EXEMPT` | — | Not exempt | | `CANT_RESCUE` | — | Rescue operation is not allowed | | `ARRAY_LENGTHS` | — | Array lengths mismatch | | `VEST_OVERLAP` | — | Vesting periods overlap | ## V3 Factory Errors | Error | Parameters | Description | | ------------------ | ------------- | ---------------------- | | `IDENTICAL_TOKENS` | — | Tokens are identical | | `FEE_TOO_LARGE` | — | Fee is too large | | `ADDRESS_ZERO` | — | Address is zero | | `F0` | — | Fee is zero | | `OOB` | `uint8 value` | Value is out of bounds | *** # CL Pool String Errors Short string error codes used in the concentrated liquidity pool contracts. ## Oracle.sol * `OLD`: The target must be chronologically after the oldest observation * `I`: The pool has not been initialized ## Position.sol * `NP`: Burn cannot be called for a position with 0 liquidity ## Tick.sol * `LO`: LiquidityGrossAfter must be less than MaxLiquidity ## TickMath.sol * `T`: The given tick must be less than, or equal to, the maximum tick * `R`: Second inequality must be \< because the price can never reach the price at the max tick ## TransferHelper.sol * `TF`: Transfer failed ## RamsesV3Pool.sol * `LOK`: Reentrancy guard — a transaction cannot re-enter the pool mid-swap * `TLU`: The lower tick must be below the upper tick * `TLM`: The lower tick must be greater than, or equal to, the minimum tick * `TUM`: The upper tick must be less than, or equal to, the maximum tick * `AI`: The pool is already initialized * `M0`: The balance of token0 before minting must be less than or equal to the balance after minting * `M1`: The balance of token1 before minting must be less than or equal to the balance after minting * `AS`: `amountSpecified` cannot be zero * `SPL`: Square root price limit violated * `IIA`: Insufficient input amount — not enough tokens sent during the callback * `L`: Liquidity must be greater than zero for a flash to be executed * `F0`: The balance of token0 before flash must be less than or equal to the balance after flash plus the fee * `F1`: The balance of token1 before flash must be less than or equal to the balance after flash plus the fee # FeeCollector Source: https://tech.ramses.xyz/contracts/reference/gauge/FeeCollector Routes protocol fees collected from Ramses V3 pools between the treasury and fee distributors. Acts as an intermediary that splits fees according to configurable ratios. ## Functions ### collectProtocolFees ```solidity theme={null} function collectProtocolFees( address pool ) external ``` Triggers collection of accumulated protocol fees from a pool and routes them according to the configured split. #### Parameters: | Name | Type | Description | | :----- | :------ | :-------------------------------------- | | `pool` | address | The Ramses V3 pool to collect fees from | ### setTreasuryFees ```solidity theme={null} function setTreasuryFees( uint256 _treasuryFees ) external ``` Sets the percentage of protocol fees directed to the treasury. The remainder goes to fee distributors for voter rewards. #### Parameters: | Name | Type | Description | | :-------------- | :------ | :----------------------------------------- | | `_treasuryFees` | uint256 | The treasury fee percentage (basis points) | ### setTreasury ```solidity theme={null} function setTreasury( address _treasury ) external ``` Sets the treasury address that receives its share of protocol fees. #### Parameters: | Name | Type | Description | | :---------- | :------ | :----------------------- | | `_treasury` | address | The new treasury address | ## Key Concepts * Protocol fees are split between the treasury and fee distributors * Fee distributors pass fees to voters as incentives for directing emissions * Configuration is managed through the AccessHub governance system # FeeDistributor Source: https://tech.ramses.xyz/contracts/reference/gauge/FeeDistributor Periodized fee and incentive distributor for a single pool's voting market. Each active gauge has an associated `FeeDistributor`. Rewards are tracked by **owner address**, not by veNFT token ID. ## Core Functions ### getReward ```solidity theme={null} function getReward(address owner, address[] memory tokens) external ``` Claims all finalized rewards for `owner` across the provided token list. The caller must be `owner` or an approved admin in `VoteModule`. ### getPeriodReward ```solidity theme={null} function getPeriodReward(uint256 period, address owner, address token) external ``` Claims a single reward token for one finalized period. ### notifyRewardAmount ```solidity theme={null} function notifyRewardAmount(address token, uint256 amount) external ``` Queues new rewards for the **next** period. This can only be called by the configured `feeRecipient` address, which is the fee-routing source for that market. ### incentivize ```solidity theme={null} function incentivize(address token, uint256 amount) external ``` Lets third parties add whitelisted incentive tokens for the next period. ### getRewardForOwner ```solidity theme={null} function getRewardForOwner(address owner, address[] memory tokens) external ``` Claims all finalized rewards on behalf of `owner`, sending them to the `owner` address. Only callable by the Voter contract. #### Parameters: | Name | Type | Description | | :------- | :--------- | :------------------------------------- | | `owner` | address | The owner address to claim rewards for | | `tokens` | address\[] | The reward token addresses to claim | ### getRewardForOwnerTo ```solidity theme={null} function getRewardForOwnerTo(address owner, address[] memory tokens, address destination) external ``` Claims all finalized rewards on behalf of `owner`, sending them to a specified `destination` address. Only callable by the Voter contract. #### Parameters: | Name | Type | Description | | :------------ | :--------- | :------------------------------------- | | `owner` | address | The owner address to claim rewards for | | `tokens` | address\[] | The reward token addresses to claim | | `destination` | address | The address to send claimed rewards to | ### earned ```solidity theme={null} function earned(address token, address owner) external view returns (uint256 reward) ``` Returns the claimable amount for `owner` across finalized periods, net of prior claims. ## Key Concepts * Rewards are period-based and typically queued into `getPeriod() + 1`. * `Voter` updates each user's balance in the fee distributor when votes are cast, reset, or recalculated. * A distributor can hold multiple reward tokens at once. * `notifyRewardAmount()` is used for fee routing, while `incentivize()` is used for vote incentives and bribes. * Claims are permissioned through `VoteModule.isAdminFor()`, which is why admin relationships matter even outside direct voting. # GaugeV3 Source: https://tech.ramses.xyz/contracts/reference/gauge/GaugeV3 Distributes weekly RAM emissions to Ramses V3 concentrated liquidity positions. Rewards are allocated based on `periodSecondsInsideX96`, which tracks each position's time-weighted in-range contribution during each weekly period. ## Functions ### notifyRewardAmount ```solidity theme={null} function notifyRewardAmount( address token, uint256 amount ) external ``` Notifies the gauge of newly deposited reward tokens for distribution in the current period. Collects protocol fees from the pool before processing. The token must be a whitelisted reward token. #### Parameters: | Name | Type | Description | | :------- | :------ | :---------------------------------------- | | `token` | address | The reward token address | | `amount` | uint256 | The amount of reward tokens to distribute | ### notifyRewardAmountNextPeriod ```solidity theme={null} function notifyRewardAmountNextPeriod( address token, uint256 amount ) external ``` Queues reward tokens for distribution in the next period rather than the current one. #### Parameters: | Name | Type | Description | | :------- | :------ | :---------------------------------------- | | `token` | address | The reward token address | | `amount` | uint256 | The amount of reward tokens to distribute | ### notifyRewardAmountForPeriod ```solidity theme={null} function notifyRewardAmountForPeriod( address token, uint256 amount, uint256 period ) external ``` Queues reward tokens for distribution in a specific future period. The period must be strictly in the future. #### Parameters: | Name | Type | Description | | :------- | :------ | :----------------------------------------- | | `token` | address | The reward token address | | `amount` | uint256 | The amount of reward tokens to distribute | | `period` | uint256 | The future period to distribute rewards in | ### getReward ```solidity theme={null} function getReward( uint256 tokenId, address[] tokens ) external ``` Claims accrued rewards for a position. Calculates rewards based on the position's `periodSecondsInsideX96` relative to total in-range liquidity during each period. The caller must be the position owner, operator, or approved for all. Only callable by authorized claimers. #### Parameters: | Name | Type | Description | | :-------- | :--------- | :-------------------------------------- | | `tokenId` | uint256 | The ID of the position NFT to claim for | | `tokens` | address\[] | The reward token addresses to claim | ### getReward (batch) ```solidity theme={null} function getReward( uint256[] tokenIds, address[] tokens ) external ``` Claims accrued rewards for multiple positions in a single call. #### Parameters: | Name | Type | Description | | :--------- | :--------- | :---------------------------------------- | | `tokenIds` | uint256\[] | The IDs of the position NFTs to claim for | | `tokens` | address\[] | The reward token addresses to claim | ### getRewardForOwner ```solidity theme={null} function getRewardForOwner( uint256 tokenId, address[] tokens ) external ``` Claims rewards on behalf of the position owner, sending them to the owner's address. Callable by the voter contract or authorized claimers. #### Parameters: | Name | Type | Description | | :-------- | :--------- | :-------------------------------------- | | `tokenId` | uint256 | The ID of the position NFT to claim for | | `tokens` | address\[] | The reward token addresses to claim | ### earned ```solidity theme={null} function earned( address token, uint256 tokenId ) external view returns (uint256) ``` Returns the amount of a reward token earned by a position but not yet claimed. #### Parameters: | Name | Type | Description | | :-------- | :------ | :------------------------- | | `token` | address | The reward token address | | `tokenId` | uint256 | The ID of the position NFT | #### Return Values: | Type | Description | | :------ | :----------------------- | | uint256 | Amount of earned rewards | ### periodEarned ```solidity theme={null} function periodEarned( uint256 period, address token, uint256 tokenId ) external view returns (uint256) ``` Returns the amount earned by a position for a specific period. #### Parameters: | Name | Type | Description | | :-------- | :------ | :------------------------- | | `period` | uint256 | The period to query | | `token` | address | The reward token address | | `tokenId` | uint256 | The ID of the position NFT | ### left ```solidity theme={null} function left( address token ) external view returns (uint256) ``` Returns the approximate amount of a reward token remaining for distribution in the current period, based on the time remaining. #### Parameters: | Name | Type | Description | | :------ | :------ | :----------------------- | | `token` | address | The reward token address | #### Return Values: | Type | Description | | :------ | :---------------------------------- | | uint256 | Approximate remaining reward amount | ### rewardRate ```solidity theme={null} function rewardRate( address token ) external view returns (uint256) ``` Returns the per-second reward rate for a token in the current period. #### Parameters: | Name | Type | Description | | :------ | :------ | :----------------------- | | `token` | address | The reward token address | #### Return Values: | Type | Description | | :------ | :----------------------- | | uint256 | Reward amount per second | ### getRewardTokens ```solidity theme={null} function getRewardTokens() external view returns (address[]) ``` Returns the list of all reward token addresses registered on this gauge. ### positionHash ```solidity theme={null} function positionHash( address owner, uint256 index, int24 tickLower, int24 tickUpper ) external pure returns (bytes32) ``` Computes the unique identifier for a position based on its owner, index, and tick range. #### Parameters: | Name | Type | Description | | :---------- | :------ | :----------------------------------- | | `owner` | address | The position owner address | | `index` | uint256 | The position index (token ID) | | `tickLower` | int24 | The lower tick of the position range | | `tickUpper` | int24 | The upper tick of the position range | ### addRewards ```solidity theme={null} function addRewards( address reward ) external ``` Adds a new reward token to the gauge. Only callable by AccessHub. #### Parameters: | Name | Type | Description | | :------- | :------ | :------------------------------ | | `reward` | address | The reward token address to add | ### removeRewards ```solidity theme={null} function removeRewards( address reward ) external ``` Removes a reward token from the gauge. Only callable by AccessHub. #### Parameters: | Name | Type | Description | | :------- | :------ | :--------------------------------- | | `reward` | address | The reward token address to remove | ### syncCache ```solidity theme={null} function syncCache() external ``` Syncs cached values from the Voter and AccessHub contracts, including the reward validator, R33 address, fee collector, and authorized claimers list. ## Key Concepts * Rewards are distributed per **weekly period** (epoch), aligned with the Ramses voting cycle * A position earns rewards proportional to its `secondsInsideX96` during each period relative to the total * Only authorized claimers (registered through the Voter contract) can call reward-claiming functions * The gauge supports a reward validator for anti-sybil checks; flagged claims are redirected to the R33 address * `notifyRewardAmount` collects protocol fees from the pool before processing new rewards # AccessHub Source: https://tech.ramses.xyz/contracts/reference/governance/AccessHub Central governance router and permissions hub for Ramses. `AccessHub` coordinates protocol changes across the factory, voter, xRAM, R33, fee-routing contracts, and AutoVault. It mixes three different control surfaces: * **Role-gated actions** * **Treasury / multisig-only actions** * **Timelock-only actions** ## Roles ### SWAP\_FEE\_SETTER Intended for fast operational actions such as: * `setSwapFees()` * Some fee-related CL and legacy operations * `compoundR33()` ### PROTOCOL\_OPERATOR Broader operational role for: * Gauge creation, revival, and kill flows * Operator-routed DLMM pool and rewarder creation * Governance whitelist changes * xRAM whitelist and operator management * Emissions-ratio and reward-token management * VoteModule and Minter operational updates ### Treasury and Timelock Some sensitive functions are not role-based: * `onlyMultisig` functions are restricted to the treasury address * `timelocked` functions are restricted to the timelock address ## Representative Functions ### setSwapFees ```solidity theme={null} function setSwapFees(address[] calldata pools, uint24[] calldata swapFees) external ``` Batch updates swap fees across CL and legacy pools. ### setFeeSplitCL / setFeeSplitLegacy ```solidity theme={null} function setFeeSplitCL(address[] calldata pools, uint24[] calldata feeProtocol) external function setFeeSplitLegacy(address[] calldata pools, uint256[] calldata feeSplits) external ``` Batch updates protocol fee routing for CL and legacy pools. ### createCLGauge / createLegacyGauge ```solidity theme={null} function createCLGauge(address tokenA, address tokenB, int24 tickSpacing, bool forceVoterFees) external returns (address) function createLegacyGauge(address pool) external returns (address) ``` Governance entrypoints for gauge creation. ### createDLMMPool / createDLMMRewarder ```solidity theme={null} function createDLMMPool( address tokenX, address tokenY, uint24 activeId, uint16 binStep ) external returns (address pool) function createDLMMRewarder(address pool) external returns (address rewarder) ``` `PROTOCOL_OPERATOR` entrypoints for operator-routed DLMM onboarding. `createDLMMPool()` can add `tokenY` to the factory quote-asset list before creating the pool. Regular users create pools directly through an open factory preset. ### DLMM fee setters ```solidity theme={null} function setFeeSplitDLMM(address[] calldata pools, uint16[] calldata protocolShares) external // Full AccessHub implementation function setSwapBaseFeeDLMM(address[] calldata pools, uint16[] calldata baseFactors) external // AccessHubSatellite, including the Robinhood snapshot implementation function setSwapFeeParametersDLMM(address[] calldata pools, bytes32[] calldata feeParameters) external ``` `setFeeSplitDLMM()` accepts the configured `Voter` or a `SWAP_FEE_SETTER`; protocol share is measured out of `10,000`. The full AccessHub changes only each pool's base factor, preserving its other fee fields. `AccessHubSatellite` accepts the full packed static-fee parameter set instead. Check the deployed implementation before encoding an operator transaction. Multisig-only DLMM controls include: * Configuring the factory and rewarder factory in `Voter` * Updating the beacon implementation used by existing rewarders * Granting or revoking hook-manager and authorized-manager status * Accepting factory ownership * Changing a rewarder's eligible bin range * Updating the global preset protocol share for future pools * Repairing the fee collector's `Voter` address ### updateEmissionsMultiplierInMinter ```solidity theme={null} function updateEmissionsMultiplierInMinter(uint256 newMultiplier) external ``` Forwards a multiplier update into `Minter`. ### setNewVoteModuleCooldown ```solidity theme={null} function setNewVoteModuleCooldown(uint256 newCooldown) external ``` Timelock-only update of the `VoteModule` cooldown. ### execute ```solidity theme={null} function execute(address target, bytes calldata payload) external ``` Timelock-only arbitrary execution hook for exceptional governance operations. ## Key Concepts * `AccessHub` is the main operational control plane for Ramses governance. * It centralizes fee updates, xRAM/R33 administration, gauge management, treasury routing, and several emergency functions. * Many functions are batched so governance can update several pools or gauges in a single transaction. * It also owns newer integrations such as `AutoVault` and reward-validator management. * For DLMM, it owns material economic and hook configuration, but the reviewed pool interface does not expose an AccessHub function that withdraws arbitrary user LP principal. # Minter Source: https://tech.ramses.xyz/contracts/reference/governance/Minter Weekly emissions controller for RAM. The current implementation in `Minter.sol` is the contract-enforced source of truth for supply caps, multiplier updates, and weekly emissions minting. ## Core Functions ### kickoff ```solidity theme={null} function kickoff( address ram, address voter, uint256 initialWeeklyEmissions, uint256 initialMultiplier, address xRam ) external ``` One-time operator-only initialization. Sets the token and governance addresses, seeds the initial emissions configuration, and mints the `INITIAL_SUPPLY` to the operator. ### initEpoch0 ```solidity theme={null} function initEpoch0() external ``` Starts epoch accounting by setting `firstPeriod`, `activePeriod`, and minting the configured week-0 emissions to the operator. ### updatePeriod ```solidity theme={null} function updatePeriod() external returns (uint256 period) ``` Permissionless weekly rollover function. When a new period has started, it: 1. Computes the next weekly emissions amount 2. Mints that amount to the Minter contract 3. Approves the `Voter` 4. Calls `Voter.notifyRewardAmount()` ### updatePeriodAndRebase ```solidity theme={null} function updatePeriodAndRebase() external ``` Convenience entrypoint that advances the period and then calls `rebase()` on xRAM. ### updateEmissionsMultiplier ```solidity theme={null} function updateEmissionsMultiplier(uint256 emissionsMultiplier) external ``` Governance-only update for the emissions multiplier. The contract enforces a maximum deviation of `25%` per update. ### calculateWeeklyEmissions ```solidity theme={null} function calculateWeeklyEmissions() external view returns (uint256) ``` Returns the next emission amount after applying the multiplier and the supply cap. ## Key Concepts * `INITIAL_SUPPLY` is `350,000,000e18`. * `MAX_SUPPLY` is `1,000,000,000e18`. * `BASIS` is `10_000`, and `MAX_DEVIATION` is `2_500`, meaning multiplier changes are capped at 25% per update. * `updatePeriod()` returns the active weekly period, not the minted token amount. * The Minter is the contract that mints weekly emissions and hands them to `Voter`; gauges receive those emissions only after the subsequent voter distribution flow. # VoteModule Source: https://tech.ramses.xyz/contracts/reference/governance/VoteModule Staking, delegation, and permissions module for xRAM. `VoteModule` is the contract that actually supplies governance voting power. `Voter` reads `VoteModule.balanceOf(user)`, not a wallet balance or NFT position. ## Core Functions ### deposit / depositAll ```solidity theme={null} function deposit(uint256 amount) external function depositAll() external ``` Moves xRAM from the caller into `VoteModule` and increases the caller's voting power. ### withdraw / withdrawAll ```solidity theme={null} function withdraw(uint256 amount) external function withdrawAll() external ``` Returns xRAM to the caller and reduces voting power. ### delegate ```solidity theme={null} function delegate(address delegatee) external ``` Grants another address permission to act as a delegate for voting-related calls such as `Voter.vote()`, `Voter.reset()`, and `Voter.poke()`. Passing `address(0)` clears the delegate. ### setAdmin ```solidity theme={null} function setAdmin(address admin) external ``` Sets an admin/operator for the caller. Admin permissions are broader than delegate permissions and are used by fee-distributor reward claims. ### isDelegateFor / isAdminFor ```solidity theme={null} function isDelegateFor(address caller, address owner) external view returns (bool) function isAdminFor(address caller, address owner) external view returns (bool) ``` Permission checks consumed by `Voter` and `FeeDistributor`. ### unlockTime / cooldown ```solidity theme={null} function unlockTime() external view returns (uint256) function cooldown() external view returns (uint256) ``` Expose the active cooldown window. Unless an address is exempt, both deposits and withdrawals require `block.timestamp >= unlockTime`. ## Key Concepts * Voting power equals the caller's staked xRAM balance in `VoteModule`. * `notifyRewardAmount(0)` can only be called by xRAM and is used to push `unlockTime` forward after weekly maintenance. * Delegates are intended for voting actions; admins are used for a wider set of owner-authorized operations such as fee claims. * `AccessHub` can change cooldown settings and add cooldown exemptions for specific addresses. # Voter Source: https://tech.ramses.xyz/contracts/reference/governance/Voter Central voting, gauge-management, and emissions-routing contract for Ramses. The current implementation is **address-based**, not NFT-based. Voting power comes from `VoteModule.balanceOf(owner)`, and votes are stored per owner address and per weekly period. ## Core Functions ### vote ```solidity theme={null} function vote(address owner, address[] calldata pools, uint256[] calldata weights) external ``` Casts or recasts votes for `owner` into the **next** weekly period. The raw `weights` array is normalized against the owner's current `VoteModule` balance, so it does not need to sum to a fixed constant. The call can be made by: * `owner` * An approved delegate/admin recognized by `VoteModule` * `AccessHub` ### reset ```solidity theme={null} function reset(address owner) external ``` Clears `owner`'s votes for the upcoming period. ### poke ```solidity theme={null} function poke(address owner) external ``` Recasts the owner's last vote weights using the owner's current voting power. This is how balance changes in `VoteModule` are propagated into the stored next-period vote weights. ### distribute ```solidity theme={null} function distribute(address gauge) external ``` Advances emissions and distributes them to a specific gauge. For CL gauges, this flow also triggers protocol-fee collection from the pool through `FeeCollector`. When DLMM is configured and the target is a registered `DLMMRewarder`, it sends RAM to the rewarder, updates its streaming rate, and synchronizes the pool's fee-routing state. ### createGauge / createCLGauge ```solidity theme={null} function createGauge(address pool) external returns (address gauge) function createCLGauge(address tokenA, address tokenB, int24 tickSpacing) external returns (address gauge) ``` Governance-only gauge creation entrypoints for legacy and concentrated-liquidity pools. ### createDLMMRewarder ```solidity theme={null} function createDLMMRewarder(address pool) external returns (address rewarder) ``` Governance-only DLMM onboarding. It: 1. Verifies the pool belongs to the configured `DLMMFactory` 2. Collects any pre-rewarder protocol fees 3. Deploys and links a beacon-proxy rewarder 4. Creates the pool's `FeeDistributor` 5. Registers the pool/rewarder mappings 6. Marks the rewarder alive and sets the pool's gauged protocol share Related governance functions configure the DLMM factory, rewarder factory, rewarded-bin range, and authorized router/manager list. ### claimIncentives / claimClGaugeRewards / claimRewards ```solidity theme={null} function claimIncentives(address owner, address[] calldata feeDistributors, address[][] calldata tokens) external function claimClGaugeRewards(address[] calldata gauges, address[][] calldata tokens, uint256[][] calldata nfpTokenIds) external function claimRewards(address[] calldata gauges, address[][] calldata tokens) external ``` Helpers for collecting fee-distributor incentives and gauge rewards. ## Key Concepts * Votes are recorded for `getPeriod() + 1`, not the current period. * `vote()` internally clears prior next-period votes before writing the new allocation. * `FeeDistributor` balances are keyed by **owner address**, which is why `Voter` deposits and withdraws vote weight there during `vote()` and `reset()`. * `distribute()` coordinates both emissions and fee routing, making it one of the central weekly-maintenance flows in the system. * Whitelisting, gauge lifecycle changes, reward-validator configuration, and other privileged actions are gated through governance and `AccessHub`. * DLMM users vote for the pool address; the associated `DLMMRewarder` is the emission target stored in `gaugeForPool`. * A DLMM rewarder is a hook, not a `GaugeV3` contract. At the [Robinhood snapshot at block 22,674,244](/contracts/reference/dlmm/deployments), the DLMM factory reported a zero `voter()` address, so these rewarder flows were not live there. # Overview Source: https://tech.ramses.xyz/contracts/reference/overview Ramses is a multi-contract system with four main layers: * **Core concentrated-liquidity contracts** * **Core discrete-liquidity contracts and periphery** * **Periphery routing and position-management contracts** * **Governance, emissions, and fee-routing contracts** The current contracts use an address-based governance model built on `xRAM`, `VoteModule`, `Voter`, `FeeDistributor`, and `AccessHub`. Older descriptions that refer to veNFT-style voting are not accurate for the code in this repository. ## Core > [**Factory Reference**](./core/RamsesV3Factory) The CL core consists of: * `RamsesV3Factory` * `RamsesV3PoolDeployer` * `RamsesV3Pool` * Core pool interfaces and math/oracle libraries Pools expose swap, liquidity, oracle, and protocol-fee functionality, while the factory wires pools into the wider Ramses governance and fee-routing system. ## DLMM > [**DLMM Contract Architecture**](./dlmm/overview) > [**Robinhood DLMM Deployments**](./dlmm/deployments) The DLMM stack consists of: * `DLMMFactory` * `DLMMPool` and its embedded `DLMMToken` share accounting * `DLMMRouter` and `DLMMQuoter` * `DLMMFeeCollector` * Optional `DLMMRewarder` hooks and `DLMMRewarderFactory` DLMM prices are divided into fixed-price bins. LP ownership is represented by a fungible share balance for each bin ID, and swap fees retained for LPs stay in bin reserves. At the [Robinhood snapshot at block 22,674,244](/contracts/reference/dlmm/deployments), the deployment was fee-only and its factory was not connected to `Voter`. Rewarder references describe optional architecture. ## Periphery > [**Swap Router Reference**](./periphery/SwapRouter) > [**Position Manager Reference**](./periphery/RamsesV3PositionManager) The periphery adds safer and more ergonomic integration points for swaps, NFT positions, quoting, tick inspection, and helper libraries. ## Gauges and Fee Routing > [**GaugeV3 Reference**](./gauge/GaugeV3) > [**FeeCollector Reference**](./gauge/FeeCollector) > [**FeeDistributor Reference**](./gauge/FeeDistributor) > [**Sarcophagus Reference & Searcher Guide**](./sarcophagus) This layer handles: * Weekly emissions for active gauges * Protocol-fee collection from CL pools * Protocol-fee collection from DLMM pools * Periodized distribution of fee and incentive tokens to voter addresses * Permissionless exchange of r33 for selected ERC-20 protocol-fee balances on supported deployments ## Governance > [**Voter Reference**](./governance/Voter) > [**Minter Reference**](./governance/Minter) > [**VoteModule Reference**](./governance/VoteModule) > [**AccessHub Reference**](./governance/AccessHub) Governance responsibilities are split across several contracts: * **VoteModule** holds staked xRAM and exposes voting power, delegation, and admin permissions. * **Voter** records votes by owner address, creates gauges, routes emissions, and coordinates reward claims. * **Minter** advances the weekly period and mints capped emissions. * **AccessHub** is the operational control layer for fees, gauges, xRAM/R33 administration, and treasury/timelock actions. ## Tokens > [**xRAM Reference**](./tokens/xRAM) > [**R33 / hyperRAM Reference**](./tokens/R33) * **xRAM** is a transfer-restricted ERC20 governance token created from RAM via `convertEmissionsToken()`. * **R33** is the source contract for the liquid governance wrapper; the ERC4626 token it mints is named `hyperRAM`. # NonfungibleTokenPositionDescriptor Source: https://tech.ramses.xyz/contracts/reference/periphery/NonfungibleTokenPositionDescriptor Produces a string containing the data URI for a JSON metadata string ## Functions ### constructor ```solidity theme={null} function constructor( ) public ``` ### tokenURI ```solidity theme={null} function tokenURI( contract IRamsesV3PositionManager positionManager, uint256 tokenId ) external returns (string) ``` Produces the URI describing a particular token ID for a position manager Note this URI may be a data: URI with the JSON contents directly inlined #### Parameters: | Name | Type | Description | | :---------------- | :-------------------------------- | :----------------------------------------------------------------------------- | | `positionManager` | contract IRamsesV3PositionManager | The position manager for which to describe the token | | `tokenId` | uint256 | The ID of the token for which to produce a description, which may not be valid | #### Return Values: | Name | Type | Description | | :---- | :-------------------------------- | :----------------------------------- | | `The` | contract IRamsesV3PositionManager | URI of the ERC721-compliant metadata | ### flipRatio ```solidity theme={null} function flipRatio( ) public returns (bool) ``` ### tokenRatioPriority ```solidity theme={null} function tokenRatioPriority( ) public returns (int256) ``` # RamsesV3PositionManager Source: https://tech.ramses.xyz/contracts/reference/periphery/RamsesV3PositionManager Wraps Ramses V3 positions in the ERC721 non-fungible token interface. Extends the standard position management with gauge reward claiming and voter integration. ## Functions ### constructor ```solidity theme={null} function constructor( ) public ``` ### positions ```solidity theme={null} function positions( uint256 tokenId ) external view returns (address token0, address token1, int24 tickSpacing, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1) ``` Returns the position information associated with a given token ID. Throws if the token ID is not valid. #### Parameters: | Name | Type | Description | | :-------- | :------ | :----------------------------------------------- | | `tokenId` | uint256 | The ID of the token that represents the position | #### Return Values: | Name | Type | Description | | :------------------------- | :------ | :------------------------------------------------------------------------------- | | `token0` | address | The address of the token0 for a specific pool | | `token1` | address | The address of the token1 for a specific pool | | `tickSpacing` | int24 | The tick spacing of the pool | | `tickLower` | int24 | The lower end of the tick range for the position | | `tickUpper` | int24 | The higher end of the tick range for the position | | `liquidity` | uint128 | The liquidity of the position | | `feeGrowthInside0LastX128` | uint256 | The fee growth of token0 as of the last action on the individual position | | `feeGrowthInside1LastX128` | uint256 | The fee growth of token1 as of the last action on the individual position | | `tokensOwed0` | uint128 | The uncollected amount of token0 owed to the position as of the last computation | | `tokensOwed1` | uint128 | The uncollected amount of token1 owed to the position as of the last computation | ### mint ```solidity theme={null} function mint( struct IRamsesV3PositionManager.MintParams params ) external payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1) ``` Creates a new position wrapped in a NFT Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized a method does not exist, i.e. the pool is assumed to be initialized. #### Parameters: | Name | Type | Description | | :------- | :----------------------------------------- | :--------------------------------------------------------------------------- | | `params` | struct IRamsesV3PositionManager.MintParams | The params necessary to mint a position, encoded as `MintParams` in calldata | #### Return Values: | Name | Type | Description | | :---------- | :------ | :------------------------------------------------------ | | `tokenId` | uint256 | The ID of the token that represents the minted position | | `liquidity` | uint128 | The amount of liquidity for this position | | `amount0` | uint256 | The amount of token0 | | `amount1` | uint256 | The amount of token1 | ### tokenURI ```solidity theme={null} function tokenURI( uint256 tokenId ) public view returns (string) ``` Returns a URI describing a particular token ID #### Parameters: | Name | Type | Description | | :-------- | :------ | :------------------------------------------------------ | | `tokenId` | uint256 | The ID of the token that represents the minted position | #### Return Values: A base64 string with the URI data. ### increaseLiquidity ```solidity theme={null} function increaseLiquidity( struct IRamsesV3PositionManager.IncreaseLiquidityParams params ) external payable returns (uint128 liquidity, uint256 amount0, uint256 amount1) ``` Increases the amount of liquidity in a position, with tokens paid by the `msg.sender` #### Parameters: | Name | Type | Description | | :------- | :------------------------------------------------------ | :------------------------------------------------------------------ | | `params` | struct IRamsesV3PositionManager.IncreaseLiquidityParams | tokenId The ID of the token for which liquidity is being increased, | #### Return Values: | Name | Type | Description | | :---------- | :------ | :--------------------------------------------------- | | `liquidity` | uint128 | The new liquidity amount as a result of the increase | | `amount0` | uint256 | The amount of token0 to achieve resulting liquidity | | `amount1` | uint256 | The amount of token1 to achieve resulting liquidity | ### decreaseLiquidity ```solidity theme={null} function decreaseLiquidity( struct IRamsesV3PositionManager.DecreaseLiquidityParams params ) external payable returns (uint256 amount0, uint256 amount1) ``` Decreases the amount of liquidity in a position and accounts it to the position #### Parameters: | Name | Type | Description | | :------- | :------------------------------------------------------ | :------------------------------------------------------------------ | | `params` | struct IRamsesV3PositionManager.DecreaseLiquidityParams | tokenId The ID of the token for which liquidity is being decreased, | #### Return Values: | Name | Type | Description | | :-------- | :------ | :----------------------------------------------------------- | | `amount0` | uint256 | The amount of token0 accounted to the position's tokens owed | | `amount1` | uint256 | The amount of token1 accounted to the position's tokens owed | ### collect ```solidity theme={null} function collect( struct IRamsesV3PositionManager.CollectParams params ) external payable returns (uint256 amount0, uint256 amount1) ``` Collects up to a maximum amount of fees owed to a specific position to the recipient #### Parameters: | Name | Type | Description | | :------- | :-------------------------------------------- | :-------------------------------------------------------------- | | `params` | struct IRamsesV3PositionManager.CollectParams | tokenId The ID of the NFT for which tokens are being collected, | recipient The account that should receive the tokens, amount0Max The maximum amount of token0 to collect, amount1Max The maximum amount of token1 to collect #### Return Values: | Name | Type | Description | | :-------- | :------ | :------------------------------------- | | `amount0` | uint256 | The amount of fees collected in token0 | | `amount1` | uint256 | The amount of fees collected in token1 | ### burn ```solidity theme={null} function burn( uint256 tokenId ) external payable ``` Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens must be collected first. #### Parameters: | Name | Type | Description | | :-------- | :------ | :--------------------------------------- | | `tokenId` | uint256 | The ID of the token that is being burned | ### getReward ```solidity theme={null} function getReward( uint256 tokenId, address[] tokens ) external ``` Claims gauge rewards for a given position NFT. Ramses-specific addition for collecting emissions from GaugeV3. #### Parameters: | Name | Type | Description | | :-------- | :--------- | :--------------------------------------------- | | `tokenId` | uint256 | The ID of the token for which to claim rewards | | `tokens` | address\[] | The reward token addresses to claim | ### setVoter ```solidity theme={null} function setVoter( address _voter ) external ``` Sets the Voter contract address for gauge integration. Ramses-specific. #### Parameters: | Name | Type | Description | | :------- | :------ | :-------------------------------- | | `_voter` | address | The address of the Voter contract | # SwapRouter Source: https://tech.ramses.xyz/contracts/reference/periphery/SwapRouter Router for stateless execution of swaps against Ramses V3 > Input parameters are viewable on the [**Swap Router Interface**](./interfaces/ISwapRouter) ## Functions ### constructor ```solidity theme={null} function constructor( ) public ``` ### uniswapV3SwapCallback ```solidity theme={null} function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes data ) external ``` Called to `msg.sender` after executing a swap via IRamsesV3Pool#swap. In the implementation you must pay the pool tokens owed for the swap. The caller of this method must be checked to be a RamsesV3Pool deployed by the canonical RamsesV3Factory. amount0Delta and amount1Delta can both be 0 if no tokens were swapped. #### Parameters: | Name | Type | Description | | :------------- | :----- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `amount0Delta` | int256 | The amount of token0 that was sent (negative) or must be received (positive) by the pool by the end of the swap. If positive, the callback must send that amount of token0 to the pool. | | `amount1Delta` | int256 | The amount of token1 that was sent (negative) or must be received (positive) by the pool by the end of the swap. If positive, the callback must send that amount of token1 to the pool. | | `data` | bytes | Any data passed through by the caller via the IRamsesV3PoolActions#swap call | ### exactInputSingle ```solidity theme={null} function exactInputSingle( struct ISwapRouter.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 ISwapRouter.ExactInputSingleParams | The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata | #### Return Values: | Name | Type | Description | | :---------- | :------ | :------------------------------- | | `amountOut` | uint256 | The amount of the received token | ### exactInput ```solidity theme={null} function exactInput( struct ISwapRouter.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 ISwapRouter.ExactInputParams | The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata | #### Return Values: | Name | Type | Description | | :---------- | :------ | :------------------------------- | | `amountOut` | uint256 | The amount of the received token | ### exactOutputSingle ```solidity theme={null} function exactOutputSingle( struct ISwapRouter.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 ISwapRouter.ExactOutputSingleParams | The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata | #### Return Values: | Name | Type | Description | | :--------- | :------ | :---------------------------- | | `amountIn` | uint256 | The amount of the input token | ### exactOutput ```solidity theme={null} function exactOutput( struct ISwapRouter.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 ISwapRouter.ExactOutputParams | The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata | #### Return Values: | Name | Type | Description | | :--------- | :------ | :---------------------------- | | `amountIn` | uint256 | The amount of the input token | # BlockTimestamp Source: https://tech.ramses.xyz/contracts/reference/periphery/base/BlockTimestamp Base contract that is overridden for tests ## Functions ### \_blockTimestamp ```solidity theme={null} function _blockTimestamp( ) internal view returns (uint256) ``` Method that exists purely to be overridden for tests #### Return Values: | Type | Description | | :------ | :---------------------- | | uint256 | current block timestamp | # ERC721Permit Source: https://tech.ramses.xyz/contracts/reference/periphery/base/ERC721Permit Nonfungible tokens that support an approve via signature, i.e. permit ## Functions ### \_getAndIncrementNonce ```solidity theme={null} function _getAndIncrementNonce( uint256 tokenId ) internal virtual returns (uint256) ``` Gets the current nonce for a token ID and then increments it, returning the original value ### constructor ```solidity theme={null} function constructor( string memory name_, string memory symbol_, string memory version_ ) internal ``` Computes the nameHash and versionHash ### DOMAIN\_SEPARATOR ```solidity theme={null} function DOMAIN_SEPARATOR( ) public view override returns (bytes32) ``` The domain separator used in the permit signature #### Return Values: | Type | Description | | :------ | :---------------------------------------------------- | | bytes32 | domain seperator used in encoding of permit signature | ### permit ```solidity theme={null} function permit( address spender, uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external ``` Approve of a specific token ID for spending by spender via signature #### Parameters: | Name | Type | Description | | :--------- | :------ | :----------------------------------------------------------------------------- | | `spender` | address | The account that is being approved | | `tokenId` | uint256 | The ID of the token that is being approved for spending | | `deadline` | uint256 | The deadline timestamp by which the call must be mined for the approve to work | | `v` | uint8 | Must produce valid secp256k1 signature from the holder along with `r` and `s` | | `r` | bytes32 | Must produce valid secp256k1 signature from the holder along with `v` and `s` | | `s` | bytes32 | Must produce valid secp256k1 signature from the holder along with `r` and `v` | # LiquidityManagement Source: https://tech.ramses.xyz/contracts/reference/periphery/base/LiquidityManagement Internal functions for safely managing liquidity in Ramses V3 ## Parameter Structs ### AddLiquidityParams ```solidity theme={null} struct AddLiquidityParams { address token0; address token1; int24 tickSpacing; address recipient; uint256 index; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; } ``` ## Functions ### uniswapV3MintCallback ```solidity theme={null} function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes data ) external ``` Called to `msg.sender` after minting liquidity to a position from IRamsesV3Pool#mint. In the implementation you must pay the pool tokens owed for the minted liquidity. The caller of this method must be checked to be a RamsesV3Pool deployed by the canonical RamsesV3Factory. #### Parameters: | Name | Type | Description | | :------------ | :------ | :--------------------------------------------------------------------------- | | `amount0Owed` | uint256 | The amount of token0 due to the pool for the minted liquidity | | `amount1Owed` | uint256 | The amount of token1 due to the pool for the minted liquidity | | `data` | bytes | Any data passed through by the caller via the IRamsesV3PoolActions#mint call | ### addLiquidity ```solidity theme={null} function addLiquidity( AddLiquidityParams memory params ) internal returns (uint128 liquidity, uint256 amount0, uint256 amount1, contract IRamsesV3Pool pool) ``` Add liquidity to an initialized pool # Multicall Source: https://tech.ramses.xyz/contracts/reference/periphery/base/Multicall Enables calling multiple methods in a single call to the contract ## Functions ### multicall ```solidity theme={null} function multicall( bytes[] data ) external payable override returns (bytes[] results) ``` 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 | | :----- | :------- | :----------------------------------------------------------------------- | | `data` | bytes\[] | The encoded function data for each of the calls to make to this contract | #### Return Values: | Name | Type | Description | | :-------- | :------- | :---------------------------------------------------- | | `results` | bytes\[] | The results from each of the calls passed in via data | # PeripheryImmutableState Source: https://tech.ramses.xyz/contracts/reference/periphery/base/PeripheryImmutableState Immutable state used by periphery contracts ## Functions ### constructor ```solidity theme={null} function constructor( address _deployer, address _WETH9 ) internal ``` # PeripheryPayments Source: https://tech.ramses.xyz/contracts/reference/periphery/base/PeripheryPayments ## Functions ### receive ```solidity theme={null} function receive( ) external ``` ### unwrapWETH9 ```solidity theme={null} function unwrapWETH9( uint256 amountMinimum, address recipient ) 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 | | `recipient` | address | The address receiving ETH | ### sweepToken ```solidity theme={null} 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 | ### refundETH ```solidity theme={null} function refundETH( ) external ``` Refunds any ETH balance held by this contract to the `msg.sender` Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps that use ether for the input amount ### pay ```solidity theme={null} function pay( address token, address payer, address recipient, uint256 value ) internal ``` #### Parameters: | Name | Type | Description | | :---------- | :------ | :----------------------------------- | | `token` | address | The token to pay | | `payer` | address | The entity that must pay | | `recipient` | address | The entity that will receive payment | | `value` | uint256 | The amount to pay | # PeripheryPaymentsWithFee Source: https://tech.ramses.xyz/contracts/reference/periphery/base/PeripheryPaymentsWithFee ## Functions ### unwrapWETH9WithFee ```solidity theme={null} function unwrapWETH9WithFee( uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient ) public ``` 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. ### sweepTokenWithFee ```solidity theme={null} function sweepTokenWithFee( address token, uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient ) public ``` 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 # PoolInitializer Source: https://tech.ramses.xyz/contracts/reference/periphery/base/PoolInitializer ## Functions ### createAndInitializePoolIfNecessary ```solidity theme={null} function createAndInitializePoolIfNecessary( address token0, address token1, int24 tickSpacing, uint160 sqrtPriceX96 ) external returns (address pool) ``` Creates a new pool if it does not exist, then initializes if not initialized This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool #### Parameters: | Name | Type | Description | | :------------- | :------ | :----------------------------------------------------------- | | `token0` | address | The contract address of token0 of the pool | | `token1` | address | The contract address of token1 of the pool | | `tickSpacing` | int24 | The tick spacing of the v3 pool for the specified token pair | | `sqrtPriceX96` | uint160 | The initial square root price of the pool as a Q64.96 value | #### Return Values: | Name | Type | Description | | :----- | :------ | :----------------------------------------------------------------------------------------------------------------------------- | | `pool` | address | Returns the pool address based on the pair of tokens and tick spacing, will return the newly created pool address if necessary | # SelfPermit Source: https://tech.ramses.xyz/contracts/reference/periphery/base/SelfPermit Functionality to call permit on any EIP-2612-compliant token for use in the route These functions are expected to be embedded in multicalls to allow EOAs to approve a contract and call a function that requires an approval in a single transaction. ## Functions ### selfPermit ```solidity theme={null} function selfPermit( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public ``` Permits this contract to spend a given token from `msg.sender` The `owner` is always msg.sender and the `spender` is always address(this). #### Parameters: | Name | Type | Description | | :--------- | :------ | :------------------------------------------------------------------------------ | | `token` | address | The address of the token spent | | `value` | uint256 | The amount that can be spent of token | | `deadline` | uint256 | A timestamp, the current blocktime must be less than or equal to this timestamp | | `v` | uint8 | Must produce valid secp256k1 signature from the holder along with `r` and `s` | | `r` | bytes32 | Must produce valid secp256k1 signature from the holder along with `v` and `s` | | `s` | bytes32 | Must produce valid secp256k1 signature from the holder along with `r` and `v` | ### selfPermitIfNecessary ```solidity theme={null} function selfPermitIfNecessary( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external ``` Permits this contract to spend a given token from `msg.sender` The `owner` is always msg.sender and the `spender` is always address(this). Can be used instead of #selfPermit to prevent calls from failing due to a frontrun of a call to #selfPermit #### Parameters: | Name | Type | Description | | :--------- | :------ | :------------------------------------------------------------------------------ | | `token` | address | The address of the token spent | | `value` | uint256 | The amount that can be spent of token | | `deadline` | uint256 | A timestamp, the current blocktime must be less than or equal to this timestamp | | `v` | uint8 | Must produce valid secp256k1 signature from the holder along with `r` and `s` | | `r` | bytes32 | Must produce valid secp256k1 signature from the holder along with `v` and `s` | | `s` | bytes32 | Must produce valid secp256k1 signature from the holder along with `r` and `v` | ### selfPermitAllowed ```solidity theme={null} function selfPermitAllowed( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public ``` Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter The `owner` is always msg.sender and the `spender` is always address(this) #### Parameters: | Name | Type | Description | | :------- | :------ | :---------------------------------------------------------------------------- | | `token` | address | The address of the token spent | | `nonce` | uint256 | The current nonce of the owner | | `expiry` | uint256 | The timestamp at which the permit is no longer valid | | `v` | uint8 | Must produce valid secp256k1 signature from the holder along with `r` and `s` | | `r` | bytes32 | Must produce valid secp256k1 signature from the holder along with `v` and `s` | | `s` | bytes32 | Must produce valid secp256k1 signature from the holder along with `r` and `v` | ### selfPermitAllowedIfNecessary ```solidity theme={null} function selfPermitAllowedIfNecessary( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external ``` Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter The `owner` is always msg.sender and the `spender` is always address(this) Can be used instead of #selfPermitAllowed to prevent calls from failing due to a frontrun of a call to #selfPermitAllowed. #### Parameters: | Name | Type | Description | | :------- | :------ | :---------------------------------------------------------------------------- | | `token` | address | The address of the token spent | | `nonce` | uint256 | The current nonce of the owner | | `expiry` | uint256 | The timestamp at which the permit is no longer valid | | `v` | uint8 | Must produce valid secp256k1 signature from the holder along with `r` and `s` | | `r` | bytes32 | Must produce valid secp256k1 signature from the holder along with `v` and `s` | | `s` | bytes32 | Must produce valid secp256k1 signature from the holder along with `r` and `v` | # IERC20Metadata Source: https://tech.ramses.xyz/contracts/reference/periphery/interfaces/IERC20Metadata Extension to IERC20 that includes token metadata ## Functions ### name ```solidity theme={null} function name( ) external returns (string) ``` #### Return Values: | Type | Description | | :----- | :---------------- | | string | name of the token | ### symbol ```solidity theme={null} function symbol( ) external returns (string) ``` #### Return Values: | Type | Description | | :----- | :------------------ | | string | symbol of the token | ### decimals ```solidity theme={null} function decimals( ) external returns (uint8) ``` #### Return Values: | Type | Description | | :---- | :------------------------------------- | | uint8 | number of decimal places the token has | # IERC721Permit Source: https://tech.ramses.xyz/contracts/reference/periphery/interfaces/IERC721Permit Extension to ERC721 that includes a permit function for signature based approvals ## Functions ### PERMIT\_TYPEHASH ```solidity theme={null} function PERMIT_TYPEHASH( ) external returns (bytes32) ``` The permit typehash used in the permit signature #### Return Values: | Type | Description | | :------ | :---------------------- | | bytes32 | typehash for the permit | ### DOMAIN\_SEPARATOR ```solidity theme={null} function DOMAIN_SEPARATOR( ) external returns (bytes32) ``` The domain separator used in the permit signature #### Return Values: | Name | Type | Description | | :---- | :--- | :---------------------------------------------------- | | `The` | | domain seperator used in encoding of permit signature | ### permit ```solidity theme={null} function permit( address spender, uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external ``` Approve of a specific token ID for spending by spender via signature #### Parameters: | Name | Type | Description | | :--------- | :------ | :----------------------------------------------------------------------------- | | `spender` | address | The account that is being approved | | `tokenId` | uint256 | The ID of the token that is being approved for spending | | `deadline` | uint256 | The deadline timestamp by which the call must be mined for the approve to work | | `v` | uint8 | Must produce valid secp256k1 signature from the holder along with `r` and `s` | | `r` | bytes32 | Must produce valid secp256k1 signature from the holder along with `v` and `s` | | `s` | bytes32 | Must produce valid secp256k1 signature from the holder along with `r` and `v` | # IMulticall Source: https://tech.ramses.xyz/contracts/reference/periphery/interfaces/IMulticall Enables calling multiple methods in a single call to the contract ## Functions ### multicall ```solidity theme={null} function multicall( bytes[] data ) external returns (bytes[] results) ``` 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 | | :----- | :------- | :----------------------------------------------------------------------- | | `data` | bytes\[] | The encoded function data for each of the calls to make to this contract | #### Return Values: | Name | Type | Description | | :-------- | :------- | :---------------------------------------------------- | | `results` | bytes\[] | The results from each of the calls passed in via data | # INonfungibleTokenPositionDescriptor Source: https://tech.ramses.xyz/contracts/reference/periphery/interfaces/INonfungibleTokenPositionDescriptor ## Functions ### tokenURI ```solidity theme={null} function tokenURI( contract IRamsesV3PositionManager positionManager, uint256 tokenId ) external returns (string) ``` Produces the URI describing a particular token ID for a position manager Note this URI may be a data: URI with the JSON contents directly inlined #### Parameters: | Name | Type | Description | | :---------------- | :-------------------------------- | :----------------------------------------------------------------------------- | | `positionManager` | contract IRamsesV3PositionManager | The position manager for which to describe the token | | `tokenId` | uint256 | The ID of the token for which to produce a description, which may not be valid | #### Return Values: | Type | Description | | :----- | :----------------------------------- | | string | URI of the ERC721-compliant metadata | ## Events ### UpdateTokenRatioPriority ```solidity theme={null} event UpdateTokenRatioPriority( address token, int256 priority ) ``` Emitted when a token is given a new priority order in the displayed price ratio #### Parameters: | Name | Type | Description | | :--------- | :------ | :-------------------------------------------------------------------- | | `token` | address | The token being given priority order | | `priority` | int256 | Represents priority in ratio - higher integers get numerator priority | # IPeripheryImmutableState Source: https://tech.ramses.xyz/contracts/reference/periphery/interfaces/IPeripheryImmutableState Functions that return immutable state of the router ## Functions ### factory ```solidity theme={null} function factory( ) external returns (address) ``` #### Return Values: | Type | Description | | :------ | :----------------------------------- | | address | the address of the Ramses V3 factory | ### WETH9 ```solidity theme={null} function WETH9( ) external returns (address) ``` #### Return Values: | Type | Description | | :------ | :------------------- | | address | the address of WETH9 | # IPeripheryPayments Source: https://tech.ramses.xyz/contracts/reference/periphery/interfaces/IPeripheryPayments Functions to ease deposits and withdrawals of ETH ## Functions ### unwrapWETH9 ```solidity theme={null} function unwrapWETH9( uint256 amountMinimum, address recipient ) 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 | | `recipient` | address | The address receiving ETH | ### refundETH ```solidity theme={null} function refundETH( ) external ``` Refunds any ETH balance held by this contract to the `msg.sender` Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps that use ether for the input amount ### sweepToken ```solidity theme={null} 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 | # IPeripheryPaymentsWithFee Source: https://tech.ramses.xyz/contracts/reference/periphery/interfaces/IPeripheryPaymentsWithFee Functions to ease deposits and withdrawals of ETH ## Functions ### unwrapWETH9WithFee ```solidity theme={null} function unwrapWETH9WithFee( ) external ``` 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. ### sweepTokenWithFee ```solidity theme={null} function sweepTokenWithFee( ) 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 # IPoolInitializer Source: https://tech.ramses.xyz/contracts/reference/periphery/interfaces/IPoolInitializer Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that require the pool to exist. ## Functions ### createAndInitializePoolIfNecessary ```solidity theme={null} function createAndInitializePoolIfNecessary( address token0, address token1, uint24 fee, uint160 sqrtPriceX96 ) external returns (address pool) ``` Creates a new pool if it does not exist, then initializes if not initialized This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool #### Parameters: | Name | Type | Description | | :------------- | :------ | :---------------------------------------------------------- | | `token0` | address | The contract address of token0 of the pool | | `token1` | address | The contract address of token1 of the pool | | `fee` | uint24 | The fee amount of the v3 pool for the specified token pair | | `sqrtPriceX96` | uint160 | The initial square root price of the pool as a Q64.96 value | #### Return Values: | Name | Type | Description | | :----- | :------ | :-------------------------------------------------------------------------------------------------------------------- | | `pool` | address | Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary | # IQuoter Source: https://tech.ramses.xyz/contracts/reference/periphery/interfaces/IQuoter Supports quoting the calculated amounts from exact input or exact output swaps These functions are not marked view because they rely on calling non-view functions and reverting to compute the result. They are also not gas efficient and should not be called on-chain. ## Functions ### quoteExactInput ```solidity theme={null} function quoteExactInput( bytes path, uint256 amountIn ) external returns (uint256 amountOut) ``` Returns the amount out received for a given exact input swap without executing the swap #### Parameters: | Name | Type | Description | | :--------- | :------ | :---------------------------------------------------------- | | `path` | bytes | The path of the swap, i.e. each token pair and the pool fee | | `amountIn` | uint256 | The amount of the first token to swap | #### Return Values: | Name | Type | Description | | :---------- | :------ | :-------------------------------------------------- | | `amountOut` | uint256 | The amount of the last token that would be received | ### quoteExactInputSingle ```solidity theme={null} function quoteExactInputSingle( address tokenIn, address tokenOut, int24 tickSpacing, uint256 amountIn, uint160 sqrtPriceLimitX96 ) external returns (uint256 amountOut) ``` Returns the amount out received for a given exact input but for a swap of a single pool #### Parameters: | Name | Type | Description | | :------------------ | :------ | :-------------------------------------------------------------- | | `tokenIn` | address | The token being swapped in | | `tokenOut` | address | The token being swapped out | | `tickSpacing` | int24 | The tick spacing of the pool | | `amountIn` | uint256 | The desired input amount | | `sqrtPriceLimitX96` | uint160 | The price limit of the pool that cannot be exceeded by the swap | #### Return Values: | Name | Type | Description | | :---------- | :------ | :---------------------------------------------- | | `amountOut` | uint256 | The amount of `tokenOut` that would be received | ### quoteExactOutput ```solidity theme={null} function quoteExactOutput( bytes path, uint256 amountOut ) external returns (uint256 amountIn) ``` Returns the amount in required for a given exact output swap without executing the swap #### Parameters: | Name | Type | Description | | :---------- | :------ | :---------------------------------------------------------- | | `path` | bytes | The path of the swap, i.e. each token pair and the pool fee | | `amountOut` | uint256 | The amount of the last token to receive | #### Return Values: | Name | Type | Description | | :--------- | :------ | :-------------------------------------------- | | `amountIn` | uint256 | The amount of first token required to be paid | ### quoteExactOutputSingle ```solidity theme={null} function quoteExactOutputSingle( address tokenIn, address tokenOut, int24 tickSpacing, uint256 amountOut, uint160 sqrtPriceLimitX96 ) external returns (uint256 amountIn) ``` Returns the amount in required to receive the given exact output amount but for a swap of a single pool #### Parameters: | Name | Type | Description | | :------------------ | :------ | :-------------------------------------------------------------- | | `tokenIn` | address | The token being swapped in | | `tokenOut` | address | The token being swapped out | | `tickSpacing` | int24 | The tick spacing of the pool | | `amountOut` | uint256 | The desired output amount | | `sqrtPriceLimitX96` | uint160 | The price limit of the pool that cannot be exceeded by the swap | #### Return Values: | Name | Type | Description | | :--------- | :------ | :---------------------------------------------------------------------------- | | `amountIn` | uint256 | The amount required as the input for the swap in order to receive `amountOut` | # IQuoterV2 Source: https://tech.ramses.xyz/contracts/reference/periphery/interfaces/IQuoterV2 Supports quoting the calculated amounts from exact input or exact output swaps. For each pool also tells you the number of initialized ticks crossed and the sqrt price of the pool after the swap. These functions are not marked view because they rely on calling non-view functions and reverting to compute the result. They are also not gas efficient and should not be called on-chain. ## Functions ### quoteExactInput ```solidity theme={null} function quoteExactInput( bytes path, uint256 amountIn ) external returns (uint256 amountOut, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate) ``` Returns the amount out received for a given exact input swap without executing the swap #### Parameters: | Name | Type | Description | | :--------- | :------ | :---------------------------------------------------------- | | `path` | bytes | The path of the swap, i.e. each token pair and the pool fee | | `amountIn` | uint256 | The amount of the first token to swap | #### Return Values: | Name | Type | Description | | :---------------------------- | :------ | :---------------------------------------------------------------------------- | | `amountOut` | bytes | The amount of the last token that would be received | | `sqrtPriceX96AfterList` | uint256 | List of the sqrt price after the swap for each pool in the path | | `initializedTicksCrossedList` | | List of the initialized ticks that the swap crossed for each pool in the path | | `gasEstimate` | | The estimate of the gas that the swap consumes | ### quoteExactInputSingle ```solidity theme={null} function quoteExactInputSingle( struct IQuoterV2.QuoteExactInputSingleParams params ) external returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate) ``` Returns the amount out received for a given exact input but for a swap of a single pool #### Parameters: | Name | Type | Description | | :------- | :------------------------------------------- | :----------------------------------------------------------------- | | `params` | struct IQuoterV2.QuoteExactInputSingleParams | The params for the quote, encoded as `QuoteExactInputSingleParams` | tokenIn The token being swapped in tokenOut The token being swapped out fee The fee of the token pool to consider for the pair amountIn The desired input amount sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap #### Return Values: | Name | Type | Description | | :------------------------ | :------------------------------------------- | :---------------------------------------------------- | | `amountOut` | struct IQuoterV2.QuoteExactInputSingleParams | The amount of `tokenOut` that would be received | | `sqrtPriceX96After` | | The sqrt price of the pool after the swap | | `initializedTicksCrossed` | | The number of initialized ticks that the swap crossed | | `gasEstimate` | | The estimate of the gas that the swap consumes | ### quoteExactOutput ```solidity theme={null} function quoteExactOutput( bytes path, uint256 amountOut ) external returns (uint256 amountIn, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate) ``` Returns the amount in required for a given exact output swap without executing the swap #### Parameters: | Name | Type | Description | | :---------- | :------ | :-------------------------------------------------------------------------------------------------- | | `path` | bytes | The path of the swap, i.e. each token pair and the pool fee. Path must be provided in reverse order | | `amountOut` | uint256 | The amount of the last token to receive | #### Return Values: | Name | Type | Description | | :---------------------------- | :------ | :---------------------------------------------------------------------------- | | `amountIn` | bytes | The amount of first token required to be paid | | `sqrtPriceX96AfterList` | uint256 | List of the sqrt price after the swap for each pool in the path | | `initializedTicksCrossedList` | | List of the initialized ticks that the swap crossed for each pool in the path | | `gasEstimate` | | The estimate of the gas that the swap consumes | ### quoteExactOutputSingle ```solidity theme={null} function quoteExactOutputSingle( struct IQuoterV2.QuoteExactOutputSingleParams params ) external returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate) ``` Returns the amount in required to receive the given exact output amount but for a swap of a single pool #### Parameters: | Name | Type | Description | | :------- | :-------------------------------------------- | :------------------------------------------------------------------ | | `params` | struct IQuoterV2.QuoteExactOutputSingleParams | The params for the quote, encoded as `QuoteExactOutputSingleParams` | tokenIn The token being swapped in tokenOut The token being swapped out fee The fee of the token pool to consider for the pair amountOut The desired output amount sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap #### Return Values: | Name | Type | Description | | :------------------------ | :-------------------------------------------- | :---------------------------------------------------------------------------- | | `amountIn` | struct IQuoterV2.QuoteExactOutputSingleParams | The amount required as the input for the swap in order to receive `amountOut` | | `sqrtPriceX96After` | | The sqrt price of the pool after the swap | | `initializedTicksCrossed` | | The number of initialized ticks that the swap crossed | | `gasEstimate` | | The estimate of the gas that the swap consumes | # IRamsesV3PositionManager Source: https://tech.ramses.xyz/contracts/reference/periphery/interfaces/IRamsesV3PositionManager Wraps Ramses V3 positions in a non-fungible token interface which allows for them to be transferred and authorized. Extends standard position management with gauge reward claiming. ## Parameter Structs ### MintParams ```solidity theme={null} struct MintParams { address token0; address token1; int24 tickSpacing; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; } ``` ### IncreaseLiquidityParams ```solidity theme={null} struct IncreaseLiquidityParams { uint256 tokenId; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } ``` ### DecreaseLiquidityParams ```solidity theme={null} struct DecreaseLiquidityParams { uint256 tokenId; uint128 liquidity; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } ``` ### CollectParams ```solidity theme={null} struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } ``` ## Functions ### positions ```solidity theme={null} function positions( uint256 tokenId ) external view returns (address token0, address token1, int24 tickSpacing, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1) ``` Returns the position information associated with a given token ID. Throws if the token ID is not valid. #### Parameters: | Name | Type | Description | | :-------- | :------ | :----------------------------------------------- | | `tokenId` | uint256 | The ID of the token that represents the position | #### Return Values: | Name | Type | Description | | :------------------------- | :------ | :------------------------------------------------------------------------------- | | `token0` | address | The address of the token0 for a specific pool | | `token1` | address | The address of the token1 for a specific pool | | `tickSpacing` | int24 | The tick spacing of the pool | | `tickLower` | int24 | The lower end of the tick range for the position | | `tickUpper` | int24 | The higher end of the tick range for the position | | `liquidity` | uint128 | The liquidity of the position | | `feeGrowthInside0LastX128` | uint256 | The fee growth of token0 as of the last action on the individual position | | `feeGrowthInside1LastX128` | uint256 | The fee growth of token1 as of the last action on the individual position | | `tokensOwed0` | uint128 | The uncollected amount of token0 owed to the position as of the last computation | | `tokensOwed1` | uint128 | The uncollected amount of token1 owed to the position as of the last computation | ### createAndInitializePoolIfNecessary ```solidity theme={null} function createAndInitializePoolIfNecessary( address token0, address token1, int24 tickSpacing, uint160 sqrtPriceX96 ) external returns (address pool) ``` Creates a new pool if it does not exist, then initializes if not initialized This method can be bundled with mint for the first mint of a pool to create, initialize a pool and mint at the same time #### Parameters: | Name | Type | Description | | :------------- | :------ | :----------------------------------------------------------- | | `token0` | address | The contract address of token0 of the pool | | `token1` | address | The contract address of token1 of the pool | | `tickSpacing` | int24 | The tick spacing of the v3 pool for the specified token pair | | `sqrtPriceX96` | uint160 | The initial square root price of the pool as a Q64.96 value | #### Return Values: | Name | Type | Description | | :----- | :------ | :----------------------------------------------------------------------------------------------------------------------------- | | `pool` | address | Returns the pool address based on the pair of tokens and tick spacing, will return the newly created pool address if necessary | ### mint ```solidity theme={null} function mint( struct IRamsesV3PositionManager.MintParams params ) external returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1) ``` Creates a new position wrapped in a NFT Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized a method does not exist, i.e. the pool is assumed to be initialized. #### Parameters: | Name | Type | Description | | :------- | :----------------------------------------- | :--------------------------------------------------------------------------- | | `params` | struct IRamsesV3PositionManager.MintParams | The params necessary to mint a position, encoded as `MintParams` in calldata | #### Return Values: | Name | Type | Description | | :---------- | :------ | :------------------------------------------------------ | | `tokenId` | uint256 | The ID of the token that represents the minted position | | `liquidity` | uint128 | The amount of liquidity for this position | | `amount0` | uint256 | The amount of token0 | | `amount1` | uint256 | The amount of token1 | ### increaseLiquidity ```solidity theme={null} function increaseLiquidity( struct IRamsesV3PositionManager.IncreaseLiquidityParams params ) external returns (uint128 liquidity, uint256 amount0, uint256 amount1) ``` Increases the amount of liquidity in a position, with tokens paid by the `msg.sender` #### Parameters: | Name | Type | Description | | :------- | :------------------------------------------------------ | :------------------------------------------------------------------ | | `params` | struct IRamsesV3PositionManager.IncreaseLiquidityParams | tokenId The ID of the token for which liquidity is being increased, | #### Return Values: | Name | Type | Description | | :---------- | :------ | :--------------------------------------------------- | | `liquidity` | uint128 | The new liquidity amount as a result of the increase | | `amount0` | uint256 | The amount of token0 to achieve resulting liquidity | | `amount1` | uint256 | The amount of token1 to achieve resulting liquidity | ### decreaseLiquidity ```solidity theme={null} function decreaseLiquidity( struct IRamsesV3PositionManager.DecreaseLiquidityParams params ) external returns (uint256 amount0, uint256 amount1) ``` Decreases the amount of liquidity in a position and accounts it to the position #### Parameters: | Name | Type | Description | | :------- | :------------------------------------------------------ | :----------------------------------------------------------------- | | `params` | struct IRamsesV3PositionManager.DecreaseLiquidityParams | tokenId The ID of the token for which liquidity is being decreased | #### Return Values: | Name | Type | Description | | :-------- | :------ | :------------------------------------- | | `amount0` | uint256 | The amount of token0 sent to recipient | | `amount1` | uint256 | The amount of token1 sent to recipient | ### collect ```solidity theme={null} function collect( struct IRamsesV3PositionManager.CollectParams params ) external returns (uint256 amount0, uint256 amount1) ``` Collects up to a maximum amount of fees owed to a specific position to the recipient #### Parameters: | Name | Type | Description | | :------- | :-------------------------------------------- | :-------------------------------------------------------------- | | `params` | struct IRamsesV3PositionManager.CollectParams | tokenId The ID of the NFT for which tokens are being collected, | #### Return Values: | Name | Type | Description | | :-------- | :------ | :------------------------------------- | | `amount0` | uint256 | The amount of fees collected in token0 | | `amount1` | uint256 | The amount of fees collected in token1 | ### burn ```solidity theme={null} function burn( uint256 tokenId ) external ``` Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens must be collected first. #### Parameters: | Name | Type | Description | | :-------- | :------ | :--------------------------------------- | | `tokenId` | uint256 | The ID of the token that is being burned | ### getReward ```solidity theme={null} function getReward( uint256 tokenId, address[] tokens ) external ``` Claims gauge rewards for a given position NFT. Ramses-specific. #### Parameters: | Name | Type | Description | | :-------- | :--------- | :--------------------------------------------- | | `tokenId` | uint256 | The ID of the token for which to claim rewards | | `tokens` | address\[] | The reward token addresses to claim | ## Events ### IncreaseLiquidity ```solidity theme={null} event IncreaseLiquidity( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ) ``` Emitted when liquidity is increased for a position NFT Also emitted when a token is minted #### Parameters: | Name | Type | Description | | :---------- | :------ | :--------------------------------------------------------------- | | `tokenId` | uint256 | The ID of the token for which liquidity was increased | | `liquidity` | uint128 | The amount by which liquidity for the NFT position was increased | | `amount0` | uint256 | The amount of token0 that was paid for the increase in liquidity | | `amount1` | uint256 | The amount of token1 that was paid for the increase in liquidity | ### DecreaseLiquidity ```solidity theme={null} event DecreaseLiquidity( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ) ``` Emitted when liquidity is decreased for a position NFT #### Parameters: | Name | Type | Description | | :---------- | :------ | :-------------------------------------------------------------------- | | `tokenId` | uint256 | The ID of the token for which liquidity was decreased | | `liquidity` | uint128 | The amount by which liquidity for the NFT position was decreased | | `amount0` | uint256 | The amount of token0 that was accounted for the decrease in liquidity | | `amount1` | uint256 | The amount of token1 that was accounted for the decrease in liquidity | ### Collect ```solidity theme={null} event Collect( uint256 tokenId, address recipient, uint256 amount0, uint256 amount1 ) ``` Emitted when tokens are collected for a position NFT The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior #### Parameters: | Name | Type | Description | | :---------- | :------ | :------------------------------------------------------------- | | `tokenId` | uint256 | The ID of the token for which underlying tokens were collected | | `recipient` | address | The address of the account that received the collected tokens | | `amount0` | uint256 | The amount of token0 owed to the position that was collected | | `amount1` | uint256 | The amount of token1 owed to the position that was collected | # ISelfPermit Source: https://tech.ramses.xyz/contracts/reference/periphery/interfaces/ISelfPermit Functionality to call permit on any EIP-2612-compliant token for use in the route ## Functions ### selfPermit ```solidity theme={null} function selfPermit( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external ``` Permits this contract to spend a given token from `msg.sender` The `owner` is always msg.sender and the `spender` is always address(this). #### Parameters: | Name | Type | Description | | :--------- | :------ | :------------------------------------------------------------------------------ | | `token` | address | The address of the token spent | | `value` | uint256 | The amount that can be spent of token | | `deadline` | uint256 | A timestamp, the current blocktime must be less than or equal to this timestamp | | `v` | uint8 | Must produce valid secp256k1 signature from the holder along with `r` and `s` | | `r` | bytes32 | Must produce valid secp256k1 signature from the holder along with `v` and `s` | | `s` | bytes32 | Must produce valid secp256k1 signature from the holder along with `r` and `v` | ### selfPermitIfNecessary ```solidity theme={null} function selfPermitIfNecessary( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external ``` Permits this contract to spend a given token from `msg.sender` The `owner` is always msg.sender and the `spender` is always address(this). Can be used instead of #selfPermit to prevent calls from failing due to a frontrun of a call to #selfPermit #### Parameters: | Name | Type | Description | | :--------- | :------ | :------------------------------------------------------------------------------ | | `token` | address | The address of the token spent | | `value` | uint256 | The amount that can be spent of token | | `deadline` | uint256 | A timestamp, the current blocktime must be less than or equal to this timestamp | | `v` | uint8 | Must produce valid secp256k1 signature from the holder along with `r` and `s` | | `r` | bytes32 | Must produce valid secp256k1 signature from the holder along with `v` and `s` | | `s` | bytes32 | Must produce valid secp256k1 signature from the holder along with `r` and `v` | ### selfPermitAllowed ```solidity theme={null} function selfPermitAllowed( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external ``` Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter The `owner` is always msg.sender and the `spender` is always address(this) #### Parameters: | Name | Type | Description | | :------- | :------ | :---------------------------------------------------------------------------- | | `token` | address | The address of the token spent | | `nonce` | uint256 | The current nonce of the owner | | `expiry` | uint256 | The timestamp at which the permit is no longer valid | | `v` | uint8 | Must produce valid secp256k1 signature from the holder along with `r` and `s` | | `r` | bytes32 | Must produce valid secp256k1 signature from the holder along with `v` and `s` | | `s` | bytes32 | Must produce valid secp256k1 signature from the holder along with `r` and `v` | ### selfPermitAllowedIfNecessary ```solidity theme={null} function selfPermitAllowedIfNecessary( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external ``` Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter The `owner` is always msg.sender and the `spender` is always address(this) Can be used instead of #selfPermitAllowed to prevent calls from failing due to a frontrun of a call to #selfPermitAllowed. #### Parameters: | Name | Type | Description | | :------- | :------ | :---------------------------------------------------------------------------- | | `token` | address | The address of the token spent | | `nonce` | uint256 | The current nonce of the owner | | `expiry` | uint256 | The timestamp at which the permit is no longer valid | | `v` | uint8 | Must produce valid secp256k1 signature from the holder along with `r` and `s` | | `r` | bytes32 | Must produce valid secp256k1 signature from the holder along with `v` and `s` | | `s` | bytes32 | Must produce valid secp256k1 signature from the holder along with `r` and `v` | # ISwapRouter Source: https://tech.ramses.xyz/contracts/reference/periphery/interfaces/ISwapRouter Functions for swapping tokens via Ramses V3 ## Parameter Structs ### ExactInputSingleParams ```solidity theme={null} struct ExactInputSingleParams { address tokenIn; address tokenOut; int24 tickSpacing; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } ``` ### ExactInputParams ```solidity theme={null} struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } ``` ### ExactOutputSingleParams ```solidity theme={null} struct ExactOutputSingleParams { address tokenIn; address tokenOut; int24 tickSpacing; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } ``` ### ExactOutputParams ```solidity theme={null} struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } ``` ## Functions ### exactInputSingle ```solidity theme={null} function exactInputSingle( struct ISwapRouter.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 ISwapRouter.ExactInputSingleParams | The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata | #### Return Values: | Name | Type | Description | | :---------- | :---------------------------------------- | :------------------------------- | | `amountOut` | struct ISwapRouter.ExactInputSingleParams | The amount of the received token | ### exactInput ```solidity theme={null} function exactInput( struct ISwapRouter.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 ISwapRouter.ExactInputParams | The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata | #### Return Values: | Name | Type | Description | | :---------- | :---------------------------------- | :------------------------------- | | `amountOut` | struct ISwapRouter.ExactInputParams | The amount of the received token | ### exactOutputSingle ```solidity theme={null} function exactOutputSingle( struct ISwapRouter.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 ISwapRouter.ExactOutputSingleParams | The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata | #### Return Values: | Name | Type | Description | | :--------- | :----------------------------------------- | :---------------------------- | | `amountIn` | struct ISwapRouter.ExactOutputSingleParams | The amount of the input token | ### exactOutput ```solidity theme={null} function exactOutput( struct ISwapRouter.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 ISwapRouter.ExactOutputParams | The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata | #### Return Values: | Name | Type | Description | | :--------- | :----------------------------------- | :---------------------------- | | `amountIn` | struct ISwapRouter.ExactOutputParams | The amount of the input token | # ITickLens Source: https://tech.ramses.xyz/contracts/reference/periphery/interfaces/ITickLens Provides functions for fetching chunks of tick data for a pool This avoids the waterfall of fetching the tick bitmap, parsing the bitmap to know which ticks to fetch, and then sending additional multicalls to fetch the tick data ## Functions ### getPopulatedTicksInWord ```solidity theme={null} function getPopulatedTicksInWord( address pool, int16 tickBitmapIndex ) external returns (struct ITickLens.PopulatedTick[] populatedTicks) ``` Get all the tick data for the populated ticks from a word of the tick bitmap of a pool #### Parameters: | Name | Type | Description | | :---------------- | :------ | :------------------------------------------------------------------------------------------------------- | | `pool` | address | The address of the pool for which to fetch populated tick data | | `tickBitmapIndex` | int16 | The index of the word in the tick bitmap for which to parse the bitmap and fetch all the populated ticks | #### Return Values: | Name | Type | Description | | :--------------- | :------------------------- | :---------------------------------------------------------- | | `populatedTicks` | ITickLens.PopulatedTick\[] | An array of tick data for the given word in the tick bitmap | # IERC1271 Source: https://tech.ramses.xyz/contracts/reference/periphery/interfaces/external/IERC1271 Interface that verifies provided signature for the data Interface defined by EIP-1271 ## Functions ### isValidSignature ```solidity theme={null} function isValidSignature( bytes32 hash, bytes signature ) external returns (bytes4 magicValue) ``` Returns whether the provided signature is valid for the provided data MUST return the bytes4 magic value 0x1626ba7e when function passes. MUST NOT modify state (using STATICCALL for solc \< 0.5, view modifier for solc > 0.5). MUST allow external calls. #### Parameters: | Name | Type | Description | | :---------- | :------ | :------------------------------------------ | | `hash` | bytes32 | Hash of the data to be signed | | `signature` | bytes | Signature byte array associated with \_data | #### Return Values: | Name | Type | Description | | :----------- | :------ | :-------------------------------- | | `magicValue` | bytes32 | The bytes4 magic value 0x1626ba7e | # IERC20PermitAllowed Source: https://tech.ramses.xyz/contracts/reference/periphery/interfaces/external/IERC20PermitAllowed Interface used by DAI/CHAI for permit ## Functions ### permit ```solidity theme={null} function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) external ``` Approve the spender to spend some tokens via the holder signature This is the permit interface used by DAI and CHAI #### Parameters: | Name | Type | Description | | :-------- | :------ | :---------------------------------------------------------------------------- | | `holder` | address | The address of the token holder, the token owner | | `spender` | address | The address of the token spender | | `nonce` | uint256 | The holder's nonce, increases at each call to permit | | `expiry` | uint256 | The timestamp at which the permit is no longer valid | | `allowed` | bool | Boolean that sets approval amount, true for type(uint256).max and false for 0 | | `v` | uint8 | Must produce valid secp256k1 signature from the holder along with `r` and `s` | | `r` | bytes32 | Must produce valid secp256k1 signature from the holder along with `v` and `s` | | `s` | bytes32 | Must produce valid secp256k1 signature from the holder along with `r` and `v` | # IWETH9 Source: https://tech.ramses.xyz/contracts/reference/periphery/interfaces/external/IWETH9 ## Functions ### deposit ```solidity theme={null} function deposit( ) external ``` Deposit ether to get wrapped ether ### withdraw ```solidity theme={null} function withdraw( ) external ``` Withdraw wrapped ether to get ether # Quoter Source: https://tech.ramses.xyz/contracts/reference/periphery/lens/Quoter Allows getting the expected amount out or amount in for a given swap without executing the swap These functions are not gas efficient and should *not* be called on chain. Instead, optimistically execute the swap and check the amounts in the callback. ## Functions ### constructor ```solidity theme={null} function constructor( ) public ``` ### uniswapV3SwapCallback ```solidity theme={null} function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes data ) external ``` Called to `msg.sender` after executing a swap via IRamsesV3Pool#swap. In the implementation you must pay the pool tokens owed for the swap. The caller of this method must be checked to be a RamsesV3Pool deployed by the canonical RamsesV3Factory. amount0Delta and amount1Delta can both be 0 if no tokens were swapped. #### Parameters: | Name | Type | Description | | :------------- | :----- | :------------------------------------------------------------------------------------------ | | `amount0Delta` | int256 | The amount of token0 that was sent (negative) or must be received (positive) by the pool by | the end of the swap. If positive, the callback must send that amount of token0 to the pool. |`amount1Delta` | int256 | The amount of token1 that was sent (negative) or must be received (positive) by the pool by the end of the swap. If positive, the callback must send that amount of token1 to the pool. |`data` | bytes | Any data passed through by the caller via the IRamsesV3PoolActions#swap call ### quoteExactInputSingle ```solidity theme={null} function quoteExactInputSingle( address tokenIn, address tokenOut, int24 tickSpacing, uint256 amountIn, uint160 sqrtPriceLimitX96 ) public returns (uint256 amountOut) ``` Returns the amount out received for a given exact input but for a swap of a single pool #### Parameters: | Name | Type | Description | | :------------------ | :------ | :-------------------------------------------------------------- | | `tokenIn` | address | The token being swapped in | | `tokenOut` | address | The token being swapped out | | `tickSpacing` | int24 | The tick spacing of the pool | | `amountIn` | uint256 | The desired input amount | | `sqrtPriceLimitX96` | uint160 | The price limit of the pool that cannot be exceeded by the swap | #### Return Values: | Name | Type | Description | | :---------- | :------ | :---------------------------------------------- | | `amountOut` | uint256 | The amount of `tokenOut` that would be received | ### quoteExactInput ```solidity theme={null} function quoteExactInput( bytes path, uint256 amountIn ) external returns (uint256 amountOut) ``` Returns the amount out received for a given exact input swap without executing the swap #### Parameters: | Name | Type | Description | | :--------- | :------ | :---------------------------------------------------------- | | `path` | bytes | The path of the swap, i.e. each token pair and the pool fee | | `amountIn` | uint256 | The amount of the first token to swap | #### Return Values: | Name | Type | Description | | :---------- | :------ | :-------------------------------------------------- | | `amountOut` | uint256 | The amount of the last token that would be received | ### quoteExactOutputSingle ```solidity theme={null} function quoteExactOutputSingle( address tokenIn, address tokenOut, int24 tickSpacing, uint256 amountOut, uint160 sqrtPriceLimitX96 ) public returns (uint256 amountIn) ``` Returns the amount in required to receive the given exact output amount but for a swap of a single pool #### Parameters: | Name | Type | Description | | :------------------ | :------ | :-------------------------------------------------------------- | | `tokenIn` | address | The token being swapped in | | `tokenOut` | address | The token being swapped out | | `tickSpacing` | int24 | The tick spacing of the pool | | `amountOut` | uint256 | The desired output amount | | `sqrtPriceLimitX96` | uint160 | The price limit of the pool that cannot be exceeded by the swap | #### Return Values: | Name | Type | Description | | :--------- | :------ | :---------------------------------------------------------------------------- | | `amountIn` | uint256 | The amount required as the input for the swap in order to receive `amountOut` | ### quoteExactOutput ```solidity theme={null} function quoteExactOutput( bytes path, uint256 amountOut ) external returns (uint256 amountIn) ``` Returns the amount in required for a given exact output swap without executing the swap #### Parameters: | Name | Type | Description | | :---------- | :------ | :---------------------------------------------------------- | | `path` | bytes | The path of the swap, i.e. each token pair and the pool fee | | `amountOut` | uint256 | The amount of the last token to receive | #### Return Values: | Name | Type | Description | | :--------- | :------ | :-------------------------------------------- | | `amountIn` | uint256 | The amount of first token required to be paid | # QuoterV2 Source: https://tech.ramses.xyz/contracts/reference/periphery/lens/QuoterV2 Allows getting the expected amount out or amount in for a given swap without executing the swap These functions are not gas efficient and should *not* be called on chain. Instead, optimistically execute the swap and check the amounts in the callback. ## Functions ### constructor ```solidity theme={null} function constructor( ) public ``` ### uniswapV3SwapCallback ```solidity theme={null} function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes data ) external view override ``` Called to `msg.sender` after executing a swap via IRamsesV3Pool#swap. In the implementation you must pay the pool tokens owed for the swap. The caller of this method must be checked to be a RamsesV3Pool deployed by the canonical RamsesV3Factory. amount0Delta and amount1Delta can both be 0 if no tokens were swapped. #### Parameters: | Name | Type | Description | | :------------- | :----- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `amount0Delta` | int256 | The amount of token0 that was sent (negative) or must be received (positive) by the pool by the end of the swap. If positive, the callback must send that amount of token0 to the pool. | | `amount1Delta` | int256 | The amount of token1 that was sent (negative) or must be received (positive) by the pool by the end of the swap. If positive, the callback must send that amount of token1 to the pool. | | `data` | bytes | Any data passed through by the caller via the IRamsesV3PoolActions#swap call. | ### quoteExactInputSingle ```solidity theme={null} function quoteExactInputSingle( ) public override returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate) ``` ### quoteExactInput ```solidity theme={null} function quoteExactInput( ) public override returns (uint256 amountOut, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate) ``` ### quoteExactOutputSingle ```solidity theme={null} function quoteExactOutputSingle( ) public override returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate) ``` ### quoteExactOutput ```solidity theme={null} function quoteExactOutput( ) public override returns (uint256 amountIn, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate) ``` # TickLens Source: https://tech.ramses.xyz/contracts/reference/periphery/lens/TickLens ## Functions ### getPopulatedTicksInWord ```solidity theme={null} function getPopulatedTicksInWord( address pool, int16 tickBitmapIndex ) public returns (struct ITickLens.PopulatedTick[] populatedTicks) ``` Get all the tick data for the populated ticks from a word of the tick bitmap of a pool #### Parameters: | Name | Type | Description | | :---------------- | :------ | :------------------------------------------------------------------------------------------------------- | | `pool` | address | The address of the pool for which to fetch populated tick data | | `tickBitmapIndex` | int16 | The index of the word in the tick bitmap for which to parse the bitmap and fetch all the populated ticks | #### Return Values: | Name | Type | Description | | :--------------- | :------------------------- | :---------------------------------------------------------- | | `populatedTicks` | ITickLens.PopulatedTick\[] | An array of tick data for the given word in the tick bitmap | # Base64 Source: https://tech.ramses.xyz/contracts/reference/periphery/libraries/Base64 Provides a function for encoding some bytes in base64 ## Functions ### encode ```solidity theme={null} function encode( bytes memory data ) internal pure returns (string memory) ``` Encodes some bytes to the base64 representation # BytesLib Source: https://tech.ramses.xyz/contracts/reference/periphery/libraries/BytesLib ## Functions ### slice ```solidity theme={null} function slice( ) internal returns (bytes) ``` ### toAddress ```solidity theme={null} function toAddress( ) internal returns (address) ``` ### toUint24 ```solidity theme={null} function toUint24( ) internal returns (uint24) ``` # ChainId Source: https://tech.ramses.xyz/contracts/reference/periphery/libraries/ChainId ## Functions ### get ```solidity theme={null} function get( ) internal returns (uint256 chainId) ``` Gets the current chain ID #### Return Values: | Name | Type | Description | | :-------- | :------ | :------------------- | | `chainId` | uint256 | The current chain ID | # HexStrings Source: https://tech.ramses.xyz/contracts/reference/periphery/libraries/HexStrings ## Functions ### toHexString ```solidity theme={null} function toHexString( ) internal returns (string) ``` Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. Credit to Open Zeppelin under MIT license [https://github.com/OpenZeppelin/openzeppelin-contracts/blob/243adff49ce1700e0ecb99fe522fb16cff1d1ddc/contracts/utils/Strings.sol#L55](https://github.com/OpenZeppelin/openzeppelin-contracts/blob/243adff49ce1700e0ecb99fe522fb16cff1d1ddc/contracts/utils/Strings.sol#L55) ### toHexStringNoPrefix ```solidity theme={null} function toHexStringNoPrefix( ) internal returns (string) ``` # LiquidityAmounts Source: https://tech.ramses.xyz/contracts/reference/periphery/libraries/LiquidityAmounts Provides functions for computing liquidity amounts from token amounts and prices ## Functions ### getLiquidityForAmount0 ```solidity theme={null} function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal returns (uint128 liquidity) ``` Computes the amount of liquidity received for a given amount of token0 and price range Calculates amount0 \_ (sqrt(upper) \_ sqrt(lower)) / (sqrt(upper) - sqrt(lower)) #### Parameters: | Name | Type | Description | | :-------------- | :------ | :------------------------------------------------- | | `sqrtRatioAX96` | uint160 | A sqrt price representing the first tick boundary | | `sqrtRatioBX96` | uint160 | A sqrt price representing the second tick boundary | | `amount0` | uint256 | The amount0 being sent in | #### Return Values: | Name | Type | Description | | :---------- | :------ | :------------------------------- | | `liquidity` | uint128 | The amount of returned liquidity | ### getLiquidityForAmount1 ```solidity theme={null} function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal returns (uint128 liquidity) ``` Computes the amount of liquidity received for a given amount of token1 and price range Calculates amount1 / (sqrt(upper) - sqrt(lower)). #### Parameters: | Name | Type | Description | | :-------------- | :------ | :------------------------------------------------- | | `sqrtRatioAX96` | uint160 | A sqrt price representing the first tick boundary | | `sqrtRatioBX96` | uint160 | A sqrt price representing the second tick boundary | | `amount1` | uint256 | The amount1 being sent in | #### Return Values: | Name | Type | Description | | :---------- | :------ | :------------------------------- | | `liquidity` | uint128 | The amount of returned liquidity | ### getLiquidityForAmounts ```solidity theme={null} function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal returns (uint128 liquidity) ``` Computes the maximum amount of liquidity received for a given amount of token0, token1, the current pool prices and the prices at the tick boundaries #### Parameters: | Name | Type | Description | | :-------------- | :------ | :------------------------------------------------- | | `sqrtRatioX96` | uint160 | A sqrt price representing the current pool prices | | `sqrtRatioAX96` | uint160 | A sqrt price representing the first tick boundary | | `sqrtRatioBX96` | uint160 | A sqrt price representing the second tick boundary | | `amount0` | uint256 | The amount of token0 being sent in | | `amount1` | uint256 | The amount of token1 being sent in | #### Return Values: | Name | Type | Description | | :---------- | :------ | :--------------------------------------- | | `liquidity` | uint128 | The maximum amount of liquidity received | ### getAmount0ForLiquidity ```solidity theme={null} function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal returns (uint256 amount0) ``` Computes the amount of token0 for a given amount of liquidity and a price range #### Parameters: | Name | Type | Description | | :-------------- | :------ | :------------------------------------------------- | | `sqrtRatioAX96` | uint160 | A sqrt price representing the first tick boundary | | `sqrtRatioBX96` | uint160 | A sqrt price representing the second tick boundary | | `liquidity` | uint128 | The liquidity being valued | #### Return Values: | Name | Type | Description | | :-------- | :------ | :------------------- | | `amount0` | uint256 | The amount of token0 | ### getAmount1ForLiquidity ```solidity theme={null} function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal returns (uint256 amount1) ``` Computes the amount of token1 for a given amount of liquidity and a price range #### Parameters: | Name | Type | Description | | :-------------- | :------ | :------------------------------------------------- | | `sqrtRatioAX96` | uint160 | A sqrt price representing the first tick boundary | | `sqrtRatioBX96` | uint160 | A sqrt price representing the second tick boundary | | `liquidity` | uint128 | The liquidity being valued | #### Return Values: | Name | Type | Description | | :-------- | :------ | :------------------- | | `amount1` | uint256 | The amount of token1 | ### getAmountsForLiquidity ```solidity theme={null} function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal returns (uint256 amount0, uint256 amount1) ``` Computes the token0 and token1 value for a given amount of liquidity, the current pool prices and the prices at the tick boundaries #### Parameters: | Name | Type | Description | | :-------------- | :------ | :------------------------------------------------- | | `sqrtRatioX96` | uint160 | A sqrt price representing the current pool prices | | `sqrtRatioAX96` | uint160 | A sqrt price representing the first tick boundary | | `sqrtRatioBX96` | uint160 | A sqrt price representing the second tick boundary | | `liquidity` | uint128 | The liquidity being valued | #### Return Values: | Name | Type | Description | | :-------- | :------ | :------------------- | | `amount0` | uint256 | The amount of token0 | | `amount1` | uint256 | The amount of token1 | # NFTDescriptor Source: https://tech.ramses.xyz/contracts/reference/periphery/libraries/NFTDescriptor ## Functions ### constructTokenURI ```solidity theme={null} function constructTokenURI( ) public returns (string) ``` ### escapeQuotes ```solidity theme={null} function escapeQuotes( ) internal returns (string) ``` ### tickToDecimalString ```solidity theme={null} function tickToDecimalString( ) internal returns (string) ``` ### fixedPointToDecimalString ```solidity theme={null} function fixedPointToDecimalString( ) internal returns (string) ``` ### feeToPercentString ```solidity theme={null} function feeToPercentString( ) internal returns (string) ``` ### addressToString ```solidity theme={null} function addressToString( ) internal returns (string) ``` ### generateSVGImage ```solidity theme={null} function generateSVGImage( ) internal returns (string svg) ``` ### tokenToColorHex ```solidity theme={null} function tokenToColorHex( ) internal returns (string str) ``` ### getCircleCoord ```solidity theme={null} function getCircleCoord( ) internal returns (uint256) ``` ### sliceTokenHex ```solidity theme={null} function sliceTokenHex( ) internal returns (uint256) ``` # NFTSVG Source: https://tech.ramses.xyz/contracts/reference/periphery/libraries/NFTSVG Provides a function for generating an SVG associated with a Uniswap NFT ## Functions ### generateSVG ```solidity theme={null} function generateSVG( ) internal returns (string svg) ``` ### getCurve ```solidity theme={null} function getCurve( ) internal returns (string curve) ``` ### generateSVGCurveCircle ```solidity theme={null} function generateSVGCurveCircle( ) internal returns (string svg) ``` ### rangeLocation ```solidity theme={null} function rangeLocation( ) internal returns (string, string) ``` ### isRare ```solidity theme={null} function isRare( ) internal returns (bool) ``` # Path Source: https://tech.ramses.xyz/contracts/reference/periphery/libraries/Path ## Functions ### hasMultiplePools ```solidity theme={null} function hasMultiplePools( bytes path ) internal returns (bool) ``` Returns true iff the path contains two or more pools #### Parameters: | Name | Type | Description | | :----- | :---- | :-------------------- | | `path` | bytes | The encoded swap path | #### Return Values: | Type | Description | | :--- | :-------------------------------------------------- | | bool | if path contains two or more pools, otherwise false | ### decodeFirstPool ```solidity theme={null} function decodeFirstPool( bytes path ) internal returns (address tokenA, address tokenB, uint24 fee) ``` Decodes the first pool in path #### Parameters: | Name | Type | Description | | :----- | :---- | :-------------------------- | | `path` | bytes | The bytes encoded swap path | #### Return Values: | Name | Type | Description | | :------- | :------ | :--------------------------------- | | `tokenA` | address | The first token of the given pool | | `tokenB` | address | The second token of the given pool | | `fee` | uint24 | The fee level of the pool | ### getFirstPool ```solidity theme={null} function getFirstPool( bytes path ) internal returns (bytes) ``` Gets the segment corresponding to the first pool in the path #### Parameters: | Name | Type | Description | | :----- | :---- | :-------------------------- | | `path` | bytes | The bytes encoded swap path | #### Return Values: | Type | Description | | :---- | :------------------------------------------------------------------------- | | bytes | segment containing all data necessary to target the first pool in the path | ### skipToken ```solidity theme={null} function skipToken( bytes path ) internal returns (bytes) ``` Skips a token + fee element from the buffer and returns the remainder #### Parameters: | Name | Type | Description | | :----- | :---- | :------------ | | `path` | bytes | The swap path | #### Return Values: | Type | Description | | :---- | :----------------------------------------- | | bytes | remaining token + fee elements in the path | # PoolTicksCounter Source: https://tech.ramses.xyz/contracts/reference/periphery/libraries/PoolTicksCounter ## Functions ### countInitializedTicksCrossed ```solidity theme={null} function countInitializedTicksCrossed( ) internal view returns (uint32 initializedTicksCrossed) ``` This function counts the number of initialized ticks that would incur a gas cost between tickBefore and tickAfter. When tickBefore and/or tickAfter themselves are initialized, the logic over whether we should count them depends on the direction of the swap. If we are swapping upwards (tickAfter > tickBefore) we don't want to count tickBefore but we do want to count tickAfter. The opposite is true if we are swapping downwards. # PositionKey Source: https://tech.ramses.xyz/contracts/reference/periphery/libraries/PositionKey ## Functions ### compute ```solidity theme={null} function compute( ) internal returns (bytes32) ``` Returns the key of the position in the core library # TokenRatioSortOrder Source: https://tech.ramses.xyz/contracts/reference/periphery/libraries/TokenRatioSortOrder # TokenRatioSortOrder ```solidity theme={null} library TokenRatioSortOrder { int256 constant NUMERATOR_MOST = 300; int256 constant NUMERATOR_MORE = 200; int256 constant NUMERATOR = 100; int256 constant DENOMINATOR_MOST = -300; int256 constant DENOMINATOR_MORE = -200; int256 constant DENOMINATOR = -100; } ``` # TransferHelper Source: https://tech.ramses.xyz/contracts/reference/periphery/libraries/TransferHelper ## Functions ### safeTransferFrom ```solidity theme={null} function safeTransferFrom( address token, address from, address to, uint256 value ) internal ``` Transfers tokens from the targeted address to the given destination Errors with 'STF' if transfer fails #### Parameters: | Name | Type | Description | | :------ | :------ | :---------------------------------------------------------------- | | `token` | address | The contract address of the token to be transferred | | `from` | address | The originating address from which the tokens will be transferred | | `to` | address | The destination address of the transfer | | `value` | uint256 | The amount to be transferred | ### safeTransfer ```solidity theme={null} function safeTransfer( address token, address to, uint256 value ) internal ``` Transfers tokens from msg.sender to a recipient Errors with ST if transfer fails #### Parameters: | Name | Type | Description | | :------ | :------ | :---------------------------------------------------------- | | `token` | address | The contract address of the token which will be transferred | | `to` | address | The recipient of the transfer | | `value` | uint256 | The value of the transfer | ### safeApprove ```solidity theme={null} function safeApprove( address token, address to, uint256 value ) internal ``` Approves the stipulated contract to spend the given allowance in the given token Errors with 'SA' if transfer fails #### Parameters: | Name | Type | Description | | :------ | :------ | :---------------------------------------------------------------- | | `token` | address | The contract address of the token to be approved | | `to` | address | The target of the approval | | `value` | uint256 | The amount of the given token the target will be allowed to spend | ### safeTransferETH ```solidity theme={null} function safeTransferETH( address to, uint256 value ) internal ``` Transfers ETH to the recipient address Fails with `STE` #### Parameters: | Name | Type | Description | | :------ | :------ | :------------------------------ | | `to` | address | The destination of the transfer | | `value` | uint256 | The value to be transferred | # Sarcophagus Source: https://tech.ramses.xyz/contracts/reference/sarcophagus Technical specification and searcher integration guide for the permissionless r33-for-protocol-fees mechanism on Robinhood Chain. Sarcophagus is a permissionless, fixed-cost mechanism for exchanging **r33** for ERC-20 protocol fees accumulated by the contract. A successful caller sends the current r33 threshold directly to the dead address and receives the Sarcophagus's entire balance of every selected fee token. Any address can call `bury` with a valid nonce, token list, minimum outputs, r33 balance, and allowance. The r33 payment and every selected token transfer succeed together or the whole transaction reverts. There is no oracle or auction curve. The owner-configured r33 threshold is the contract's only exchange price. Callers choose which ERC-20 balances to claim, up to the current `maxTokenClaim` value. The Robinhood contract is deployed and verified. A viable claim exists only after ERC-20 fees have reached it and their realizable value exceeds the r33 cost, gas, slippage, and execution risk. Fee routing and balances must be checked live. ## Robinhood deployment The following values were read at Robinhood block `38,278,392` on **August 16, 2026**. Mutable values can change after this block. | Field | Value | | ------------------------ | ------------------------------------------------------------------------------------------------------------ | | Network | Robinhood Chain | | Chain ID | `4663` | | Public RPC | `https://rpc.mainnet.chain.robinhood.com` | | Sarcophagus | [`0x7125...Aba3e`](https://robinhoodchain.blockscout.com/address/0x712567e71a93Fb111510A790cAf3469677aAba3e) | | r33 | [`0x4e51...0FeeE`](https://robinhoodchain.blockscout.com/address/0x4e5195469A0360f5dfe811730C9CCaCFF0a0FeeE) | | r33 token metadata | `xRAM Liquid Staking Token` / `r33` / 18 decimals | | Owner | [`0x20D6...BE1A`](https://robinhoodchain.blockscout.com/address/0x20D630cF1f5628285BfB91DfaC8C89eB9087BE1A) | | r33 threshold | `3,333 r33` (`3_333e18` raw units) | | Maximum tokens per claim | `100` | | Nonce | `1` | | r33 destination | [`0x0000...dEaD`](https://robinhoodchain.blockscout.com/address/0x000000000000000000000000000000000000dEaD) | ```text Canonical addresses theme={null} SARCOPHAGUS=0x712567e71a93Fb111510A790cAf3469677aAba3e R33_TOKEN=0x4e5195469A0360f5dfe811730C9CCaCFF0a0FeeE OWNER=0x20D630cF1f5628285BfB91DfaC8C89eB9087BE1A R33_DEAD_ADDRESS=0x000000000000000000000000000000000000dEaD ``` `exchangeAmountThreshold`, `maxTokenClaim`, `nonce`, token balances, and the caller's r33 allowance are execution inputs—not constants. Read them at one block, build the call, and simulate the exact transaction against current state. ## Execution flow ```mermaid theme={null} flowchart LR A["Protocol fee sources"] -->|"ERC-20 fees"| B["Sarcophagus balances"] S["Searcher"] -->|"read nonce, threshold, limits, balances"| B S -->|"approve r33"| R["r33 token"] S -->|"bury(nonce, tokens, minimums)"| B R -->|"exact threshold"| D["0x...dEaD"] B -->|"full selected balances"| S ``` `bury` is an atomic **first-valid-transaction** race. It is not a Dutch auction, sealed-bid auction, or oracle-priced swap. The first included transaction that satisfies every check consumes the current nonce and claims the selected balances. The token list must be non-empty, no longer than `maxTokenClaim`, and the same length as the minimum-output array. The supplied nonce must equal `nonce()`. The contract increments it for the successful claim. A later revert rolls the increment back with the rest of the transaction. `safeTransferFrom` moves exactly `exchangeAmountThreshold` r33 from the caller directly to `0x000...dEaD`. For each selected token, the contract reads its complete Sarcophagus balance, checks it against the paired minimum, and transfers that full balance to the caller. A successful call emits `Buried(nonce, user, tokensClaimed)` using the nonce supplied by the caller. This Robinhood deployment sends r33 to `0x000...dEaD`; it does not call an r33 `burn` function. The transfer removes the tokens from ordinary circulation but does not reduce the ERC-20 `totalSupply` value. ## Searcher runbook ### 1. Discover candidate fee assets Sarcophagus does **not** maintain an enumerable token registry. Searchers must discover candidates from trusted Ramses fee-source configuration, ERC-20 `Transfer` logs into the contract, or another independently maintained index. Treat discovery as untrusted input: * Confirm every candidate is the intended token contract on chain `4663`. * Read `balanceOf(Sarcophagus)` at the same pinned block used for the other quote inputs. * Exclude zero balances and tokens with incompatible or reverting ERC-20 behavior. * Deduplicate token addresses before constructing the call. * Do not assume the contract holds only assets shown by a block explorer UI. ### 2. Price the opportunity For candidate tokens (T\_i), a claim is economically attractive only when the expected realizable output exceeds all costs: $$ \sum_i \operatorname{value}(balance_i) > \operatorname{value}(r33Threshold) + gas + slippage + risk $$ The contract does not calculate this inequality and does not validate token prices. Searchers are responsible for pricing, liquidity checks, gas estimation, and downstream execution. ### 3. Set minimum outputs `_minAmountsOut[i]` is compared with the **raw Sarcophagus balance** of `_tokens[i]`. It is not a price, quote, or decimal-normalized value. Use minimums to protect against another transaction reducing a selected balance before inclusion. Setting every minimum to zero removes that protection and can allow the call to pay r33 while receiving no value from one or more selected tokens. ### 4. Approve and simulate The caller needs at least the threshold amount of r33 and sufficient allowance for Sarcophagus. Approval is made on the r33 token; r33 should not be transferred to Sarcophagus manually. Simulate the exact `bury` call from the intended sender immediately before submission. A successful simulation is only a point-in-time result: another claim or owner update can still make the pending transaction revert. ### 5. Submit competitively Public-mempool transactions reveal the selected assets and minimums. Another searcher can independently submit a valid claim with the same nonce if it has r33 and allowance. The contract does not reserve an opportunity for the first observer. After inclusion, verify the transaction status and `Buried` event rather than inferring success from submission alone. ## TypeScript example This `viem` example pins quote reads to one block, applies a 0.5% balance buffer, checks allowance, and simulates the exact call. Candidate-token discovery and economic pricing are intentionally separate. ```ts theme={null} import { createPublicClient, createWalletClient, http, parseAbi } from 'viem' import { privateKeyToAccount } from 'viem/accounts' const robinhood = { id: 4663, name: 'Robinhood Chain', nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 }, rpcUrls: { default: { http: ['https://rpc.mainnet.chain.robinhood.com'] }, }, } as const const SARCOPHAGUS = '0x712567e71a93Fb111510A790cAf3469677aAba3e' const sarcophagusAbi = parseAbi([ 'function R33() view returns (address)', 'function nonce() view returns (uint256)', 'function exchangeAmountThreshold() view returns (uint256)', 'function maxTokenClaim() view returns (uint256)', 'function bury(uint256 nonce, address[] tokens, uint256[] minAmountsOut)', ]) const erc20Abi = parseAbi([ 'function balanceOf(address) view returns (uint256)', 'function allowance(address,address) view returns (uint256)', ]) const publicClient = createPublicClient({ chain: robinhood, transport: http(), }) const account = privateKeyToAccount(process.env.SEARCHER_KEY as `0x${string}`) const walletClient = createWalletClient({ account, chain: robinhood, transport: http(), }) // Supply addresses discovered from trusted fee configuration or indexed logs. const tokens: readonly `0x${string}`[] = [ // '0x...', ] const blockNumber = await publicClient.getBlockNumber() const read = { address: SARCOPHAGUS, abi: sarcophagusAbi, blockNumber } as const const [r33, nonce, threshold, maxTokenClaim] = await Promise.all([ publicClient.readContract({ ...read, functionName: 'R33' }), publicClient.readContract({ ...read, functionName: 'nonce' }), publicClient.readContract({ ...read, functionName: 'exchangeAmountThreshold' }), publicClient.readContract({ ...read, functionName: 'maxTokenClaim' }), ]) if (tokens.length === 0 || BigInt(tokens.length) > maxTokenClaim) { throw new Error('Invalid token count') } const balances = await Promise.all( tokens.map((token) => publicClient.readContract({ address: token, abi: erc20Abi, functionName: 'balanceOf', args: [SARCOPHAGUS], blockNumber, }), ), ) // Raw token units. Choose policy based on each token's behavior and latency. const minAmountsOut = balances.map((balance) => (balance * 995n) / 1000n) const allowance = await publicClient.readContract({ address: r33, abi: erc20Abi, functionName: 'allowance', args: [account.address, SARCOPHAGUS], }) if (allowance < threshold) { throw new Error('Approve the r33 threshold, then rebuild the quote from a new block') } const { request } = await publicClient.simulateContract({ account, address: SARCOPHAGUS, abi: sarcophagusAbi, functionName: 'bury', args: [nonce, [...tokens], minAmountsOut], }) // Re-evaluate profitability and freshness before signing. const hash = await walletClient.writeContract(request) const receipt = await publicClient.waitForTransactionReceipt({ hash }) if (receipt.status !== 'success') throw new Error(`bury reverted: ${hash}`) ``` The example uses an environment variable only to keep the transaction flow concise. Production searchers should use an appropriate signer, isolated key policy, transaction replacement strategy, and private-orderflow decision for their operating environment. ## Contract interface ### State reads | Function | Mutability | Meaning | | --------------------------- | -------------- | ---------------------------------------------------------------- | | `R33()` | immutable view | r33 ERC-20 charged for every successful claim | | `exchangeAmountThreshold()` | view | Exact raw r33 amount transferred by `bury` | | `maxTokenClaim()` | view | Maximum number of token entries accepted by one call | | `nonce()` | view | Nonce required by the next successful claim | | `owner()` | view | Address authorized to update parameters and rescue ERC-20 tokens | ### `bury` ```solidity theme={null} function bury( uint256 _nonce, address[] calldata _tokens, uint256[] calldata _minAmountsOut ) external ``` | Parameter | Type | Requirement | | ---------------- | ----------- | -------------------------------------------------------------------- | | `_nonce` | `uint256` | Must equal the current `nonce()` | | `_tokens` | `address[]` | Non-empty; length must not exceed `maxTokenClaim()` | | `_minAmountsOut` | `uint256[]` | Same length and index order as `_tokens`; values are raw token units | The function is `nonReentrant`. On success it transfers the r33 threshold from `msg.sender` to the dead address, then transfers the complete pre-transfer Sarcophagus balance of each selected token to `msg.sender`. ### Owner functions ```solidity theme={null} function rescue(address token, address to, uint256 amount) external onlyOwner function setExchangeAmountThreshold(uint256 threshold) external onlyOwner function setMaxTokenClaim(uint256 maxTokenClaim) external onlyOwner ``` * `rescue` can move any ERC-20 balance from the contract at any time. * The threshold and maximum claim count must each remain greater than zero. * Parameter setters do not emit dedicated events in this deployment. Track owner transactions and confirm storage directly. ## Events and errors ### `Buried` ```solidity theme={null} event Buried( uint256 indexed nonce, address indexed user, address[] tokensClaimed ) ``` The event records the consumed nonce, successful caller, and requested token-address array. It does not include transferred amounts; reconstruct amounts from transaction traces, ERC-20 `Transfer` logs, or pre-transaction state. ### Custom errors | Error | Trigger | | -------------------- | ----------------------------------------------------- | | `InvalidNonce()` | Supplied nonce differs from `nonce()` | | `NoTokensProvided()` | Token array is empty | | `TooManyAssets()` | Token count exceeds `maxTokenClaim()` | | `LengthMismatch()` | Token and minimum-output array lengths differ | | `SlippageExceeded()` | A selected balance is below its paired minimum | | `InvalidThreshold()` | Owner attempts to set the threshold to zero | | `InvalidMaxClaim()` | Owner attempts to set the maximum claim count to zero | ERC-20 calls can also revert with token-specific errors or `SafeERC20` failures. ## Atomicity and token behavior The entire transaction reverts, including the r33 transfer and nonce increment. A malformed or incompatible token therefore blocks only batches that include it; retry without that token. The first occurrence can transfer the token's full balance. A later occurrence observes the remaining balance, normally zero. A positive minimum on the duplicate reverts the entire call; a zero minimum adds no value and wastes gas. No. The minimum is checked against `balanceOf(Sarcophagus)` before transfer, not the caller's received amount. A transfer-tax token can deliver less than its checked balance, and unusual rebasing or callback behavior may cause different results or a revert. Yes. Token selection is not allowlisted, and the contract does not exclude r33. The claim payment goes directly from the caller to the dead address, while any r33 already held by Sarcophagus can be selected like another ERC-20 balance. No. `bury` and `rescue` operate on ERC-20 token contracts. Native ETH is not part of the claim interface. ## Security and trust boundaries | Control | What it provides | What it does not provide | | ------------------- | -------------------------------------------------------- | ------------------------------------------------------------------ | | Expected nonce | Ordering and stale-call rejection | Exclusive execution rights or front-running protection | | Minimum outputs | Lower bounds on selected pre-transfer balances | USD pricing or guaranteed received amounts for non-standard tokens | | `nonReentrant` | Blocks re-entry into guarded execution | Compatibility with every token implementation | | `SafeERC20` | Handles standard false/no-return ERC-20 transfers | Protection from malicious token-side semantics | | Maximum token count | Bounds the current claim batch | A guarantee that every maximum-sized batch fits a chosen gas limit | | Owner controls | Operational threshold, batch-size, and rescue management | Immutable economics or guaranteed availability of accrued balances | Searchers should assume that the owner can change the threshold or maximum token count and can rescue tokens before a claim is included. Token balances can also change independently as fees arrive or other transfers occur. Use live reads, explicit minimums, and exact-call simulation. ## Verified build | Field | Value | | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Contract | `Sarcophagus` | | Source pragma | `^0.8.27` | | Compiler | Solidity `0.8.30+commit.73712a01` | | Optimizer | Enabled, `25,000` runs | | IR pipeline | `viaIR: true` | | Runtime code hash | `0x7b368a0adab70e9752fd16d9ba71a2baddac5e8787d17a7509cb0d9816a4b967` | | Creation transaction | [`0xcd405c9afc90c62b785d819de58a15f0705b4527769ee856ff9ff056f529420b`](https://robinhoodchain.blockscout.com/tx/0xcd405c9afc90c62b785d819de58a15f0705b4527769ee856ff9ff056f529420b) | | Verification | Exact creation and runtime bytecode match | The constructor was deployed with the Ramses owner address and r33 token address listed above. The deployment is not a proxy; mutable behavior is limited to the exposed owner-controlled parameters and rescue function. ## Resources * [Verified contract on Robinhood Blockscout](https://robinhoodchain.blockscout.com/address/0x712567e71a93Fb111510A790cAf3469677aAba3e) * [Exact-match source on Sourcify](https://repo.sourcify.dev/4663/0x712567e71a93Fb111510A790cAf3469677aAba3e) * [r33 / hyperRAM reference](/contracts/reference/tokens/R33) * [Robinhood DLMM deployment reference](/contracts/reference/dlmm/deployments) * [Fee mechanics](/concepts/protocol/fees) # R33 Source: https://tech.ramses.xyz/contracts/reference/tokens/R33 ERC4626 vault built in `R33.sol`. The source contract is named `R33`, but the ERC20 share token it mints is `"xRAM Liquid Staking Token"` with symbol `hyperRAM`. The vault wraps xRAM exposure, stakes the underlying into `VoteModule`, and lets an operator vote and compound on behalf of all depositors. ## Core ERC4626 Functions ### deposit ```solidity theme={null} function deposit(uint256 assets, address receiver) external returns (uint256 shares) ``` Deposits xRAM, stakes it into `VoteModule`, and mints vault shares to `receiver`. ### withdraw ```solidity theme={null} function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares) ``` Burns shares, withdraws xRAM from `VoteModule`, and transfers xRAM to `receiver`. ### redeem ```solidity theme={null} function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets) ``` Redeems a share amount for the corresponding xRAM assets. ### totalAssets ```solidity theme={null} function totalAssets() public view returns (uint256) ``` Returns the xRAM currently staked by the vault in `VoteModule`. ### ratio ```solidity theme={null} function ratio() public view returns (uint256) ``` Returns the current xRAM-per-share ratio, scaled by `1e18`. ## Operator and Governance Functions ### submitVotes ```solidity theme={null} function submitVotes(address[] calldata pools, uint256[] calldata weights) external ``` Operator-only helper that forwards a vote through `Voter` on behalf of the vault. ### claimIncentives ```solidity theme={null} function claimIncentives(address[] calldata feeDistributors, address[][] calldata tokens) external ``` Claims vote incentives and fee rewards to the vault. ### swapIncentiveViaAggregator ```solidity theme={null} function swapIncentiveViaAggregator(AggregatorParams calldata params) external ``` Operator-only reward-processing hook that swaps incentive tokens through a whitelisted aggregator. RAM output is then available for `compound()`. ### compound ```solidity theme={null} function compound() external ``` Converts any RAM held by the vault into xRAM, deposits that xRAM into `VoteModule`, and increases the vault ratio for all share holders. ### unlock ```solidity theme={null} function unlock() external ``` Marks the current period as unlocked, but only when the `VoteModule` cooldown is not active. ## Key Concepts * Deposits are gated by `isUnlocked()`, which requires the current period to be unlocked and not within one hour of the next weekly period. * Withdrawals and redeems do not use the same vault lock, but they still depend on `VoteModule.withdraw()` succeeding, so the VoteModule cooldown matters. * `totalAssets()` reads from `VoteModule.balanceOf(address(this))`, not from idle xRAM held directly in the vault. * Aggregators must be whitelisted by `AccessHub` before `swapIncentiveViaAggregator()` can be used. * Shares are transferable even though the underlying xRAM token is transfer-restricted. # XRAM Source: https://tech.ramses.xyz/contracts/reference/tokens/xRAM Transfer-restricted ERC20 governance token used by the Ramses voting system. The current implementation lives in `XRam.sol` and is controlled by `AccessHub`, `Voter`, and `VoteModule`. ## Core Functions ### convertEmissionsToken ```solidity theme={null} function convertEmissionsToken(uint256 amount) external ``` Transfers `amount` of RAM from the caller, burns the configured slashing penalty, and mints `amount` of xRAM to the caller. #### Parameters | Name | Type | Description | | :------- | :------ | :----------------------- | | `amount` | uint256 | Amount of RAM to convert | ### exit ```solidity theme={null} function exit(uint256 amount) external returns (uint256 exitedAmount) ``` Burns xRAM and returns the post-penalty RAM amount to the caller. The contract applies the same slashing formula used on entry and caps the returned amount to the RAM balance currently residing in the xRAM contract. #### Parameters | Name | Type | Description | | :------- | :------ | :--------------------- | | `amount` | uint256 | Amount of xRAM to burn | ### pause / unpause ```solidity theme={null} function pause() external function unpause() external ``` Governance-controlled circuit breakers for conversion, exit, and rebase-related flows. ### setExemption / setExemptionTo ```solidity theme={null} function setExemption(address[] calldata who, bool[] calldata exempt) external function setExemptionTo(address[] calldata who, bool[] calldata exempt) external ``` Manages the transfer allowlists used by `_update()`. ### getBalanceResiding ```solidity theme={null} function getBalanceResiding() external view returns (uint256) ``` Returns the amount of underlying RAM currently held by the xRAM contract. ## Key Concepts * `XRam` is **not** a freely transferable ERC20. Transfers only succeed when the sender or receiver is exempt, or when the transfer involves recognized gauges or fee distributors. * `convertEmissionsToken()` mints xRAM 1:1 with the input amount, but it also burns at least 50% of the incoming RAM via `SLASHING_PENALTY`. * `exit()` burns xRAM and returns the post-penalty RAM amount, which is typically about half of the xRAM burned. * `rebase()` is still exposed for compatibility, but the current implementation notifies `VoteModule` with `0` rather than distributing a positive rebase amount. * Voting power comes from staking xRAM in `VoteModule`, not from simply holding xRAM in a wallet. # Background Source: https://tech.ramses.xyz/sdk/guides/01-background Before integrating with Ramses, it may be helpful for newcomers to review the following background information on some important developer web3 concepts, the structure of our examples, and SDK concepts. Already familiar with web3 development and/or the basics of our SDK and want to get right to the code? Start with our first guide, [Getting a Quote](./swaps/01-quoting)! ## Providers Communication with the blockchain is typically done through a provider and local models of smart contracts and their [ABIs](#abis). To achieve this, our examples use the [ethers.js](https://docs.ethers.io/v5/) library. To instantiate a provider you will need a data source. Our examples offer two options: * **JSON RPC URL**: If you are working directly with the Ethereum mainnet or a local fork, products such as [Infura](https://infura.io/) offer JSON RPC URLs for a wide variety of chains and testnets. For our examples, we'll only be using the Ethereum mainnet. * **Wallet Extension**: If you are connecting to a wallet browser extension, these wallets embed a source directly into the Javascript window object as `window.ethereum`. This object surfaces information about the user's wallets and provides the ability to communicate with the connected chain. Importantly for our examples, it can be used with `ethers.js` to construct a provider. ## Runnable Examples Each guide is accompanied and driven by runnable examples using React to provide a basic UI for interacting with the example. Each example provides relevant options such as running against a local blockchain or connecting to the network directly. You also have the option of using a wallet extension which can be connected to either environment. Inputs and environment settings are configured in each example's `config.ts` and allows for simple setup and configuration. ### Developing and Testing To test your code, we recommend utilizing a local fork of the Ethereum mainnet. To help facilitate easy testing, each example includes a quickstart for running the local chain with a test wallet. To further test, we also recommend using a wallet extension and connecting to the local chain. Finally, each example can be run against the Ethereum mainnet if desired. Full development instructs can be found in the `README.md` of each code example. ### Utility Libraries Each example is concentrated into a single file within the `libs/` folder of the example, with the entry points noted in each guide and README. To allow the guides to focus on the SDK's core functionality, additional basic building blocks can be found in each example's `libs` folder. The exported functionality from these files is intended to be the minimum needed for each example and not a complete library for production usage. These also include storing core constants such as definitions for tokens, ABI's, and blockchain addresses that can distract from the core concepts. Below are summaries of the helping libraries you will encounter. #### Provider Utilities `provider.ts` wraps the basics of `ethers.js` and connecting to wallet extensions into an abstracted view of a provider, a wallet address, and the ability to send transactions. It also helps abstract the configured environment you wish to run against in your example without making code changes outside of your configuration. #### Wallet Utilities `wallet.ts` offers the ability to query a wallet (whether connected via an extension or defined in code/config) for its balances and other essential information. #### Pool Information `pool.ts` contains the basic querying of pool information when not essential / core to the relevant guide #### Display Utilities `conversion.ts` provides display and light math wrappers to help show human readable prices when dealing with currency amounts (typically stored as raw numbers and the decimal placement separate for precision reasons) in the form of two functions: `fromReadableAmount` and `toReadableAmount` ## Notable SDK Structures and Concepts When working with the SDK it can be helpful to understand some of the design choices and why they are needed. Below you can find a few important concepts. ### ABI's To allow others to interact with a smart contract, each contract exposes an ABI (Application Binary Interface). As these are defined on the blockchain, we must ensure the correct definitions are provided to our Javascript functions. ABI's are provided from various SDK's and imported in as needed. Some examples will define an ABI directly as needed. ### CurrencyAmount and JSBI Cryptocurrency applications often work with very small fractions of tokens. As a result, high precision is very important. To ensure precision is upheld, the `CurrencyAmount` class helps store exact values as fractions and utilizes [JSBI](https://github.com/GoogleChromeLabs/jsbi) for compatibility across the web. To display these amounts nicely to users, additional work is sometimes required. ### Currency The `Currency` class can represent both native currency (ETH) and an ERC20 `Token`. Currencies vary in their relative value, so the `Token` class allows your application to define the number of decimals needed for each currency along with the currency's address, symbol, and name. # Local Development Source: https://tech.ramses.xyz/sdk/guides/02-local-development ## Introduction Developing your dApps or smart contracts requires some tinkering to get a proper setup that is both a good simulation of how Mainnet will behave, but also customizable enough to suit the needs of a development environment. One very common approach is to create your own custom chain offline and develop on top of it. The issue with this approach is that if you are integrating with protocols like Ramses or others that are on Mainnet, it's difficult to simulate on your local chain as the smart contracts from Mainnet are not there. Another approach is to use a testnet. While most protocols have versions of their smart contracts deployed on common testnets, there are certain behavioral differences. Not all pools that are on Mainnet are on testnets for example. Also, it's difficult to get enough testnet ETH to account for real testing. And without lots of testnet tokens it's even more difficult to swap to other coins on Ramses, if that's what you need to do in your development environment. This guide focuses on yet another approach to local development: Mainnet Forks. A Mainnet Fork is a local chain that copies the state of Ethereum Mainnet at a given block number. It then gives you access to cheat codes like wallets with thousands of ETH and RPC URLs that you can use as drop-in replacements of real Mainnet RPCs. This approach combines the best of all other approaches. You have a local chain that you can manipulate to your liking and you have real deployments of all the protocols you need to test and develop your dApp or smart contracts. This guide focuses on Ethereum Mainnet. But you can easily fork any other chain by simply replacing the RPC URL with one of the network you want to use. For this guide, the following packages are used: * [`@kingdomdotone/v3-sdk`](https://www.npmjs.com/package/@kingdomdotone/v3-sdk) * [`@uniswap/sdk-core`](https://www.npmjs.com/package/@uniswap/sdk-core) * [`ethers@5`](https://www.npmjs.com/package/ethers) The `@kingdomdotone/v3-sdk` is Ramses' fork of the Uniswap V3 SDK, tailored for Ramses V3 pools. Use it alongside `@uniswap/sdk-core` for core token abstractions. Please note that we use ethers version 5, as this is still the most commonly used version of ethers.js. If you use version 6, you will need to slightly change the syntax in the examples below. Forking a chain requires archival data and trace calls. Infura and normal geth instances are by default not archival. You can get a free archival RPC that you can use to follow this guide and fork Mainnet you can visit [Chainnodes](https://www.chainnodes.org/). ## Using Foundry and Anvil There are several developer tools to fork Mainnet. [Anvil](https://github.com/foundry-rs/foundry/tree/master/crates/anvil) by foundry is a newcomer that's fast and easy to setup. This guide focuses on Anvil. As a first step, follow the [installation guide](https://book.getfoundry.sh/getting-started/installation) in the foundry book. Once you have done that, you will be able to fork Mainnet straight away. Run the below command in your terminal: Make sure that you: * Replace your API Key (get one by heading to [Chainnodes](https://app.chainnodes.org/)) * Replace the block number with a recent one, check [Etherscan](https://etherscan.io/) for that * If you fork a non-Ethereum Mainnet chain, check [Chainlist](https://chainlist.org/) for the correct chain id and replace both occurrences in the command below ```bash theme={null} anvil --fork-url https://mainnet.chainnodes.org/api_key --fork-block-number 17480237 --fork-chain-id 1 --chain-id 1 ``` Run `anvil --help` to see all available options. Once you have done that, you should see something like the below: ```text theme={null} _ _ (_) | | __ _ _ __ __ __ _ | | / _` | | '_ \ \ \ / / | | | | | (_| | | | | | \ V / | | | | \__,_| |_| |_| \_/ |_| |_| 0.2.0 (abcdef 2023-06-15T00:00:00.000000Z) https://github.com/foundry-rs/foundry Available Accounts ================== (0) 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 (10000.000000000000000000 ETH) (1) 0x70997970C51812dc3A010C7d01b50e0d17dc79C8 (10000.000000000000000000 ETH) (2) 0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC (10000.000000000000000000 ETH) ... Private Keys ================== (0) 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 (1) 0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d (2) 0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a ... Fork ================== Endpoint: https://mainnet.chainnodes.org/api_key Block number: 17480237 Block hash: 0x... Chain ID: 1 Listening on 127.0.0.1:8545 ``` Your local fork of Mainnet is now running! As you can see above, anvil prints a bunch of private keys that are loaded with 10k ETH each. We will use them going forward to send transactions, including swaps on Ramses pools. Security consideration: This is a fork of Mainnet and the same chain id is used. You have no replay protection to Ethereum Mainnet. So you need to 1: Never use the anvil private keys on a real chain or send funds to it (they are leaked everywhere) and 2: Not send any transactions to your local fork chain with accounts that you use on Ethereum Mainnet or other real chains. If you scroll down in your terminal, near the bottom of the anvil logs you will find your RPC URL. If you haven't changed any configs, it should be `127.0.0.1:8545`. This is the RPC URL that you can now use as a drop-in replacement everywhere in your development environment, and interact with it as if it was real Ethereum Mainnet. You can use the http provider `http://127.0.0.1:8545` as well as the Websocket provider `ws://127.0.0.1:8545`. You can now make a sample RPC request to your http provider using [Postman](https://www.postman.com/) using the below: POST `http://127.0.0.1:8545` Body: ```json theme={null} { "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 } ``` The result should look like the below: ```json theme={null} { "jsonrpc": "2.0", "id": 1, "result": "0x1" } ``` The `result` value `0x1` is the hex-encoded chain ID for Ethereum Mainnet (`1`). This confirms your local fork is correctly emulating Mainnet. You can find the above example and more in the Postman workspace under "Local Development". ## Using your Mainnet Fork Now that you have a running Mainnet Fork, you will be able to use it everywhere in your development setup. Using one of the private keys provided by anvil, you have access to enough ETH to do endless swaps and smart contract calls. If you need any other token, you now have the flexibility of swapping your ETH to any token that has a pool deployed on Mainnet. You basically take your fake ETH and swap it to the token you need. Check out one of the [guides about swapping](./swaps/02-trading) and replace the RPC URL with your local anvil HTTP link as above. ## Next Steps Using the above you are fully equipped to continue following the guides about how to use Ramses while testing everything locally before going live. You will also be able to reuse what you have learned when you develop your own protocols or dApps. You can also continue tapping into other developer tools that make smart contract development easier like [forge](https://github.com/foundry-rs/foundry/tree/master/crates/forge) from foundry. To read more about foundry and their developer tooling, visit their [GitHub](https://github.com/foundry-rs/foundry) or the [foundry book](https://book.getfoundry.sh/). # Web3 Development Basics Source: https://tech.ramses.xyz/sdk/guides/03-web3-development-basics ## Introduction Developing dApps and interacting with Smart Contracts is quite different from Web2, and at times challenging due to little information on this topic compared to other areas of software development. This developer guide is a quick overview of the space, including references to libraries and guides that are great starting points. Reading this guide should help you identify areas that you might need to learn a bit more about and prepare you for the following Uniswap-specific guides. It is assumed that you know the basics about Ethereum and the blockchain, including some terminology. If you already know how to build dApps and interact with ethersJS etc. you can safely skip this guide. ## RPCs The access point to the blockchain are RPC nodes. They are the [standardized interface](https://ethereum.org/en/developers/docs/apis/json-rpc/) to read data from smart contracts, send transactions and interact with on-chain protocols. RPCs are either [full or archival nodes](https://ethereum.org/en/developers/docs/nodes-and-clients/archive-nodes/) with a ([JSON-RPC](https://www.jsonrpc.org/)) interface. To support Ethereum's decentralization, one can host a node themselves, for example by using one of the implementations listed below: * [geth](https://github.com/ethereum/go-ethereum) - The original (reference) implementation of the Ethereum protocol * [erigon](https://github.com/ledgerwatch/erigon) - A very efficient archival node implementation * [Nethermind](https://github.com/NethermindEth/nethermind) - An Ethereum implementation focused on stability As achieving high availability and making sure your node is synced all the time turns out to be quite challenging, there are nodes as a service (RPC) providers that you can use, especially in production environments. When choosing an RPC provider, we suggest you look for an RPC service that supports websockets as they provide far superior performance than HTTP connections. To ensure interoperability, you should also ensure that your RPC provider adheres strictly to the JSON-RPC standard and doesn't require custom requests. [Chainnodes](https://www.chainnodes.org/) is a robust RPC provider with generous free tier that you can use in both development and production environments. For testing purposes you could also use a free public RPC endpoint, for example from [Chainlist](https://chainlist.org/). ### JSON-RPC Standard RPCs communicate over the [JSON-RPC](https://www.jsonrpc.org/) standard. To send requests, you take the RPC URL and make a POST request with a JSON body. See the below example: `POST https://mainnet.chainnodes.org/API_KEY` Body: ```json theme={null} { "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 } ``` At the time of writing, this request would respond with the following: ```json theme={null} { "id": 1, "result": "0x11527c0", "jsonrpc": "2.0" } ``` Examining the result, we see that the result is an encoded hex string. After decoding it, we see it returns the current blocknumber of our network, `18163648`. You can find the above examples, including more, in [this Postman collection](https://www.postman.com/chainnodes/workspace/uniswap-examples). To check out all possible RPC requests, head over to the [Chainnodes Docs](https://www.chainnodes.org/docs). ### Client implementations As communicating over HTTP with POST requests directly can be quite difficult, especially if you want to properly encode and decode responses and handle failures and exponential backoffs, there are client implementations that can do the heavy lifting for you. These SDKs have developer friendly APIs and internally handle creating the proper RPC requests, sending them to the endpoint you choose and decoding the response for you. Some of the major implementations are listed below: * [ethers.js](https://github.com/ethers-io/ethers.js) - Javascript/Typescript SDK for NodeJS and the Browser. Used throughout the Ramses Docs. * [wagmi](https://github.com/wagmi-dev/wagmi) and [viem](https://github.com/wagmi-dev/viem) - Javascript/Typescript, great duo for modern Web3 development in the Browser. * [web3js](https://github.com/web3/web3.js) - Javascript/Typescript SDK for NodeJS and the Browser by ChainSafe. Web3 development is not limited to JS. Web3 libraries for various languages include: * [Web3.swift](https://github.com/Boilertalk/Web3.swift) - Swift SDK for iOS apps and Backends. * [KEthereum](https://github.com/komputing/KEthereum) - Kotlin SDK for Android development. * [ethers-rs](https://github.com/gakonst/ethers-rs) - Rust SDK. * [ethclient](https://github.com/ethereum/go-ethereum/tree/master/ethclient) - Go SDK, part of geth, the reference Ethereum node implementation. * [web3.py](https://github.com/ethereum/web3.py) - Python SDK. At the moment, Uniswap only offers Typescript sdks. As you can see there are lots of SDKs to make it easier to communicate via RPC with the blockchain. ### Local Development To simulate RPCs and transactions locally, you can check [this guide](./02-local-development). ## Indexers As RPCs are only a slim abstraction of the data stored in the blockchain, there are certain things that are hard or expensive to access with regular RPC requests. A common example are transactions of a specific Wallet address. Imagine you want to get a list of all transactions that originated from (or to) a specific Wallet. One could think there should be an RPC method called `eth_getTransactionsForWallet` or something similar. But due to the nature of how the data is stored, this RPC method is not feasible, and hence not implemented. Now, instead of accessing those kind of things by iterating through every block in the blockchain, you can use Indexers, that are designed to index data like that on the go and provide easy access to it. ### TheGraph A well-known, standardized implementation of indexers is [TheGraph](https://thegraph.com/). It is used by most major protocols, including Uniswap, to index data and make it accessible to users and dashboards. Using TheGraph, you can either access open [subgraphs](https://thegraph.com/explorer) via the GraphQL querying language, or [create your own](https://thegraph.com/docs/en/developing/creating-a-subgraph/) and deploy it. Throughout the docs you will see how to interact with the Uniswap subgraph to fetch tick data and more without ever touching RPCs. An important note about Indexers though: While they can be helpful, you need to be aware that the ultimate source of truth comes from the RPCs. As reorgs happen and certain issues on indexers arise, there might be certain datapoints that are either not fully up-to-date or even completely wrong on Indexers. If you have a use-case that requires perfectly correct data all the time, use RPCs directly. If you are just doing data visualization or dashboards, use Indexers if they fit your use-case. Some popular subgraphs that you can try to fetch data from the blockchain easily (click on playground to give it a try): * [Uniswap Messari subgraph](https://thegraph.com/explorer/subgraphs/ELUcwgpm14LKPLrBRuVvPvNKHQ9HvwmtKgKSH6123cr7?view=Overview\&chain=mainnet) * [Snapshot Subgraph](https://thegraph.com/explorer/subgraphs/3Q4vnuSqemXnSNHoiLD7wdBbGCXszUYnUbTz191kDMNn?view=Overview\&chain=mainnet) * [Aave V3 Messari subgraph](https://thegraph.com/explorer/subgraphs/HB1Z2EAw4rtPRYVb2Nz8QGFLHCpym6ByBX6vbCViuE9F?view=Overview\&chain=mainnet) ## Smart Contract Development Smart contracts are typically developed using the [Solidity language](https://soliditylang.org/). There are VSCode plugins that make the development with Solidity easier. One of them is Juan Blanco's "Solidity" that you can find over [here](https://marketplace.visualstudio.com/items?itemName=JuanBlanco.solidity). You would typically also go for a developer suite with testing, compilation and deployment capabilities: * [Foundry](https://github.com/foundry-rs/foundry) - Fast and modern developer tools for smart contract engineers. * [Hardhat](https://github.com/NomicFoundation/hardhat) - Scriptable, easy and battle-tested JS developer suite for smart contracts. To read data from smart contracts, or interact with them, use the [client SDKs](#client-implementations) mentioned above. They help you generate the necessary RPC calls to fetch data from / send transactions to the blockchain and interact with your smart contracts. You can read more about it in the [ethers.js docs](https://docs.ethers.org/v5/api/contract/contract/). ## Blockchain Explorers Manually gathering information and inspecting data stored in a blockchain is a tedious task. Almost all chains have at least one accompanying block explorer to help visualize addresses, transactions, contracts and more. For Ethereum mainnet, we suggest using [Etherscan](https://etherscan.io/). You can use Etherscan to inspect [contracts](https://etherscan.io/address/0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45#code), transactions, blocks, and much more. If you are looking to debug a transaction, [Tenderly](https://dashboard.tenderly.co/tx/mainnet/0xa4affe1abfaf28d1763d6c3ccda33e717462a928abca89415fc6e661dd7e0c55) can also be a very helpful tool. In this example of a failed transaction on the Uniswap V2 Router you can easily see why the execution failed and where. ## The Uniswap development suite Uniswap offers several SDKs that work together and enable you to easily interact with Ramses The most important SDKs are: * [sdk-core](https://github.com/Uniswap/sdk-core): The core of the Uniswap SDKs, defines classes and types shared across all the SDKs * [v2-sdk](https://github.com/Uniswap/v2-sdk): An SDK to interact with the Uniswap V2 protocol. * [v3-sdk](https://www.npmjs.com/package/@kingdomdotone/v3-sdk): Ramses' fork of the Uniswap V3 SDK, tailored for interacting with Ramses V3 pools. * [router-sdk](https://github.com/Uniswap/router-sdk): Provides abstractions to interact with the (older) SwapRouter contracts. * [universal-router-sdk](https://github.com/Uniswap/universal-router-sdk): Abstracts interactions with the Universal Router. * [smart-order-router](https://github.com/Uniswap/smart-order-router): Searches for the most efficient routes for a trade. * [permit2-sdk](https://github.com/Uniswap/permit2-sdk): Simplifies interactions with Permit2 in JS. * [uniswapx-sdk](https://github.com/Uniswap/uniswapx-sdk): SDK for the UniswapX protocol. As you know already, all interactions with the blockchain happens through RPCs. So the Uniswap SDKs, as you will see throughout the guides, requires you to have access to an RPC endpoint like [Chainnodes](https://www.chainnodes.org). When reading data, the data is read from the given RPC endpoint. When actually swapping, you will need to sign a transaction using a private key. We are continuously working on improving the Uniswap development suite, so stay tuned for more updates. ## Next Steps Go through the basic guides first and try to fetch some data and interact with the Uniswap ecosystem a little bit. You can even [send your first swap transaction](./swaps/02-trading) on a local fork! While some concepts in Web3 require thinking outside of the box, this guide should give you a good overview on where to start. You should now be fully equipped to follow our other guides. # Introduction Source: https://tech.ramses.xyz/sdk/guides/advanced/01-introduction For some more advanced use cases, it is necessary to use multiple tools in the Ramses V3 toolchain. If you need a briefer on the SDK and to learn more about how these guides connect to the examples repository, please visit our [background](../01-background) page! The following examples use **ethersJS** and the **V3 subgraph** hosted on The Graph's hosted service. To learn more about subgraph usage, visit the [Uniswap V3 Subgraph documentation](https://docs.uniswap.org/concepts/protocol/subgraph) (Ramses V3 uses the same subgraph schema). We will take a deep dive into the Ramses V3 protocol and use practical examples to understand the data stored by the V3 smart contracts. We will explore how we can compute the available liquidity in a specific price range, visualize **liquidity density** in pools, use Ramses V3 as a **price oracle** and swap by creating **Range Orders**. These guides are a bit longer than the previous ones and provide more theoretical background. ## Theoretical background Some of the guides presented here require a bit of theoretical and mathematical background. To get the most out of the advanced guides, we encourage you to take a step back and read a bit about the math and theories behind Ramses. The most complete source of information on Ramses is the [Uniswap V3 book](https://uniswapv3book.com/). Besides the [concepts](../../../../concepts/ramses-protocol) section of the Docs, the [Uniswap V3 whitepaper](https://uniswap.org/whitepaper-v3.pdf) is a great introduction to the protocol. If you haven't checked it out yet, it is probably more concise and easier to understand than you would expect. ### Datatypes in Solidity Ramses V3 pools make use of a number of Datatypes Solidity offers to efficiently store their state. If you are not familiar with Solidity data types yet, it can help to take a look at the [Solidity language reference](https://docs.soliditylang.org/en/v0.8.7/types.html#). For the following guides, it is beneficial to take a look at two of them, which we will outline here. Ticks are stored as a [mapping(int24 => Tick.Info)](https://github.com/Uniswap/v3-core/blob/main/contracts/UniswapV3Pool.sol#L93). Solidity [mappings](https://docs.soliditylang.org/en/v0.8.7/types.html#mapping-types) are very similar to hash maps, such that we can access any Value with their key with just one read operation. The [`Tick.Info`](https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/Tick.sol#L17) stores the values of the Tick that we need to work with the Pool: ```solidity theme={null} struct Info { // the total position liquidity that references this tick uint128 liquidityGross; // amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left), int128 liquidityNet; // fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick) // only has relative meaning, not absolute — the value depends on when the tick is initialized uint256 feeGrowthOutside0X128; uint256 feeGrowthOutside1X128; // the cumulative tick value on the other side of the tick int56 tickCumulativeOutside; // the seconds per unit of liquidity on the _other_ side of this tick (relative to the current tick) // only has relative meaning, not absolute — the value depends on when the tick is initialized uint160 secondsPerLiquidityOutsideX128; // the seconds spent on the other side of the tick (relative to the current tick) // only has relative meaning, not absolute — the value depends on when the tick is initialized uint32 secondsOutside; // true iff the tick is initialized, i.e. the value is exactly equivalent to the expression liquidityGross != 0 // these 8 bits are set to prevent fresh sstores when crossing newly initialized ticks bool initialized; } ``` We will use most of these values in the following guides. In our case, we can access any `Tick.Info` value stored in the pool by its `int24` key. The key of the Tick is usually called its *index*. Mappings are not iterable, so if we are trying to fetch all the Ticks stored in a Pool, we can't just iterate over the mapping. Instead, we have to know the keys (indices) of the mapping, we will explore how to do that in the [Pool data guide](./02-pool-data). The second Solidity datatype we need to understand are normal unsigned [Integers](https://docs.soliditylang.org/en/v0.8.7/types.html#integers). Solidity supports unsigned integer sizes between `uint8` and `uint256`, which are 8 and 256 bits long respectively. Let's take a look at the `tickBitmap` function of a V3 Pool: ```solidity theme={null} function tickBitmap( int16 wordPosition ) external view returns (uint256) ``` Similar to the tick mapping, the tickBitmap is a mapping of type [mapping(int16 => uint256)](https://github.com/Uniswap/v3-core/blob/main/contracts/UniswapV3Pool.sol#L95). Let's look at the WETH/USDC pool with LOW fee on [Etherscan](https://etherscan.io/address/0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640#readContract). If we call the `tickBitmap` function with the input `0` we get a response like: ```text theme={null} tickBitmap(int16) : 0 int16: 0 ──────────────────────────────────── uint256: 768 ``` The value `768` is `0x300` in hex, or `...0000001100000000` in binary. Etherscan displays the `uint256` return value as a decimal number. The actual raw return value are 256 bits, that look something like this: ```raw theme={null} 0x0000 ... lots of zeros and ones ... 000000110000000000 ``` We interpret this string of zeros and ones not as the representation of a number, but rather as 256 booleans. If the value of a position in the value is 1, the Tick at this position is **initialized**, meaning it holds a value. With this trick, V3 Pools allow us to fetch the status of **256 ticks** with one call. We will go into more details on how to calculate the tick indices from the tickBitmaps we fetch in the following guides. ## History of Uniswap To get a better understanding of the V3 protocol, it can also be beneficial to understand the **history of decentralized exchanges** and Ramses since it was founded in 2018. You can read more about the older versions of Uniswap in the [V1](https://hackmd.io/@HaydenAdams/HJ9jLsfTz?type=view#Swaps-vs-Transfers) and [V2](https://uniswap.org/whitepaper.pdf) whitepapers, as well as the [V1](../../../../contracts/v1/overview) and [V2](../../../../contracts/v2/overview) section in the contract section. # Fetching Pool Data Source: https://tech.ramses.xyz/sdk/guides/advanced/02-pool-data ## Introduction This guide will cover how to initialize a Pool with full tick data to allow offchain calculations. It is based on the [Fetching Pool data example](https://github.com/Uniswap/examples/tree/main/v3-sdk/pool-data), found in the Uniswap code examples [repository](https://github.com/Uniswap/examples). To run this example, check out the guide's [README](https://github.com/Uniswap/examples/blob/main/v3-sdk/pool-data/README) and follow the setup instructions. If you need a briefer on the SDK and to learn more about how these guides connect to the examples repository, please visit our [background](../01-background) page! In this example we will use **ethers JS** and **ethers-multicall** to construct a `Pool` object that we can use in the following guides. This guide will **cover**: 1. Computing the Pool's address 2. Referencing the Pool contract and fetching metadata 3. Fetching the positions of all initialized Ticks with multicall 4. Fetching all ticks by their indices with a multicall 5. Constructing the Pool object At the end of the guide, we will have created a `Pool` Object that accurately represents the state of a V3 pool at the time we fetched it. For this guide, the following packages are used: * [`@kingdomdotone/v3-sdk`](https://www.npmjs.com/package/@kingdomdotone/v3-sdk) * [`@uniswap/sdk-core`](https://www.npmjs.com/package/@uniswap/sdk-core) We will also use the `ethers-multicall` npm package: * [`ethers-multicall`](https://www.npmjs.com/package/ethers-multicall) The core code of this guide can be found in [`fetcher.ts`](https://github.com/Uniswap/examples/tree/main/v3-sdk/multicall/src/libs/fetcher.ts) ## Configuration The example accompanying this guide can be configured in the [`config.ts`](https://github.com/Uniswap/examples/tree/main/v3-sdk/multicall/src/config.ts) file. The default configuration defines the rpc endpoint and the pool that is used for this guide: ```typescript theme={null} export const CurrentConfig: ExampleConfig = { env: Environment.MAINNET, rpc: { local: 'http://localhost:8545', mainnet: 'https://mainnet.infura.io/v3/0ac57a06f2994538829c14745750d721', }, ... pool: { token0: USDC_TOKEN, token1: WETH_TOKEN, fee: FeeAmount.MEDIUM, }, } ``` FeeAmount.MEDIUM means that the pool has a swap fee of **0.3%**. The `USDC_TOKEN` and `WETH_TOKEN` are defined in the [`constants.ts`](https://github.com/Uniswap/examples/tree/main/v3-sdk/multicall/src/libs/constants.ts) file: ```typescript theme={null} export const WETH_TOKEN = new Token( SupportedChainId.MAINNET, '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', 18, 'WETH', 'Wrapped Ether' ) export const USDC_TOKEN = new Token( SupportedChainId.MAINNET, '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', 6, 'USDC', 'USD//C' ) ``` ## Computing the Pool's deployment address In this example, we will construct the **USDC - WETH** Pool with **MEDIUM** fees. The SDK provides a method to compute the address: ```typescript theme={null} import { Pool } from '@kingdomdotone/v3-sdk' import { CurrentConfig } from '../config.ts' const poolAddress = Pool.getAddress( CurrentConfig.pool.token0, CurrentConfig.pool.token1, CurrentConfig.pool.fee ) ``` Ramses V3 supports multiple fee tiers when deploying a pool, so multiple pools can exist for each pair of tokens. ## Creating a Pool Contract instance and fetching metadata Now that we have the address of a **USDC - ETH** Pool, we can construct an instance of an **ethers** `Contract` to interact with it. To construct the Contract we need to provide the address of the contract, its ABI and a provider connected to an [RPC endpoint](https://www.chainnodes.org/docs). We get access to the contract's ABI through the `@uniswap/v3-core` package (Ramses V3 uses compatible interfaces): ```typescript theme={null} import { ethers } from 'ethers' import IUniswapV3PoolABI from '@uniswap/v3-core/artifacts/contracts/interfaces/IUniswapV3Pool.sol/IUniswapV3Pool.json' const provider = getProvider() const poolContract = new ethers.Contract( poolAddress, IUniswapV3PoolABI.abi, provider ) ``` The `getProvider()` function returns an `ethers.providers.JsonRpcProvider` with either the local or mainnet rpc url that we defined, depending on the Environment that we set in `config.ts`. Once we have set up our reference to the contract, we can proceed to access its methods. To construct our offchain representation of the Pool Contract, we need to fetch its liquidity, sqrtPrice, currently active tick and the full Tick data. We get the **liquidity**, **sqrtPrice** and **tick** directly from the blockchain by calling `liquidity()`and `slot0()` on the Pool contract: ```typescript theme={null} const [liquidity, slot0] = await Promise.all([ poolContract.liquidity(), poolContract.slot0(), ]) ``` The [slot0 function](../../../../contracts/reference/core/interfaces/pool/IRamsesV3PoolState.md#slot0) represents the first (0th) storage slot of the pool and exposes multiple useful values in a single function: ```solidity theme={null} function slot0( ) external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ) ``` For our use case, we only need the `sqrtPriceX96` and the currently active `tick`. ## Fetching all Ticks V3 pools use ticks to [concentrate liquidity](../../../../concepts/protocol/concentrated-liquidity) in price ranges and allow for better pricing of trades. Even though most Pools only have a couple of **initialized ticks**, it is possible that a pools liquidity is defined by thousands of **initialized ticks**. In that case, it can be very expensive or slow to get all of them with normal RPC calls. If you are not familiar with the concept of ticks, check out the [`introduction`](./01-introduction). To access tick data, we will use the `ticks` function of the V3 Pool contract: ```solidity theme={null} function ticks( int24 tick ) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ) ``` The `tick` parameter that we provide the function with is the **index** (memory position) of the Tick we are trying to fetch. To get the indices of all initialized Ticks of the Pool, we can calculate them from the **tickBitmaps**. To fetch a `tickBitmap` function of the V3 Pool: ```solidity theme={null} function tickBitmap( int16 wordPosition ) external view returns (uint256) ``` A pool stores lots of bitmaps, each of which contain the status of 256 Ticks. The parameter `int16 wordPosition` the function accepts is the position of the bitMap we want to fetch. We can calculate all the position of bitMaps (or words as they are sometimes called) from the `tickSpacing` of the Pool, which is in turn dependant on the Fee tier. So to summarise we need 4 steps to fetch all initialized ticks: 1. Calculate all bitMap positions from the tickSpacing of the Pool. 2. Fetch all bitMaps using their positions. 3. Calculate the memory positions of all Ticks from the bitMaps. 4. Fetch all Ticks by their memory position. We will use multicalls for the fetch calls. ## Multicall Multicall contracts **aggregate results** from multiple contract calls and therefore allow sending multiple contract calls in **one RPC request**. This can improve the **speed** of fetching large amounts of data significantly and ensures that the data fetched is all from the **same block**. We will use the Multicall2 contract by MakerDAO. We use the `ethers-muticall` npm package to easily interact with the Contract. ## Calculating all bitMap positions As mentioned, Ramses V3 Pools store **bitmaps**, also called *words*, that represent the state of **256 initializable ticks** at a time. The value at a bit of a word is 1 if the tick at this index is initialized and 0 if it isn't. We can calculate the positions of initialized ticks from the **words** of the Pool. All ticks of Ramses V3 pools are between the indices `-887272` and `887272`. We can calculate the minimum and maximum word from these indices and the Pool's tickSpacing: ```typescript theme={null} function tickToWord(tick: number): number { let compressed = Math.floor(tick / tickSpacing) if (tick < 0 && tick % tickSpacing !== 0) { compressed -= 1 } return compressed >> 8 } const minWord = tickToWord(-887272) const maxWord = tickToWord(887272) ``` Ticks can only be initialized at indices that are **divisible by the tickSpacing**. One word contains 256 ticks, so we can compress the ticks by right shifting 8 bit. ## Fetching bitMaps from their position Knowing the positions of words in the Pool contract, we can now fetch them from the Pool using multicall and the `tickBitmap` read call. First we initialize our multicall providers and Pool Contract: ```typescript theme={null} import { ethers } from 'ethers' import { Contract, Provider } from 'ethers-multicall' const ethersProvider = new ethers.providers.JsonRpcProvider("...rpcUrl") const multicallProvider = new Provider(ethersProvider) await multicallProvider.init() const poolContract = new Contract(poolAddress, IUniswapV3PoolABI.abi) ``` The `multicallProvider` creates the multicall request and sends it via the ethers Provider. Next we loop through all possible word positions and add a `tickBitmap` call for each: ```typescript theme={null} let calls: any[] = [] let wordPosIndices: number[] = [] for (let i = minWord; i <= maxWord; i++) { wordPosIndices.push(i) calls.push(poolContract.tickBitmap(i)) } ``` We also keep track of the word position indices to be able to loop through them in the same order we added the calls to the array. We use the `multicallProvider.all()` function to send a multicall and map the results: ```typescript theme={null} const results: bigint[] = (await multicallProvider.all(calls)).map( (ethersResponse) => { return BigInt(ethersResponse.toString()) } ) ``` A great visualization of what the bitMaps look like can be found in the [Uniswap V3 development book](https://uniswapv3book.com/milestone_2/tick-bitmap-index.html): ```text theme={null} Word index: -1 0 1 ┌───────────────────┐ ┌───────────────────────┐ ┌───────────────────┐ │ ...0 0 1 0 0 1 0 │ │ 0 0 1 1 0 0 0 0 0 1 │ │ 0 1 0 0 0 1 0... │ └───────────────────┘ └───────────────────────┘ └───────────────────┘ ▲ ▲ ▲ ▲ ▲ ▲ ▲ │ │ │ │ │ │ │ initialized ticks initialized ticks init. init. init. Each word = 256 bits = 256 ticks. A 1-bit means the tick at that index is initialized. ``` We encourage anyone trying to get a deeper understanding of Ramses to read the Uniswap V3 Book. ## Calculating the memory positions of all Ticks Now that we fetched all **bitMaps**, we check which ticks are initialized and calculate the **tick position** from the **word index** and the **tickSpacing** of the pool. We check if a tick is **initialized** inside the word by shifting a bit by the index we are looking at and performing a bitwise AND operation: ```typescript theme={null} const bit = 1n const initialized = (bitmap & (bit << BigInt(i))) !== 0n ``` If the tick is **initialized**, we revert the compression from tick to word we made earlier by multiplying the word index with 256, which is the same as left shifting by 8 bit, adding the position we are currently at, and multiplying with the tickSpacing: ```typescript theme={null} const tickIndex = (ind * 256 + i) * tickSpacing ``` The whole loop looks like this: ```typescript theme={null} const tickIndices: number[] = [] for (let j = 0; j < wordPosIndices.length; j++) { const ind = wordPosIndices[j] const bitmap = results[j] if (bitmap !== 0n) { for (let i = 0; i < 256; i++) { const bit = 1n const initialized = (bitmap & (bit << BigInt(i))) !== 0n if (initialized) { const tickIndex = (ind * 256 + i) * tickSpacing tickIndices.push(tickIndex) } } } } ``` We now have an array containing the indices of all initialized Ticks. ## Fetching all Ticks by their indices We use the multicallProvider again to execute an aggregated read call for all tick indices. We create an array of call Promises again and use `.all()` to make our multicall: ```typescript theme={null} const calls: any[] = [] for (const index of tickIndices) { calls.push(poolContract.ticks(index)) } const results = await multicallProvider.all(calls) ``` Again, the order of the results array is the same as the elements in **tickIndices**. We are able to combine the **tickIndices** and **results** array to create an array of `Tick` objects: ```typescript theme={null} const allTicks: Tick[] = [] for (let i = 0; i < tickIndices.length; i++) { const index = tickIndices[i] const ethersResponse = results[i] const tick = new Tick({ index, liquidityGross: JSBI.BigInt(ethersResponse.liquidityGross.toString()), liquidityNet: JSBI.BigInt(ethersResponse.liquidityNet.toString()), }) allTicks.push(tick) } ``` We need to parse the response from our RPC provider to JSBI values that the v3-sdk can work with. ## Constructing the Pool We have everything to construct our `Pool` now: ```typescript theme={null} const usdcWethPool = new Pool( USDC, WETH, feeAmount, slot0.sqrtPriceX96, liquidity, slot0.tick, allTicks ) ``` With this fully initialized Pool, we can make accurate offchain calculations. ## Next Steps Now that you are familiar with fetching Pool data, continue your journey with the [next example](./03-active-liquidity) on visualizing the Liquidity density of a pool. # Active Liquidity Source: https://tech.ramses.xyz/sdk/guides/advanced/03-active-liquidity ## Introduction This guide will cover how to fetch and compute the active liquidity in the specific Tick ranges of a pool. It is based on the [Liquidity Density example](https://github.com/Uniswap/examples/tree/main/v3-sdk/liquidity-density) and can be seen used in production, albeit in a more sophisticated way, in the [Uniswap Analytics](https://info.uniswap.org/#/pools) website. If you need a briefer on the SDK and to learn more about how these guides connect to the examples repository, please visit our [background](../01-background) page! In this guide, we will use the V3 subgraph to fetch all ticks from **theGraph** and compute the active liquidity our Pool can use at each Tick. We then use `recharts` to draw a chart that visualizes our Pool's liqudity density. This guide will cover: 1. Getting the tickSpacing and currently active Tick from the Pool 2. Calculating active liquidity from net liquidity 3. Drawing a chart from the Tick data This guide will not cover: * Specifics of working with the recharts library. You can read more about that [here](https://recharts.org/en-US/). At the end of the guide, we should be able to visualize the liquidity of any V3 Pool. ## Understanding Active Liquidity To visualize the distribution of active liquidity in our Pool, we want to draw our Chart around the currently active Tick. For that we have to first understand: * What is an initialized Tick? * What is the current Tick? ### Initialized Ticks When providing liquidity for a pool, the LP decides the **price range** in which the liquidity should be provided, and the amount of liquidity to be provided. The pool understands the position as **liquidity between the lower and upper Tick**. The Tick Index in this context is a representation of the price between the Pool's assets. Looking at this [visualization](https://www.desmos.com/calculator/oduetjzfp4) of multiple positions in a V3 Pool, we can see that the liquidity available for a swap does not change inside a position, but when crossing into the next position. This is what the **Initialized Ticks** of a Pool represent - they are a representation of the start or end of one or more positions. ```text theme={null} Active Liquidity liquidityNet at each initialized tick ▲ ▲ │ ┌──────┐ │ │ │ Pos1 │ │ +L1 +L2 -L2 -L1 │ │ ┌───┴──┐ │ │ │ │ │ │ │ │ Pos2 │ │ ▼ ▼ ▼ ▼ │ ───┘ │ │ │ ───────────────────────────────── │ │ └─── │ └──────────────────► tick └──────────────────────────────► tick tA tB tC tD tA tB tC tD When Pos1 starts at tA, liquidityNet = +L1. When Pos2 starts at tB, liquidityNet = +L2. When Pos2 ends at tC, liquidityNet = -L2. When Pos1 ends at tD, liquidityNet = -L1. ``` When entering or leaving a position, its liquidity is added or removed from the **active liquidity available** for a Swap. The initialized Ticks store this **change in available liquidity** in the `liquidityNet` field. The change is always stored in relation to the currently active Tick - the current price. When the price crosses an initialized Tick, it gets updated and liqudity that was previously added when crossing the Tick would now be removed and vice versa. The `liquidityGross` value represents the gross value of liquidity referencing the tick. This is important for the edge case that one position ends at a Tick and a second position with exactly the same liquidity value would start at the Tick. In this case `liquidityNet` would be **0** but `liquidityGross` would still have a value, which ensures that the Tick is not deleted from the Pool. To visualize liquidity in a graph, we will only need to consider the changes, so it's sufficient to fetch the Ticks with `liquidityNet` not 0. ### Fetching initialized Ticks To fetch all ticks of our Pool, we will use the [Uniswap V3 subgraph](https://thegraph.com/explorer/subgraphs/5zvR82QoaXYFyDEKLZ9t6v9adgnptxYpKpSbxtgVENFV?view=Query\&chain=arbitrum-one). To visualize active liquidity, we need the **tickIdx**, the **liquidityGross** and the **liquidityNet**. We define our GraphQL query and [send a POST request](https://axios-http.com/docs/post_example) to the V3 subgraph API endpoint: ```typescript theme={null} axios.post( "https://gateway.thegraph.com/api/${api_key}/subgraphs/id/5zvR82QoaXYFyDEKLZ9t6v9adgnptxYpKpSbxtgVENFV", {"query": `{ ticks( where: {poolAddress: "${poolAddress.toLowerCase()}", liquidityNet_not: "0"} first: 1000, skip: ${skip}, orderBy: tickIdx, orderDirection: asc ) { tickIdx liquidityGross liquidityNet } }` }, { headers: { "Content-Type": "application/json" } } ) ``` We only fetch the ticks that **have liquidity**, and we convert the poolAddress to **lower case** for the subgraph to work with. To make sure the Ticks are ordered correctly, we also define the **order direction** in the query. GraphQL is only able to fetch 1000 records at a time. If a pool has more than 1000 initialized ticks, multiple calls are necessary to get all of them. The ticks we got from **theGraph** have this format: ```typescript theme={null} interface GraphTick { tickIdx: string liquidityGross: string liquidityNet: string } ``` ### Current Tick The current Tick of the Pool represents the **current Price** after the last swap. Considering that the initialized Ticks only represent positions, we see that it is not necessarily one of the initialized Ticks but can be at any point in between them. The active liqudity at the current Price is also stored in the smart contract - we already fetched it with the `liquidity` function in the [previous guide](./02-pool-data). ### Tickspacing Only the Ticks with indices that are divisible with 0 remainder by the tickspacing of a Pool are initializable. This is a convention defined by the protocol to save gas. The Tickspacing of the Pool is dependent on the Fee Tier. Pools with lower fees are meant to be used for more stable Token Pairs and allow for more granularity in where LPs position their liquidity. We can get the `tickSpacing` from the `TICK_SPACINGS` enum exposed by the `v3-sdk`: ```typescript theme={null} import { TICK_SPACINGS } const tickSpacing = TICK_SPACINGS[fee] ``` Alternatively, if we have already constructed a `Pool` object, we could just call `Pool.tickSpacing()`. ### Putting it all together For the purpose of visualizing the liquidity density of the Pool, it rarely makes sense to display the full Tick Range of the Pool, as the vast majority of liquidity will be focused in a narrow price range. Instead, we will display a sensible number of Ticks around the current price. ## Calculating active liquidity We know the spacing between Ticks and the Initialized Ticks where active liquidity changes. All we have to do is start calculating from the current Tick and iterate outwards. The code mentioned in the following snippets can be found in [`active-liquidity.ts`](https://github.com/Uniswap/examples/tree/main/v3-sdk/pool-data/src/libs/active-liquidity.ts). To draw our chart we want a data structure that looks something like this: ```typescript theme={null} interface TickProcessed { tickIdx: number, liquidityActive: JSBI, liquidityNet: JSBI, price0: string, price1: string, isCurrent: boolean } ``` To access the initialized Ticks directly from their Tick Index, we store them in a [Record](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type): ```typescript theme={null} const tickIdxToTickDictionary: Record = Object.fromEntries( ticks.map((graphTick) => [graphTick.tickIdx, graphTick]) ) ``` The `ticks` variable in this code snippet is the result we got from the V3 Subgraph earlier. We want to mark the Tick closest to the current Price and we want to be able to display the prices at a Tick to the user. We calculate the **initializable Tick** closest to the current price and create the active Tick that we start from: ```typescript theme={null} import { tickToPrice } from '@kingdomdotone/v3-sdk' const activeTickIdx = Math.floor(pool.tickCurrent / tickSpacing) * tickSpacing const activeTickProcessed: TickProcessed = { tickIdx: activeTickIdx, liquidityActive: pool.liquidity, liquidityNet: JSBI.BigInt(0), price0: tickToPrice(tokenA, tokenB, activeTickIdx).toFixed(6), price1: tickToPrice(tokenB, tokenA, activeTickIdx).toFixed(6), isCurrent: true } ``` Here we also calculate the price of the tokens from the tickIdx, the `v3-sdk` exports a handy utility function for that, `tickToPrice`. We store the Price as a string as we won't make any further calculations in this example. We will instead use it to display prices in the tooltip of our chart. Notice how the `price0` is the Price of tokenA in terms of tokenB and the `price1` is the Price of tokenB in terms of tokenA **at the specified Tick**. If the **current Tick is initialized**, we also need to set the **liquidityNet** to correctly handle moving out of the position: ```typescript theme={null} const currentTickInitialized = tickIdxToTickDictionary[activeTickIdx] if (currentTickInitialized !== undefined) { activeTickProcessed.liquidityNet = JSBI.BigInt(currentTickInitialized.liquidityNet) } ``` We now start iterating outwards from the active Tick and compute the active liquidity for each Tick we want to display. The processed Tick is then saved in an Array of `TickProcessed`. We choose an arbitrary number of Ticks we want to display, for this example we calculate 100 Ticks in each direction. ```typescript theme={null} import { TickMath, tickToPrice } from '@kingdomdotone/v3-sdk' let previousTickProcessed = { ...activeTickProcessed } processedTicks: TickProcessed[] = [] for (let i = 0; i < 100; i++) { const currentTickIdx = previousTickProcessed.tickIdx + tickSpacing if (currentTickIdx > TickMath.MAX_TICK) { break } const currentTickProcessed = { liquidityActive: previousTickProcessed.liquidityActive, tickIdx: currentTickIdx, liquidityNet: JSBI.BigInt(0), price0: tickToPrice(token0, token1, currentTickIdx), price1: tickToPrice(token1, token0, currentTickIdx), isActive: false } ... } ``` We calculate one Tick at a time, and we need to make sure our Tick stays inside the possible price range by checking against `TickMath.MAX_TICK`. Again, we check if our current Tick is initialized and if so, recalculate the active liquidity: ```typescript theme={null} for (let i = 0; i < 100; i++) { ... const currentTickInitialized = tickIdxToTickDictionary[currentTickIdx] if (currentTickInitialized !== undefined) { currentTickProcessed.liquidityNet = JSBI.BigInt(currentTickInitialized.liquidityNet) currentTickProcessed.liquidityActive = JSBI.add( previousTickProcessed.liquidityActive, JSBI.BigInt(currentTickInitialized.liquidityNet) ) } processedTicks.push(currentTickProcessed) previousTickProcessed = currentTickProcessed } ``` After we are done calculating the next 100 Ticks after the current Tick, we iterate in the opposite direction for the previous Ticks. Iterating downwards, we need to subtract the net liquidity where we added it when iterating upwards. You can find a full code example in the [Uniswap Example repository](https://github.com/Uniswap/examples/blob/main/v3-sdk/pool-data/src/libs/active-liquidity.ts). We are finally able to combine the previous, active and subsequent Ticks: ```typescript theme={null} const allProcessedTicks = previousTicks.concat(activeTickProcessed).concat(subsequentTicks) ``` ## Drawing the Chart We are done with our calculations and move on to displaying the data. **Recharts** is not able to handle JSBI, so we need to convert the Array we created to a format it can handle: ```typescript theme={null} const chartTicks: TicksChart[] = allProcessedTicks.map((tickProcessed) => { return {...processedTick, liquidityActiveChart: parseFloat(tickProcessed.liquidityActive.toString())} }) ``` The loss of precision will not be visually noticeable in the chart and we are still able to display the exact number in a Tooltip if we wish to. Liquidity is stored in a `uint128` format onchain, so the maximum loss of precision will be far smaller than the number of decimals of almost any ERC20 Token. Finally, we draw the Chart: ```jsx theme={null} {chartTicks.map((entry, index) => { return ( ) })} ``` In a real application, you will probably want to format the chart properly and display additional information for users. Check out the full [code example](https://github.com/Uniswap/examples/blob/main/v3-sdk/pool-data/src/libs/active-liquidity.ts) to this guide and the official recharts [documentation](https://recharts.org/). You can also take a look at the [Uniswap Info](https://github.com/Uniswap/v3-info) repository to see a similar chart used in production. ## Locked Liquidity If you run the example, you will notice that the chart also displays a custom tooltip with additional information that we didn't touch on in this example. The total locked liqudity in the tooltip represents the sum of positions in the currency locked at the selected Tick. It is calculated as the maximum token output of a swap when crossing to the next Tick. The V3 pool here is initialized with only the liquidity of the current Tick. Depending on your use case, it may make sense to display this value. You can find the full code in the [code example](https://github.com/Uniswap/examples/blob/main/v3-sdk/pool-data/src/libs/active-liquidity.ts). ## Next Steps Now that you are familiar with liquidity data, consider checking out our [next guide](./04-price-oracle) on using Ramses V3 as a Price Oracle. # Ramses V3 as a Price Oracle Source: https://tech.ramses.xyz/sdk/guides/advanced/04-price-oracle ## Introduction This guide will cover how to fetch price observations from a V3 pool to get onchain asset prices. It is based on the [Price Oracle example](https://github.com/Uniswap/examples/tree/main/v3-sdk/oracle), found in the Uniswap code examples [repository](https://github.com/Uniswap/examples). To run this example, check out the guide's [README](https://github.com/Uniswap/examples/blob/main/v3-sdk/oracle/README) and follow the setup instructions. If you need a briefer on the SDK and to learn more about how these guides connect to the examples repository, please visit our [background](../01-background) page! In this example we will use **ethers JS** to observe the development of a Pool's current tick over several blocks. We will then calculate the time weighted average price - **TWAP**, and time weighted average liquidity - **TWAL** over the observed time interval. This guide will **cover**: 1. Understanding observations 2. Fetching observations 3. Computing TWAP 4. Computing TWAL 5. Why prefer observe over observations Before diving into this guide, consider reading the theory behind using Ramses V3 as an [Onchain Oracle](../../../../concepts/protocol/oracle). For this guide, the following packages are used: * [`@kingdomdotone/v3-sdk`](https://www.npmjs.com/package/@kingdomdotone/v3-sdk) The core code of this guide can be found in [`oracle.ts`](https://github.com/Uniswap/examples/tree/main/v3-sdk/oracle/src/libs/oracle.ts) ## Understanding Observations First, we need to create a Pool contract to fetch data from the blockchain. Check out the [Pool data guide](./02-pool-data) to learn how to compute the address and create an **ethers Contract** to interact with. ```typescript theme={null} const poolContract = new ethers.Contract( poolAddress, IUniswapV3PoolABI.abi, provider ) ``` All V3 pools store observations of the current tick and the block timestamp. To minimize pool deployment costs, only one Observation is stored in the contract when the Pool is created. Anyone who is willing to pay the gas costs can [increase](../../../../contracts/reference/core/RamsesV3Pool.md#increaseobservationcardinalitynext) the number of stored observations to up to `65535`. If the Pool cannot store an additional Observation, it overwrites the oldest one. We create an interface to map our data to: ```typescript theme={null} interface Observation { secondsAgo: number tickCumulative: bigint secondsPerLiquidityCumulativeX128: bigint } ``` To fetch the `Observations` from our pool contract, we will use the [`observe`](../../../../contracts/reference/core/RamsesV3Pool.md#observe) function: ```solidity theme={null} function observe( uint32[] secondsAgos ) external view override noDelegateCall returns ( int56[] tickCumulatives, uint160[] secondsPerLiquidityCumulativeX128s ) ``` We first check how many observations are stored in the Pool by calling the `slot0` function. ```typescript theme={null} const slot0 = await poolContract.slot0() const observationCount = slot0.observationCardinality const maxObservationCount = slot0.observationCardinalityNext ``` The `observationCardinalityNext` is the maximum number of Observations the Pool **can store** at the moment. The `observationCardinality` is the actual number of Observations the Pool **has currently stored**. Observations are only stored when the `swap()` function is called on the Pool or when a **Position is modified**, so it can take some time to write the Observations after the `observationCardinalityNext` was increased. If the number of Observations on the Pool is not sufficient, we need to call the `increaseObservationCardinalityNext()` function and set it to the value we desire. This is a write function as the contract needs to store more data on the blockchain. We will need a **wallet** or **signer** to pay the corresponding gas fee. In this example, we want to fetch 10 observations. ```typescript theme={null} import { ethers } from 'ethers' let provider = new ethers.providers.WebSocketProvider('rpcUrl...') let wallet = new ethers.Wallet('private_key', provider) const poolContract = new ethers.Contract( poolAddress, IUniswapV3PoolABI.abi, wallet ) const txRes = await poolContract.increaseObservationCardinalityNext(10) ``` The Pool will now fill the open Observation Slots. As someone has to pay for the gas to write the observations, writing to the array of observations is part of the `swap()` and the `modifyPosition()` function of the Pool. Saving an Observation is a write operation on the blockchain and therefore costs gas. This means that the pool will only be able to save observations for blocks where write calls are executed on the Pool contract. If no Observation is stored for a block, it is calculated as the time weighted arithmetic mean between the two closest Observations. Because of this, we can be sure the oldest Observation is **at least** 10 blocks old. It is very likely that the number of blocks covered is bigger than 10. ## Fetching Observations We are now sure that at least 10 observations exist, and can safely fetch observations for the last 10 blocks. We call the `observe` function with an array of numbers, representing the timestamps of the Observations in seconds ago from now. In this example, we calculate averages over the last ten blocks so we fetch 2 observations with 9 times the blocktime in between. Fetching an Observation `0s` ago will return the **most recent Observation** interpolated to the current timestamp as observations are written at most once a block. ```typescript theme={null} const timestamps = [ 0, 108 ] const [tickCumulatives, secondsPerLiquidityCumulatives] = await poolContract.observe(timestamps) const observations: Observation[] = timestamps.map((time, i) => { return { secondsAgo: time tickCumulative: BigInt(tickCumulatives[i]) secondsPerLiquidityCumulativeX128: BigInt(secondsPerLiquidityCumulatives[i]) } }) ``` We map the response from the RPC provider to match our Observations interface. ## Calculating the average Price To calculate the time weighted average price (TWAP) in the period we fetched, we first need to understand what the values we fetched mean. The `tickCumulative` value is a snapshot of the `tick accumulator` at the timestamp we fetched. The Tick Accumulator stores the sum of all current ticks at every second since the Pool was initialised. Its value is therefore increasing with every second. We cannot directly use the value of a single Observation for anything meaningful. Instead we need to compare the **difference** between two Observations and calculate the **time weighted arithmetic mean**. ```typescript theme={null} const diffTickCumulative = observations[0].tickCumulative - observations[1].tickCumulative const secondsBetween = 108 const averageTick = diffTickCumulative / secondsBetween ``` Now that we know the average active Tick over the last 10 blocks, we can calculate the price with the `tickToPrice` function, which returns a [`Price`](../../../core/reference/classes/Price) Object. Check out the [Pool data](./02-pool-data) guide to understand how to construct a Pool Object and access its properties. We don't need the full Tick Data for this guide. ```typescript theme={null} import { tickToPrice, Pool } from '@kingdomdotone/v3-sdk' const pool = new Pool(...) const TWAP = tickToPrice(pool.token0, pool.token1, averageTick) ``` We have now calculated the **time weighted average price** over the last 108 seconds. Let's continue with the average liquidity. ## Calculating the average Liquidity To understand the term **active Liquidity**, check out the [previous guide](./03-active-liquidity). Similar to the `tick accumulator`, the `liquidity accumulator` stores a sum of values for every second since the Pool was initialized and increases with every second. Because of the size of the active liquidity value, it is impractical to just add up the active liquidity. Instead the **seconds per liquidity** are summed up. The `secondsPerLiquidityX128` value is calculated by shifting the seconds since the last Observation by 128 bits and dividing that value by the active liquidity. It is then added to the accumulator. ```solidity theme={null} uint32 delta = blockTimestamp - last.blockTimestamp; uint128 secondsPerLiquidityX128 = (uint160(delta) << 128) / liquidity uint160 secondsPerLiquidityCumulativeX128 = last.secondsPerLiquidityCumulativeX128 + secondsPerLiquidityX128 ``` `last` is the most recent Observation in this illustrative code snippet. Consider taking a look at the [Solidity Oracle library](https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/Oracle.sol) to see the actual implementation. Let's invert this calculation and find the average active liquidity over our observed time period. ```typescript theme={null} const diffSecondsPerLiquidityX128 = observations[0].secondsPerLiquidityCumulativeX128 - observations[1].secondsPerLiquidityCumulativeX128 const secondsBetweenX128 = BigInt(108) << 128 const TWAL = secondsBetweenX128 / diffSecondsPerLiquidityX128 ``` This **time weighted average liquidity** is the harmonic mean over the time period observed. The costs associated with manipulating/ changing the liquidity of a Pool are **orders of magnitude smaller** than with manipulating the price of the assets, as **prices** will be arbitraged for assets **with more than one market**. Adding massive amounts of liquidity to a Pool and withdrawing them after a block has passed more or less only costs gas fees. Use the **TWAP** with care and consider handling outliers. ## Why prefer observe over observations? As touched on previously, the `observe` function calculates Observations for the timestamps requested from the nearest observations stored in the Pool. It is also possible to directly fetch the stored observations by calling the `observations` function with the index of the Observation that we are interested in. Let's fetch all observations stored in our Pool. We already made sure the observationCardinality is 10. The solidity struct `Observation` looks like this: ```solidity theme={null} struct Observation { // the block timestamp of the observation uint32 blockTimestamp; // the tick accumulator, i.e. tick * time elapsed since the pool was first initialized int56 tickCumulative; // the seconds per liquidity, i.e. seconds elapsed / max(1, liquidity) since the pool was first initialized uint160 secondsPerLiquidityCumulativeX128; // whether or not the observation is initialized bool initialized; } ``` It is possible to request any Observation up to (excluding) index `65535`, but indices equal to or greater than the `observationCardinality` will return uninitialized Observations. The full code to the following code snippets can be found in [`oracle.ts`](https://github.com/uniswap/examples/blob/main/v3-sdk/oracle/src/libs/oracle.ts) ```typescript theme={null} let requests = [] for (let i = 0; i < 10; i++) { requests.push(poolContract.observations(i)) } const results = await Promise.all(requests) ``` We can only request one Observation at a time, so we create an Array of Promises to get an Array of Observations. We already see one difference, to using the `observe` function here. While `observe` creates an array onchain in the smart contract and returns it, calling `observations` requires us to make multiple RPC calls. Depending on our setup and the Node we are using, either option can be faster, but making multiple RPC calls always has the danger of the blockchain state changing between our calls. While it is extremely unlikely, it is still possible that our Node updates with a new block and new Observation in between our calls. Because we access indices of an array, this would give us an unexpected result that we need to handle as an edge case in our implementation. One way to handle this behaviour is deploying or [using](https://github.com/mds1/multicall) a Contract with a [multicall](https://solidity-by-example.org/app/multi-call/) functionality to get all observations with one request. You can also find an example of a JS multicall in the [Pool data guide](./02-pool-data). We map the RPC result to the Typescript interface that we created: ```typescript theme={null} const utcNow = Math.floor(Date.now() / 1000) const observations = results.map((result) => { const secondsAgo = utcNow - Number(result.blockTimeStamp) return { secondsAgo, tickCumulative: BigInt(result.tickCumulative), secondsPerLiquidityCumulativeX128: BigInt(result.secondsPerLiquidityCumulativeX128) } }).sort((a, b) => a.secondsAgo - b.secondsAgo) ``` We now have an Array of observations in the same format that we are used to. Because Observations are stored in a **fixed size array** with always the oldest Observation overwritten if a new one is stored, they are **not sorted**. We need to sort the result by the timestamp. The timestamps of the Observations we got are correspondent to blocks where **Swaps or Position changes** happened on the Pool. Because of this, we would need to calculate Observations for specific intervals manually from the **surrounding Observations**. In conclusion, it is much harder to work with `observations` than with `observe`, and we need to consider multiple edge cases. For this reason, it is recommended to use the `observe` function. ## Next Steps Now that you are familiar with the Oracle feature of Ramses V3, consider checking out the [next guide](./05-range-orders) on **Range Orders**. # Range Orders Source: https://tech.ramses.xyz/sdk/guides/advanced/05-range-orders ## Introduction This guide will cover how single-side liquidity provisioning can be used to execute **Limit Orders** on Ramses V3 Pools. An example to showcase this concept can be found in the [Range Order example](https://github.com/Uniswap/examples/tree/main/v3-sdk/range-order), in the Uniswap code examples [repository](https://github.com/Uniswap/example). To run this example, check out the guide's [README](https://github.com/Uniswap/examples/blob/main/v3-sdk/price-oracle/README) and follow the setup instructions. This guide builds on top of the [Pooling Liquidity guides](../liquidity/01-position-data). We recommend going through this section of the docs before imnplementing Range Orders. In this example we will create a single-side liquidity position with the [RamsesV3PositionManager](../../../../contracts/reference/periphery/RamsesV3PositionManager) contract. We will then use **ethers JS** to observe the price of the Pool on new blocks and withdraw the liquidity when our target is reached. This guide will **cover**: 1. Understanding Range Orders 2. Calculating our Tick Range 3. Creating a single-side liquidity position 4. Observing the price of the Pool 5. Closing the Limit Order Before working through this guide, consider checking out the Range Orders [concept page](../../../../concepts/protocol/range-orders) to understand how Limit orders can be executed with Ramses V3. For this guide, the following packages are used: * [`@kingdomdotone/v3-sdk`](https://www.npmjs.com/package/@kingdomdotone/v3-sdk) * [`@uniswap/sdk-core`](https://www.npmjs.com/package/@uniswap/sdk-core) The core code of this guide can be found in [`range-order.ts`](https://github.com/Uniswap/examples/tree/main/v3-sdk/range-order/src/libs/range-order.ts). ## Understanding Range Orders If you have read the [Range Order Concept page](../../../../concepts/protocol/range-orders), you can skip this section. Positions on a V3 Pool are always created with a Tick range in which their liquidity is accessible to swaps on the Pool. Lets look at the return value of the RamsesV3PositionManager contract when calling the `positions` function with a Position `tokenId`. ```solidity theme={null} function positions( uint256 tokenId ) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, // Lower Boundary of Position int24 tickUpper, // Upper Boundary of Position uint128 liquidity, // Liquidity uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ) ``` We see that a position only stores a single `liquidity` value, and a `tickLower` and `tickUpper` value that define the range in which the liquidity of the Position can be utilised for Swaps. The actual **amount** of `token0` and `token1` that a Pool owes the Position owner is calculated from the parts of the liquidity position that are to the left and right of the current Tick. Liquidity left of the current Tick is denominated in `token0` and liquidity right of the current Tick is denominated in `token1`. If a new Position is created and the Tick Range of the position does not include the current Tick of the Pool, only one of the two Tokens in the Pool can be provided. We will call this a **Single Side Liquidity Position**. Range Order When the current Tick of the Pool moves across the Position, the ratio of `token0` and `token1` will change, and ultimately inverse if the current Tick moves out of the position on the other side. We will utilise this behaviour to provide liquidity with `token1` and withdraw the position when it has been converted to `token0`. ## Calculating the Tick Range Our goal for this guide is to create a [Take Profit Order](../../../../concepts/protocol/range-orders.md#take-profit-orders) that trades `token0` for `token1` when the Price of `token0` increases by 5%. To create our Position, we need to first decide the Tick Range that we want to provide liquidity in. ### Upper Tick We [create a Pool](./02-pool-data) that represents the V3 Pool we are interacting with and get the `token0Price`. We won't need full tick data in this example. ```typescript theme={null} import { Pool } from '@kingdomdotone/v3-sdk' ... const pool = new Pool(token0, token1, fee, sqrtPriceX96, liquidity, tickCurrent) const currentPrice = pool.token0Price ``` Next we increase the `Price` by 5%. We create a new Price with a numerator 5% higher than our current Price: ```typescript theme={null} import { Price, Fraction } from '@uniswap/sdk-core' const targetFraction = Price.asFraction.multiply(new Fraction(100 + 5, 100)) const targetPrice = new Price( currentPrice.baseCurrency, currentPrice.quoteCurrency, targetFraction.denominator, targetFraction.numerator ) ``` Be aware that the `numerator` and `denominator` parameters are ordered differently in the `Fraction` and `Price` constructor. We have calculated our target Price but we still need to find the **nearest usable tick** to create our Position. As Positions can only start and end at initializable Ticks of the Pool, so we can only create a Range Order to a Price that exactly matches an initializable Tick. We use the `priceToClosestTick` function to find the closest tick to our targetPrice. We then use the `nearestUsableTick` function to find the closest initializable Tick for the `tickSpacing` of the `Pool`. ```typescript theme={null} import {priceToClosestTick, nearestUsableTick} from '@kingdomdotone/v3-sdk' let targetTick = nearestUsableTick( priceToClosestTick(targetPrice), pool.tickSpacing ) ``` This nearest Tick will most likely not **exactly** match our Price target. Depending on our personal preferences we can either err on the higher or lower side of our target by adding or subtracting the `tickSpacing` if the initializable Tick is lower or higher than the theoretically closest Tick. ### Lower Tick We now find the lower Tick by subtracting the tickSpacing from the upper Tick: ```typescript theme={null} let lowerTick = targetTick - pool.tickSpacing ``` If the price difference is too low, the lower tick may be left of the current Tick of the Pool. In that case we would not be able to provide single side liquidity. We can either throw an Error or increase our Position by one Tick. ```typescript theme={null} if (tickLower <= pool.tickCurrent) { tickLower += pool.tickSpacing targetTick += pool.tickSpacing } ``` We now have a lower and upper Tick for our Position, next we need to construct and mint it. ## Creating the Single Side Liquidity Position We will use the `RamsesV3PositionManager` and `Position` classes from the `v3-sdk` to construct our position. We then use an **etherJS** wallet to mint our Position onchain. If you are not familiar with liquidity Positions, check out the [liquidity position guides](../liquidity/01-position-data). ### Minting the Position We create a `Position` object with our ticks and the amount of tokens we want to deposit: ```typescript theme={null} import { Position } from '@kingdomdotone/v3-sdk' const position = Position.fromAmount0({ pool: pool, tickLower: tickLower, tickUpper: targetTick, amount0: amount, useFullPrecision: true }) ``` Before we mint our position, we need to give the `RamsesV3PositionManager` Contract an approval to transfer our tokens. We can find the Contract address from the [Ramses contract addresses](https://docs.ramses.xyz/security/contract-addresses) or the [Uniswap GitHub](https://github.com/Uniswap/v3-periphery/blob/main/deploys) for Ethereum mainnet forks. For local development, the contract address is the same as the network we are forking from. So if we are using a local fork of mainnet like described in the [Local development guide](../02-local-development), the contract address would be the same as on mainnet. ```typescript theme={null} import ethers from 'ethers' const provider = new ethers.providers.JsonRpcProvider(rpcUrl) const wallet = new ethers.Wallet(privateKey, provider) const tokenContract = new ethers.Contract( pool.token0.address, ERC20_ABI, wallet ) await tokenContract['approve']( NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS, ethers.BigNumber.from(amount) ) ``` Once we have our approval, we create the calldata for the **Mint** call using the `RamsesV3PositionManager`: ```typescript theme={null} import {MintOptions, RamsesV3PositionManager} import { Percent } from '@uniswap/sdk-core' const mintOptions: MintOptions = { recipient: wallet.address, deadline: Math.floor(Date.now() / 1000) + 60 * 20, slippageTolerance: new Percent(50, 10_000), } const { calldata, value } = RamsesV3PositionManager.addCallParameters( order.position, mintOptions ) ``` We can populate our mint transaction and send it with our wallet: ```typescript theme={null} const transaction = { data: calldata, to: NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS, value: ethers.BigNumber.from(value), from: address, maxFeePerGas: MAX_FEE_PER_GAS, maxPriorityFeePerGas: MAX_PRIORITY_FEE_PER_GAS, } const txRes = await wallet.sendTransaction(transaction) ``` You can find full code examples for these code snippets in [`range-order.ts`](https://github.com/uniswap/examples/blob/main/v3-sdk/range-order/src/libs/range-order.ts). ### Getting the tokenId We want to read the response to our `Mint` function call to get **the position id**. We will need the positionId to fetch the Position Info from the NFTPositionManager contract. We wait for the transaction receipt and fetch the result using `trace_transaction`: ```typescript theme={null} let receipt = null let mintCallOutput while (receipt === null) { try { receipt = await provider.getTransactionReceipt(txRes.hash) if (receipt === null) { continue } else { const callTraces = await provider.send('trace_transaction', [ txRes.hash ]) mintCallOutput = callTraces[0].result.output } } catch (e) { break } } ``` Your Node provider may not support this call. In that case you can also call the RamsesV3PositionManager Contract with the wallet address and identify the Range Order Position manually: ```typescript theme={null} const mintCallOutput = await wallet.call(transaction) ``` We get a raw byte string as a return value from this function and have to parse it ourselves. We decode the result with the **ethers AbiCoder**. The solidity function has this signature: ```solidity theme={null} function mint( struct IRamsesV3PositionManager.MintParams params ) external returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1) ``` So we need the first parameter to get the `tokenId`: ```typescript theme={null} const decodedOutput = ethers.utils.defaultAbiCoder.decode( ['tuple(uint256, uint128, uint256, uint256)'], mintCallOutput )[0] const tokenId = decodedOutput.toString() ``` Ethers handles the string decoding of the byte string we got and parses it to its internal datatypes. The decodedOutput we get from the AbiCoder is a `ethers.Bignumber` so we need to cast it to a string to use it with the SDK. We have created our Range Order Position, now we need to monitor it. In the [code example](https://github.com/uniswap/examples/blob/main/v3-sdk/range-order/src/libs/range-order.ts#L180) we use `wallet.call` to get the position id. `call` and `trace_call` both simulate a transaction on the connected node and return the expected output, `trace_call` gives us a much more detailed output though. Depending on the use case, either can be the better choice. In a production environment you would prefer to wait for the `transactionReceipt` like described earlier to ensure the transaction was actaully included in the blockchain. ## Observing the Price We need to observe the price of the Pool and withdraw our Position once the `tickCurrent` has moved across our Position. We use **ethers JS** to watch for new blocks and fetch the latest Pool data: ```typescript theme={null} provider.on('block', refreshPool()) function refreshPool() { ... // construct Pool contract const slot0 = await poolContract.slot0() const tickCurrent = slot0.tick } ``` It is not necessary to calculate the Price from the tick we fetched, as executing the limit order is dependent on the tick range we defined and not the Price from which we calculated it. ```typescript theme={null} if (tickCurrent > targetTick) { // Withdraw position } ``` We check if the tick has crossed our position, and if so we withdraw the Position. ## Closing the Limit Order We call the RamsesV3PositionManager Contract with the `tokenId` to get all info of our position as we may have gotten fees from trades on the Pool: ```typescript theme={null} import INON_FUNGIBLE_POSITION_MANAGER from '@uniswap/v3-periphery/artifacts/contracts/RamsesV3PositionManager.sol/RamsesV3PositionManager.json' const positionManagerContract = new ethers.Contract( NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS, INONFUNGIBLE_POSITION_MANAGER.abi, provider ) const positionInfo = await positionManagerContract.positions(tokenId) ``` We use the `RamsesV3PositionManager`, the `pool`, `positionInfo` and `tokenId` to create call parameter for a `decreaseLiquidity` call. We start with creating `CollectOptions`: ```typescript theme={null} import { Percent, CurrencyAmount } from '@uniswap/sdk-core' import { CollectOptions, RemoveLiquidityOptions } from '@kingdomdotone/v3-sdk' import JSBI from 'jsbi' const collectOptions: Omit = { expectedCurrencyOwed0: CurrencyAmount.fromRawAmount( pool.token0, JSBI.BigInt(positionInfo.tokensOwed0.toString()) ), expectedCurrencyOwed1: CurrencyAmount.fromRawAmount( pool.token1, JSBI.BigInt(positionInfo.tokensOwed1.toString()) ), recipient: wallet.address, } ``` Next we create `RemoveLiquidityOptions`. We remove all our liquidity so we set liquidityPercentage to `1`: ```typescript theme={null} const removeLiquidityOptions: RemoveLiquidityOptions = { deadline: Math.floor(Date.now() / 1000) + 60 * 20, slippageTolerance: new Percent(50, 10_000), tokenId, // percentage of liquidity to remove liquidityPercentage: new Percent(1), collectOptions, } ``` We create a new `Position` object from the updated `positionInfo` info we fetched: ```typescript theme={null} const updatedPosition = new Position{ pool, liquidity: JSBI.BigInt(currentPositionInfo.liquidity.toString()), tickLower: currentPositionInfo.tickLower, tickUpper: currentPositionInfo.tickUpper, } ``` We have everything to create our calldata now and are ready to make our Contract call: ```typescript theme={null} const { calldata, value } = RamsesV3PositionManager.removeCallParameters( updatedPosition, removeLiquidityOptions ) const transaction = { data: calldata, to: NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS, value: value, from: address, maxFeePerGas: MAX_FEE_PER_GAS, maxPriorityFeePerGas: MAX_PRIORITY_FEE_PER_GAS, } const result = await wallet.sendTransaction(transaction) ``` Our liquidity position is removed and we receive `token1` at the Price we have specified. We have successfully executed a range order. ## Caveats Executing a range order has certain limitations that may have become obvious during the course of this guide. * If the price of the Pool drops below `tickUpper` while we already decided to withdraw our liquidity our order may fail and we either receive `token0`, `token0` and `token1` or our transaction fails depending on our exact implementation. * Range Orders can only be created between initializable ticks and may not exactly represent our limit order Price-Target. * Depending on the price ratio of the tokens in the Pool the minimum price difference to the current price may be significant. * The tokens received are the average between the Price of `tickUpper` and `tickLower` of the Range order. This can be a significant difference for Pools with a tickCurrent far from 0, for example tokens with different decimals (WETH/ USDT, WETH/USDC). The example showcases this behaviour well with the default configuration. ## Next Steps This guide showcases everything you need to implement Range Orders on your own, but only demonstrates creating a Take Profit order in `token0` to `token1` direction. Consider implementing Buy Limit orders as described in the [Range Orders concept page](../../../../concepts/protocol/range-orders.md#buy-limit-orders). This is currently the last guide in the `v3-sdk` series. Consider joining the [Ramses Discord](https://discord.gg/ramses) or checkout the official [GitHub](https://github.com/RamsesExchange) to learn more about Ramses. # Liquidity Positions Source: https://tech.ramses.xyz/sdk/guides/liquidity/01-position-data ## Introduction This guide will introduce us to **liquidity positions** in Ramses V3 and present the `v3-sdk` classes and Contracts used to interact with the protocol. Ramses provides a forked SDK (`@kingdomdotone/v3-sdk`) tailored for Ramses V3 pools. In this guide, we will take a look at the [Position](../../reference/classes/Position) and [RamsesV3PositionManager](../../reference/classes/RamsesV3PositionManager) classes, as well as the [RamsesV3PositionManager Contract](../../../../contracts/reference/periphery/RamsesV3PositionManager). At the end of the guide, we should be familiar with the most important classes used to interact with liquidity positions. We should also understand how to fetch positions from the **RamsesV3PositionManager Contract**. For this guide, the following packages are used: * [`@kingdomdotone/v3-sdk`](https://www.npmjs.com/package/@kingdomdotone/v3-sdk) * [`@uniswap/sdk-core`](https://www.npmjs.com/package/@uniswap/sdk-core) * [`@uniswap/v3-periphery`](https://www.npmjs.com/package/@uniswap/v3-periphery) The code patterns mentioned in this guide apply to minting positions, collecting fees, modifying positions, and swap-and-add liquidity operations. ## Prerequisites To understand what Positions are, we need to understand some underlying concepts of Ramses. Consider checking out the [Concepts section](../../../../concepts/protocol/concentrated-liquidity) which covers concentrated liquidity and period-based accounting in Ramses V3. ### Concentrated liquidity Ramses V3 Pools use concentrated liquidity to allow a denser concentration of liquidity at specific prices. Compared to full range liquidity models, this allows traders to make larger trades with less price impact. Liquidity providers can choose a specific price range in which they want their liquidity to be used by trades. Ramses V3 pools also use **period-based accounting** to track time-weighted active liquidity for fair gauge reward distribution. To achieve this, Ramses V3 Pools discriminate the price range with **Ticks**. ### Ticks Ticks are the boundaries between discrete price ranges. A change of 1 Tick always represents a price change of 0.01% from the current price. Ramses V3 Pools can have different `tickSpacings`, a constant that describes which ticks can be used by the Pool. Only ticks at indices that are divisible by the tickSpacing can be initialized. Tick spacing determines pool characteristics and typical volatility profile. For example, a Pool with **HIGH** fee (1%) has a tickSpacing of 200, meaning the price difference between initializable Ticks is: $1.0001^{200} = 1.0202$ or $2.02$% ### Liquidity Positions When someone provides liquidity to a Pool, they create a **Liquidity Position**. This position is defined by the amount of liquidity provided and the start tick and the end tick, or price range, of the Position. Because V3 Pools allow users to choose any price range in which they want to provide liquidity, it is possible to create positions that do not contain the current Price of the Pool. In this case, the liquidity provider will pay only one type of Token into the Pool, creating a **single side liquidity position**. To learn more about how Ticks and Liquidity positions work, see the [concentrated liquidity guide](../../../../concepts/protocol/concentrated-liquidity) or the [Uniswap V3 whitepaper](https://uniswap.org/whitepaper-v3.pdf) for the core math. Now that we have a rough understanding of liquidity positions in Ramses V3, let's look at the corresponding classes the SDK offers us. ## Position class The **sdk** provides a `Position` class used to create local representations of an onchain position. It is used to create the calldata for onchain calls to mint or modify an onchain position. There are four ways to construct a position. Directly with the constructor: ```typescript theme={null} import { Pool, Position } from '@kingdomdotone/v3-sdk' import JSBI from 'jsbi' const pool = new Pool(...) const tickLower: number = -100 const tickUpper: number = 200 const liquidity: JSBI = JSBI.BigInt('1000000000000000000') const position = new Position({ pool, liquidity, tickLower, tickUpper }) ``` Using the `fromAmounts()` function: ```typescript theme={null} import { BigIntish } from '@uniswap/sdk-core' const pool = new Pool(...) const tickLower: number = -100 const tickUpper: number = 200 const amount0: BigIntish = '1000000000000000000' const amount1: BigIntish = JSBI.BigInt('1000000000000000000') const useFullPrecision: boolean = true const position = Position.fromAmounts({ pool, tickLower, tickUpper, amount0, amount1, useFullPrecision }) ``` Or using the `fromAmount0()` or `fromAmount1()` functions: ```typescript theme={null} import { BigIntish } from '@uniswap/sdk-core' ... const pool = new Pool(...) const tickLower: number = -200 const tickUpper: number = 100 const amount0: BigIntish = '1000000000000000000' const useFullPrecision: boolean = true const singleSidePositionToken0 = Position.fromAmount0({ pool, tickLower, tickUpper, amount0, useFullPrecision }) const amount1: BigIntish = 100000000 const singleSidePositionToken1 = Position.fromAmount1({ pool, tickLower, tickUpper, amount1, useFullPrecision }) ``` These last two functions calculate a position at the given tick range given the amount of `token0` or `token1`. The amount of the second token is calculated from the ratio of the tokens inside the tick range and the amount of token one. A create transaction would then fail if the wallet doesn't hold enough `token1` or the Contract is not given the necessary **Transfer Approval**. All of these functions take an Object with **named values** as a call parameter. The amount and liquidity values are of type `BigIntish` which accepts `number`, `string` and `JSBI`. The values of `tickLower` and `tickUpper` must match **initializable ticks** of the Pool. ## RamsesV3PositionManager The `RamsesV3PositionManager` class is mainly used to create calldata for functions on the **RamsesV3PositionManager Contract**. We will look at the **sdk** class and write functions on the Contract in this section. ### Creating a Position To create a position on a Pool, the [`mint`](../../../../contracts/reference/periphery/RamsesV3PositionManager.md#mint) function is called on the Contract. The **sdk** class provides the `addCallParameters` function to create the calldata for the transaction: ```typescript theme={null} import { MintOptions, RamsesV3PositionManager } from '@kingdomdotone/v3-sdk' const mintOptions: MintOptions = { recipient: address, deadline: Math.floor(Date.now() / 1000) + 60 * 20, slippageTolerance: new Percent(50, 10_000), } // get calldata for minting a position const { calldata, value } = RamsesV3PositionManager.addCallParameters( positionToMint, mintOptions ) ``` This call creates a position if it doesn't exist, but can also be used to increase an existing position. Take a look at the [Mint Position guide](./02-minting-position) and [Modify Position guide](./04-modifying-position) to learn more. ### Decreasing and Increasing a Position To decrease or increase the liquidity of a Position, the `decreaseLiquidity` or `increaseLiquidity` functions are called on the Contract. To increase, `addCallParameters` is used as mentioned above, to decrease we use `removeCallParameters`: ```typescript theme={null} const { calldata, value } = RamsesV3PositionManager.removeCallParameters( currentPosition, removeLiquidityOptions ) ``` Take a look at the [Modify Positions guide](04-modifying-position) to learn how to create the `currentPosition` and `removeLiquidityOptions` parameters. ### Collecting Fees To collect fees accrued, the `collect` function is called on the Contract. The **sdk class** provides the `collectCallParameters` function to create the calldata for that: ```typescript theme={null} const { calldata, value } = RamsesV3PositionManager.collectCallParameters(collectOptions) ``` ## Next steps Now that you are familiar with the most important classes and Contract to interact with Liquidity Positions, continue with the next guide on [Minting Positions](./02-minting-position). # Minting a Position Source: https://tech.ramses.xyz/sdk/guides/liquidity/02-minting-position ## Introduction This guide will cover how to create (or mint) a liquidity position on the Ramses V3 protocol. It is based on the [minting a position code example](https://github.com/Uniswap/examples/tree/main/v3-sdk/minting-position), found in the Uniswap code examples [repository](https://github.com/Uniswap/examples). To run this example, check out the examples's [README](https://github.com/Uniswap/examples/blob/main/v3-sdk/minting-position/README) and follow the setup instructions. If you need a briefer on the SDK and to learn more about how these guides connect to the examples repository, please visit our [background](../01-background) page! In the Ramses V3 protocol, liquidity positions are represented using non-fungible tokens. In this guide we will use the `NonfungiblePositionManager` class to help us mint a liquidity position for the **USDC - DAI** pair. The inputs to our guide are the **two tokens** that we are pooling for, the **amount** of each token we are pooling for and the Pool **fee**. The guide will **cover**: 1. Giving approval to transfer our tokens 2. Creating an instance of a `Pool` 3. Calculating our `Position` from our input tokens 4. Configuring and executing our minting transaction At the end of the guide, given the inputs above, we should be able to mint a liquidity position with the press of a button and view the position on the UI of the web application. For this guide, the following packages are used: * [`@kingdomdotone/v3-sdk`](https://www.npmjs.com/package/@kingdomdotone/v3-sdk) * [`@uniswap/sdk-core`](https://www.npmjs.com/package/@uniswap/sdk-core) * [`@uniswap/smart-order-router`](https://www.npmjs.com/package/@uniswap/smart-order-router) The core code of this guide can be found in [`mintPosition()`](https://github.com/Uniswap/examples/blob/main/v3-sdk/minting-position/src/libs/positions.ts#L37) ## Giving approval to transfer our tokens We want to use the `RamsesV3PositionManager` contract to create our liqudity position. In situations where a smart contract is transfering tokens on our behalf, we need to give it approval to do so. This is done by interacting with the Contract of the contract, considering ERC20 Tokens are smart contracts of their own. Considering this, the first step to create our position is to give approval to the protocol's `RamsesV3PositionManager` to transfer our tokens: ```typescript theme={null} const token0Approval = await getTokenTransferApproval( token0Address, amount0 ) const token1Approval = await getTokenTransferApproval( token1Address, amount1 ) ``` The logic to achieve that is wrapped in the `getTokenTransferApprovals` function. In short, since both **USDC** and **DAI** are ERC20 tokens, we setup a reference to their smart contracts and call the `approve` function: ```typescript theme={null} import { ethers, BigNumber } from 'ethers' async function getTokenTransferApproval(address: string, amount: BigNumber) { const provider = new ethers.providers.JsonRpcProvider(rpcUrl) const tokenContract = new ethers.Contract( address, ERC20_ABI, provider ) return tokenContract.approve( NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS, amount ) } ``` We can get the Contract address for the NonfungiblePositionManager from the [Ramses contract addresses](https://docs.ramses.xyz/security/contract-addresses). For Ethereum mainnet or a local fork of mainnet, we see that the contract address is `0xC36442b4a4522E871399CD717aBDD847Ab11FE88`. In our example, this is defined in the [`constants.ts`](https://github.com/Uniswap/examples/blob/main/v3-sdk/minting-position/src/libs/constants.ts) file. ## Creating an instance of a `Pool` Having approved the transfer of our tokens, we now need to get data about the pool for which we will provide liquidity, in order to instantiate a Pool class. To start, we compute our Pool's address by using a helper function and passing in the unique identifiers of a Pool - the **two tokens** and the Pool **fee**. The **fee** input parameter represents the swap fee that is distributed to all in range liquidity at the time of the swap. ```typescript theme={null} import { computePoolAddress, FeeAmount } from '@kingdomdotone/v3-sdk' import { Token } from '@uniswap/sdk-core' const token0: Token = ... const token1: Token = ... const fee: FeeAmount = ... const POOL_FACTORY_CONTRACT_ADDRESS: string = ... const currentPoolAddress = computePoolAddress({ factoryAddress: POOL_FACTORY_CONTRACT_ADDRESS, tokenA: token0, tokenB: token1, fee: poolFee, }) ``` Again, we can get the factory contract address from the [Ramses contract addresses](https://docs.ramses.xyz/security/contract-addresses). For Ethereum mainnet, or a local fork of mainnet, it is `0x1F98431c8aD98523631AE4a59f267346ea31F984`. In our example, it is defined in [`constants.ts`](https://github.com/Uniswap/examples/blob/main/v3-sdk/minting-position/src/libs/constants.ts) Then, we get the Pool's data by creating a reference to the Pool's smart contract and accessing its methods, very similar to what we did in the [Quoting guide](../swaps/01-quoting.md#referencing-the-pool-contract-and-fetching-metadata): ```typescript theme={null} import IUniswapV3PoolABI from '@uniswap/v3-core/artifacts/contracts/interfaces/IUniswapV3Pool.sol/IUniswapV3Pool.json' const poolContract = new ethers.Contract( currentPoolAddress, IUniswapV3PoolABI.abi, provider ) const [liquidity, slot0] = await Promise.all([ poolContract.liquidity(), poolContract.slot0(), ]) ``` Having collected the required data, we can now create an instance of the `Pool` class: ```typescript theme={null} import { Pool } from '@kingdomdotone/v3-sdk' const configuredPool = new Pool( token0, token1, poolFee, slot0.sqrtPriceX96.toString(), liquidity.toString(), slot0.tick ) ``` We need a Pool instance to create our Position as various parameters of liquidity positions depend on the state of the Pool where they are created. An example is the current price (named *sqrtPriceX96* after the way it is encoded) to know the ratio of the two Tokens we need to send to the Pool. Liquidity provided below the current Price will be provided in the first Token of the Pool, while liquidity provided above the current Price is made up by the second Token. ## Calculating our `Position` from our input tokens Having created the instance of the `Pool` class, we can now use that to create an instance of a `Position` class, which represents the price range for a specific pool that LPs choose to provide in: ```typescript theme={null} import { Position } from '@kingdomdotone/v3-sdk' import { BigIntish } from '@uniswap/sdk-core' // The maximum token amounts we want to provide. BigIntish accepts number, string or JSBI const amount0: BigIntish = ... const amount1: BigIntish = ... const position = Position.fromAmounts({ pool: configuredPool, tickLower: nearestUsableTick(configuredPool.tickCurrent, configuredPool.tickSpacing) - configuredPool.tickSpacing * 2, tickUpper: nearestUsableTick(configuredPool.tickCurrent, configuredPool.tickSpacing) + configuredPool.tickSpacing * 2, amount0: amount0, amount1: amount1, useFullPrecision: true, }) ``` We use the `fromAmounts` static function of the `Position` class to create an instance of it, which uses the following parameters: * The **tickLower** and **tickUpper** parameters specify the price range at which to provide liquidity. This example calls **nearestUsableTick** to get the current useable tick and adjust the lower parameter to be below it by two **tickSpacing** and the upper to be above it by two tickSpacing. This guarantees that the provided liquidity is "in range", meaning it will be earning fees upon minting this position * **amount0** and **amount1** define the maximum amount of currency the liquidity position can use. In this example, we supply these from our configuration parameters. Given those parameters, `fromAmounts` will attempt to calculate the maximum amount of liquidity we can supply. ## Configuring and executing our minting transaction The Position instance is then passed as input to the `RamsesV3PositionManager`'s `addCallParameters` function. The function also requires an [`AddLiquidityOptions`](https://github.com/Uniswap/v3-sdk/blob/08a7c050cba00377843497030f502c05982b1c43/src/nonfungiblePositionManager.ts#L77) object as its second parameter. This is either of type [`MintOptions`](https://github.com/Uniswap/v3-sdk/blob/08a7c050cba00377843497030f502c05982b1c43/src/nonfungiblePositionManager.ts#L74) for minting a new position or [`IncreaseOptions`](https://github.com/Uniswap/v3-sdk/blob/08a7c050cba00377843497030f502c05982b1c43/src/nonfungiblePositionManager.ts#L75) for adding liquidity to an existing position. For this example, we're using a `MintOptions` to create our position. ```typescript theme={null} import { MintOptions, RamsesV3PositionManager } from '@kingdomdotone/v3-sdk' import { Percent } from '@uniswap/sdk-core' const mintOptions: MintOptions = { recipient: address, deadline: Math.floor(Date.now() / 1000) + 60 * 20, slippageTolerance: new Percent(50, 10_000), } // get calldata for minting a position const { calldata, value } = RamsesV3PositionManager.addCallParameters( position, mintOptions ) ``` The `MintOptions` interface requires three keys: * `recipient` defines the address of the Position owner, so in our case the address of our wallet. * `deadline` defines the latest point in time at which we want our transaction to be included in the blockchain. * `slippageTolerance` defines the maximum amount of **change of the ratio** of the Tokens we provide. The ratio can change if for example **trades** that change the price of the Pool are included before our transaction. The `addCallParameters` function returns the calldata as well as the value required to execute the transaction: ```typescript theme={null} const transaction = { data: calldata, to: NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS, value: value, from: address, maxFeePerGas: MAX_FEE_PER_GAS, maxPriorityFeePerGas: MAX_PRIORITY_FEE_PER_GAS, } ``` We use our wallet to send the transaction. As it is a write call, we need to sign the transaction with a valid private key. ```typescript theme={null} const wallet = new ethers.Wallet(privateKey, provider) const txRes = await wallet.sendTransaction(transaction) ``` Write calls do not return the result of the transaction. If we want to read the result we would need to use for example `trace_transaction`. You can find an example of that in the [Range Order guide](../advanced/05-range-orders). In this example, we don't need the result of the transaction. The effect of the transaction is to mint a new Position NFT. We should see a new position with liquidity in our list of positions. ## Next Steps Once you have minted a position, our next guide [Adding and Removing Liquidity](./04-modifying-position) will demonstrate how you can add and remove liquidity from that minted position! # Fetching Positions Source: https://tech.ramses.xyz/sdk/guides/liquidity/03-fetching-positions ## Introduction This guide will cover how to create (or mint) a liquidity position on the Ramses V3 protocol. Like the [Liquidity Position guide](./01-position-data) it doesn't have an accompanying example, nevertheless the concepts and functions used here can be found among the various examples that interact with liquidity positions. If you need an introduction to liquidity positions, check out the [Liquidity Position guide](./01-position-data) The [RamsesV3PositionManager Contract](../../../../contracts/reference/periphery/RamsesV3PositionManager) can be used to create Positions, as well as get information on **existing Positions**. In this guide, we will fetch **all Positions** an address has and fetch the **detailed Position Data** for those positions. The guide will **cover**: 1. Creating an ethersJS contract to interact with the RamsesV3PositionManager. 2. Fetching all positions for an address. 3. Fetching the position info for the positions. At the end of the guide, given the inputs above, we should be able to mint a liquidity position with the press of a button and view the position on the UI of the web application. For this guide, we do not need to use the SDK packages directly. We will only import the contract ABI for the NonfungiblePositionManager Contract from [`@uniswap/v3-periphery`](https://www.npmjs.com/package/@uniswap/v3-periphery) (Ramses V3 uses compatible interfaces). ## Connecting to the NFTPositionManager Contract We use **ethersJS** to interact with the RamsesV3PositionManager Contract. Let's create an ethers Contract: ```typescript theme={null} import { ethers } from 'ethers' import INONFUNGIBLE_POSITION_MANAGER from '@uniswap/v3-periphery/artifacts/contracts/RamsesV3PositionManager.sol/RamsesV3PositionManager.json' const provider = new ethers.providers.JsonRpcProvider(rpcUrl) const nfpmContract = new ethers.Contract( NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS, INONFUNGIBLE_POSITION_MANAGER.abi, provider ) ``` We get the Contract ABI from the `v3-periphery` package and the contract address from the [Ramses contract addresses](https://docs.ramses.xyz/security/contract-addresses) ## Fetching the Position Ids We want to fetch all Position Ids for our address. We first fetch the number of positions and then the ids by their indices. We fetch the number of positions using the `balanceOf` read call: ```typescript theme={null} const numPositions = await nfpmContract.balanceOf(address) ``` Next we iterate over the number of positions and fetch the ids: ```typescript theme={null} const calls = [] for (let i = 0; i < numPositions; i++) { calls.push( nfpmContract.tokenOfOwnerByIndex(address, i) ) } const positionIds = await Promise.all(calls) ``` ## Fetching the Position Info Now that we have the ids of the Positions associated with our address, we can fetch the position info using the `positions` function. The solidity function returns a lot of values describing the Position: ```solidity theme={null} function positions( uint256 tokenId ) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ) ``` In this example we only care about values needed to interact with positions, so we create an Interface `PositionInfo`: ```typescript theme={null} interface PositionInfo { tickLower: number tickUpper: number liquidity: JSBI feeGrowthInside0LastX128: JSBI feeGrowthInside1LastX128: JSBI tokensOwed0: JSBI tokensOwed1: JSBI } ``` We fetch the Position data with `positions`: ```typescript theme={null} const positionCalls = [] for (let id of positionIds) { positionCalls.push( nfpmContract.positions(id) ) } const callResponses = await Promise.all(positionCalls) ``` Finally, we map the RPC response to our interface: ```typescript theme={null} const positionInfos = callResponses.map((position) => { return { tickLower: position.tickLower, tickUpper: position.tickUpper, liquidity: JSBI.BigInt(position.liquidity), feeGrowthInside0LastX128: JSBI.BigInt(position.feeGrowthInside0LastX128), feeGrowthInside1LastX128: JSBI.BigInt(position.feeGrowthInside1LastX128), tokensOwed0: JSBI.BigInt(position.tokensOwed0), tokensOwed1: JSBI.BigInt(position.tokensOwed1), } }) ``` We now have an array containing PositionInfo for all positions that our address holds. # Adding & Removing Liquidity Source: https://tech.ramses.xyz/sdk/guides/liquidity/04-modifying-position ## Introduction This guide will cover how to modify a liquidity position by adding or removing liquidity on the Ramses V3 protocol. It is based on the [modifying a position code example](https://github.com/Uniswap/examples/tree/main/v3-sdk/modifying-position), found in the Uniswap code examples [repository](https://github.com/Uniswap/examples). To run this example, check out the examples's [README](https://github.com/Uniswap/examples/blob/main/v3-sdk/modifying-position/README) and follow the setup instructions. If you need a briefer on the SDK and to learn more about how these guides connect to the examples repository, please visit our [background](../01-background) page! In the Ramses V3 protocol, liquidity positions are represented using non-fungible tokens. In this guide we will use the `NonfungiblePositionManager` class to help us mint a liquidity position and then modify the provided liquidity for the **USDC - DAI** pair. The inputs to our guide are the **two tokens** that we are pooling for, the **amount** of each token we are pooling for, the Pool **fee** and the **fraction** by which to **add and remove** from our position. The guide will **cover**: 1. Adding liquidity to our position 2. Removing liquidity from our position At the end of the guide, given the inputs above, we should be able to add or remove liquidity from a minted position with the press of a button and see the change reflected in our position and the balance of our tokens. For this guide, the following packages are used: * [`@kingdomdotone/v3-sdk`](https://www.npmjs.com/package/@kingdomdotone/v3-sdk) * [`@uniswap/sdk-core`](https://www.npmjs.com/package/@uniswap/sdk-core) The core code of this guide can be found in [`addLiquidity()`](https://github.com/Uniswap/examples/blob/d34a53412dbf905802da2249391788a225719bb8/v3-sdk/modifying-position/src/example/Example.tsx#L33) and [`removeLiquidity()`](https://github.com/Uniswap/examples/blob/733d586070afe2c8cceb35d557a77eac7a19a656/v3-sdk/modifying-position/src/example/Example.tsx#L83) This guide assumes you are familiar with our [Minting a Position](./02-minting-position) guide. A minted position is required to add or remove liquidity from, so the buttons will be disabled until a position is minted. Also note that we do not need to give approval to the `RamsesV3PositionManager` to transfer our tokens as we will have already done that when minting our position. ## Configuration and utils The example can be configured in the [`config.ts`](https://github.com/Uniswap/examples/blob/d34a53412dbf905802da2249391788a225719bb8/v3-sdk/modifying-position/src/config.ts) file. The `CurrentConfig` object has this structure: ```typescript theme={null} export const CurrentConfig: ExampleConfig = { env: Environment.LOCAL, rpc: { local: 'http://localhost:8545', mainnet: 'https://mainnet.infura.io/v3/0ac57a06f2994538829c14745750d721', }, wallet: { address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', privateKey: '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80', }, tokens: { token0: USDC_TOKEN, token0Amount: 1000, token1: DAI_TOKEN, token1Amount: 1000, poolFee: FeeAmount.LOW, fractionToRemove: 1, fractionToAdd: 0.5, }, } ``` You should already be familiar with the `rpc`, `wallet` and token parameters, they are used in the same way as in the guides earlier in our v3-sdk series. The `fractionToAdd` variable is the multiplicator by which we will increase the Position. A fraction of **0.5** means we increase the liquidity by **50%**. The `fractionToRemove` variable is the fraction of the Position that we want to remove later in the guide. A fraction of **1** means we remove **100%** of the liquidity. ## Adding liquidity to our position Assuming we have already minted a position, our first step is to construct the modified position using our original position to calculate the amount by which we want to increase our current position: ```typescript theme={null} const fractionToAdd: number = ... const amount0Increased: JSBI = fromReadableAmount( readableAmount0 * fractionToAdd, token0.decimals ) const amount1Increase: JSBI = fromReadableAmount( readableAmount1 * fractionToAdd, token1.decimals ) const positionToIncreaseBy = constructPosition( amount0Increased, amount1Increase ) ) ``` The `fromReadableAmount()` function calculates the amount of tokens in their smallest unit, so for example 1 ETH would be `1000000000000000000` Wei as ETH has 18 decimals. A better way to get the amounts might be to fetch them with the positionId directly from the blockchain. We demonstrated how to do that in the [first guide](./01-position-data) of this series. ```typescript theme={null} import { Pool, Position } from '@kingdomdotone/v3-sdk' import JSBI from 'jsbi' function constructPosition( amount0: JSBI, amount1: JSBI ): Position { // create Pool same as in the previous guide const pool = new Pool(...) // create position using the maximum liquidity from input amounts return Position.fromAmounts({ pool, tickLower: nearestUsableTick(pool.tickCurrent, pool.tickSpacing) - pool.tickSpacing * 2, tickUpper: nearestUsableTick(pool.tickCurrent, pool.tickSpacing) + pool.tickSpacing * 2, amount0, amount1, useFullPrecision: true, }) } ``` The function receives two arguments, which are the amounts that are used to construct the Position instance. In this example, both of the arguments follow the same logic: we multiply the parameterized `tokenAmount` by the parameterized `fractionToAdd` since the new liquidity position will be added on top of the already minted liquidity position. We then need to construct an options object of type [`AddLiquidityOptions`](https://github.com/Uniswap/v3-sdk/blob/08a7c050cba00377843497030f502c05982b1c43/src/nonfungiblePositionManager.ts#L77) similar to how we did in the minting case. In this case, we will use [`IncreaseOptions`](https://github.com/Uniswap/v3-sdk/blob/08a7c050cba00377843497030f502c05982b1c43/src/nonfungiblePositionManager.ts#L75): ```typescript theme={null} import { AddLiquidityOptions } from '@kingdomdotone/v3-sdk' const addLiquidityOptions: AddLiquidityOptions = { deadline: Math.floor(Date.now() / 1000) + 60 * 20, slippageTolerance: new Percent(50, 10_000), tokenId, } ``` Compared to minting, we have omitted the `recipient` parameter and instead passed in the `tokenId` of the position we previously minted. As the Position already exists, the recipient doesn't change, instead the RamsesV3PositionManager contract can modify the existing Position by accessing it with its id. The tokenId can be fetched with the tokenOfOwnerByIndex function of the RamsesV3PositionManager Contract as described [here](./01-position-data). The newly created position along with the options object are then passed to the `RamsesV3PositionManager`'s `addCallParameters`: ```typescript theme={null} import { RamsesV3PositionManager } from '@kingdomdotone/v3-sdk' const positionToIncreaseBy = constructPosition(CurrentConfig.tokens.amount0, CurrentConfig.tokens.amount1) const { calldata, value } = RamsesV3PositionManager.addCallParameters( positionToIncreaseBy, addLiquidityOptions ) ``` The return values of `addCallParameters` are the calldata and value of the transaction we need to submit to increase our position's liquidity. We can now build and execute the transaction: ```typescript theme={null} import { ethers } from 'ethers' const transaction = { data: calldata, to: NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS, value: value, from: address, maxFeePerGas: MAX_FEE_PER_GAS, maxPriorityFeePerGas: MAX_PRIORITY_FEE_PER_GAS, } const wallet = new ethers.Wallet(privateKey, provider) const txRes = await wallet.sendTransaction(transaction) ``` We can get the Contract address for the NonfungiblePositionManager from the [Ramses contract addresses](https://docs.ramses.xyz/security/contract-addresses). After pressing the button, note how the balance of USDC and DAI drops and our position's liquidity increases. ## Removing liquidity from our position The `removeLiquidity` function is the mirror action of adding liquidity and will be somewhat similar as a result, requiring a position to already be minted. To start, we create a position identical to the one we minted: ```typescript theme={null} const amount0: JSBI = fromReadableAmount( readableAmount0 * fractionToAdd, token0.decimals ) const amount1: JSBI = fromReadableAmount( readableAmount1 * fractionToAdd, token1.decimals ) const currentPosition = constructPosition( amount0, amount1 ) ``` We then need to construct an options object of type [`RemoveLiquidityOptions`](https://github.com/Uniswap/v3-sdk/blob/08a7c050cba00377843497030f502c05982b1c43/src/nonfungiblePositionManager.ts#L138): ```typescript theme={null} import { RemoveLiquidityOptions } from '@kingdomdotone/v3-sdk' import { Percent } from '@uniswap/sdk-core' const removeLiquidityOptions: RemoveLiquidityOptions = { deadline: Math.floor(Date.now() / 1000) + 60 * 20, slippageTolerance: new Percent(50, 10_000), tokenId: positionId, // percentage of liquidity to remove liquidityPercentage: new Percent(0.5), collectOptions, } ``` Just as with adding liquidity, we have we have omitted the `recipient` parameter and instead passed in the `tokenId` of the position we previously minted. We have also provide two additional parameters: * `liquidityPercentage` determines how much liquidity is removed from our initial position (as a `Percentage`), and transfers the removed liquidity back to our address. We set this percentage from our guide configuration ranging from 0 (0%) to 1 (100%). In this example we would remove 50% of the liquidity. * [`collectOptions`](https://github.com/Uniswap/v3-sdk/blob/08a7c050cba00377843497030f502c05982b1c43/src/nonfungiblePositionManager.ts#L105) gives us the option to collect the fees, if any, that we have accrued for this position. In this example, we won't collect any fees, so we provide zero values. If you'd like to see how to collect fees without modifying your position, check out our [collecting fees](./05-collecting-fees) guide! ```typescript theme={null} import { CurrencyAmount } from '@uniswap/sdk-core' import { CollectOptions } from '@kingdomdotone/v3-sdk' const collectOptions: Omit = { expectedCurrencyOwed0: CurrencyAmount.fromRawAmount( token0, 0 ), expectedCurrencyOwed1: CurrencyAmount.fromRawAmount( token1, 0 ), recipient: address, } ``` The position object along with the options object is passed to the `RamsesV3PositionManager`'s `removeCallParameters`, similar to how we did in the adding liquidity case: ```typescript theme={null} const { calldata, value } = RamsesV3PositionManager.removeCallParameters( currentPosition, removeLiquidityOptions ) ``` The return values `removeCallParameters` are the calldata and value that are needed to construct the transaction to remove liquidity from our position. We can build the transaction and send it for execution: ```typescript theme={null} const transaction = { data: calldata, to: NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS, value: value, from: address, maxFeePerGas: MAX_FEE_PER_GAS, maxPriorityFeePerGas: MAX_PRIORITY_FEE_PER_GAS, } const txRes = await wallet.sendTransaction(transaction) ``` After pressing the button, note how the balance of USDC and DAI increases and our position's liquidity drops. ## Next Steps Now that you can mint and modify a position, check out how to [collect fees](./04-collecting-fees) from the position! # Collecting Fees Source: https://tech.ramses.xyz/sdk/guides/liquidity/05-collecting-fees ## Introduction This guide will cover how to collect fees from a liquidity position on the Ramses V3 protocol. It is based on the [collecting fees code example](https://github.com/Uniswap/examples/tree/main/v3-sdk/collecting-fees), found in the Uniswap code examples [repository](https://github.com/Uniswap/examples). To run this example, check out the examples's [README](https://github.com/Uniswap/examples/blob/main/v3-sdk/collecting-fees/README) and follow the setup instructions. If you need a briefer on the SDK and to learn more about how these guides connect to the examples repository, please visit our [background](../01-background) page! In the Ramses V3 protocol, liquidity positions are represented using non-fungible tokens. In this guide we will use the `NonfungiblePositionManager` class to help us mint a liquidity position for the **USDC - DAI** pair. We will then attempt to collect any fees that the position has accrued from those trading against our provisioned liquidity. The inputs to our guide are the **two tokens** that we are pooling for, the **amount** of each token we are pooling for, the Pool **fee** and the **max amount of accrued fees** we want to collect for each token. The guide will **cover**: 1. Setting up our fee collection 2. Submitting our fee collection transaction At the end of the guide, given the inputs above, we should be able to collect the accrued fees (if any) of a minted position with the press of a button and see the change reflected in our position and the balance of our tokens. For this guide, the following packages are used: * [`@kingdomdotone/v3-sdk`](https://www.npmjs.com/package/@kingdomdotone/v3-sdk) * [`@uniswap/sdk-core`](https://www.npmjs.com/package/@uniswap/sdk-core) The core code of this guide can be found in [`collectFees()`](https://github.com/Uniswap/examples/blob/main/v3-sdk/collecting-fees/src/libs/liquidity.ts#L35). This guide assumes you are familiar with our [Minting a Position](./01-minting-position) guide. A minted position is required to add or remove liquidity from, so the buttons will be disabled until a position is minted. Also note that we do not need to give approval to the `RamsesV3PositionManager` to transfer our tokens as we will have already done that when minting our position. ## Setting up our fee collection All of the fee collecting logic can be found in the [`collectFees`](https://github.com/Uniswap/examples/blob/be67e7df220b0a270c9d18bbaab529e017213adf/v3-sdk/collecting-fees/src/example/Example.tsx#L24) function. Notice how the **Collect Fees** button is disabled until a position is minted. This happens because there will be no fees to collect unless there is a position whose liquidity has been traded against. To start, we fetch the position from the RamsesV3PositionManager Contract to get the fees we are owed: ```typescript theme={null} import { ethers } from 'ethers' import JSBI from 'jsbi' ... const nfpmContract = new ethers.Contract(NONFUNGIBLE_POSITION_MANAGER_ADDRESS, provider) const position = nfpmContract.positions(positionId) ``` Next, we construct an options object of type [`CollectOptions`](https://github.com/Uniswap/v3-sdk/blob/08a7c050cba00377843497030f502c05982b1c43/src/nonfungiblePositionManager.ts#L105) that holds the data about the fees we want to collect: ```typescript theme={null} import { CurrencyAmount } from '@uniswap/sdk-core' const collectOptions: CollectOptions = { tokenId: positionId, expectedCurrencyOwed0: CurrencyAmount.fromRawAmount( CurrentConfig.tokens.token0, JSBI.BigInt(position.tokensOwed0) ), expectedCurrencyOwed1: CurrencyAmount.fromRawAmount( CurrentConfig.tokens.token1, JSBI.BigInt(position.tokensOwed1) ), recipient: address, } ``` Read more about fetching position info [here](./01-position-data). Similar to the other functions exposed by the `RamsesV3PositionManager`, we pass the `tokenId` and the `recipient` of the fees, which in this case is our function's input position id and our wallet's address. The other two `CurrencyAmount` parameters (`expectedCurrencyOwed0` and `expectedCurrencyOwed1`) define the **maximum** amount of currency we expect to get collect through accrued fees of each token in the pool. We set these through our guide's configuration. In a real world scenario, we can fetch the amount of fees that are owed to the Position through the `positions()` function of the RamsesV3PositionManager Contract. We fetch the position info like in this code snippet taken from the [Fetching Positions guide](./03-fetching-positions): ```typescript theme={null} const positionInfos = callResponses.map((position) => { return { tickLower: position.tickLower, tickUpper: position.tickUpper, liquidity: JSBI.BigInt(position.liquidity), feeGrowthInside0LastX128: JSBI.BigInt(position.feeGrowthInside0LastX128), feeGrowthInside1LastX128: JSBI.BigInt(position.feeGrowthInside1LastX128), tokensOwed0: JSBI.BigInt(position.tokensOwed0), tokensOwed1: JSBI.BigInt(position.tokensOwed1), } }) ``` The `tokensOwed0` and `tokensOwed1` values are the fees owed. In this example, we have the values hardcoded in the [`config.ts`](https://github.com/Uniswap/examples/blob/main/v3-sdk/collecting-fees/src/config.ts) file. ## Submitting our fee collection transaction Next, we get the call parameters for collecting our fees from our `RamsesV3PositionManager` using the constructed `CollectOptions`: ```typescript theme={null} const { calldata, value } = RamsesV3PositionManager.collectCallParameters(collectOptions) ``` The function above returns the calldata and value required to construct the transaction for collecting accrued fees. Now that we have both the calldata and value we needed for the transaction, we can build and execute the it: ```typescript theme={null} const transaction = { data: calldata, to: NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS, value: value, from: address, maxFeePerGas: MAX_FEE_PER_GAS, maxPriorityFeePerGas: MAX_PRIORITY_FEE_PER_GAS, } const txRes = await wallet.sendTransaction(transaction) ``` After pressing the button, if someone has traded against our position, we should be able to note how the balance of USDC and DAI increases as we collect fees. ## Next Steps The previous guides detail all the atomic steps needed to create and manage positions. However, these approaches may not use all of your desired currency. To ensure you are using your full funds while minimizing gas prices, check out our guide on [Swapping and Adding Liquidity](./06-swap-and-add-liquidity) in a single transaction! # Swapping and Adding Liquidity Source: https://tech.ramses.xyz/sdk/guides/liquidity/06-swap-and-add-liquidity ## Introduction This guide will cover how to execute a swap-and-add operation in a single atomic transaction. It is based on the [swap-and-add example](https://github.com/Uniswap/examples/tree/main/v3-sdk/swap-and-add-liquidity), found in the Uniswap code examples [repository](https://github.com/Uniswap/examples). To run this example, check out the examples's [README](https://github.com/Uniswap/examples/tree/main/v3-sdk/swap-and-add-liquidity) and follow the setup instructions. If you need a briefer on the SDK and to learn more about how these guides connect to the examples repository, please visit our [background](../01-background) page! When adding liquidity to a Ramses V3 pool, you must provide two assets in a particular ratio. In many cases, your contract or the user's wallet hold a different ratio of those two assets. In order to deposit 100% of your assets, you must first swap your assets to the optimal ratio and then add liquidity. However, the swap may shift the balance of the pool and thus change the optimal ratio. To avoid that, we can execute this swap-and-add liquidity operation in an atomic fashion, using a router. The inputs to our guide are the **two tokens** that we are pooling for, the **amount** of each token we are pooling for, the **amount** of each token to swap-and-add, and the Pool **fee**. The guide will **cover**: 1. Setup a router instance 2. Configuring our ratio calculation 3. Calculating our currency ratio 4. Constructing and executing our swap-and-add transaction At the end of the guide, given the inputs above, we should be able swap-and-add liquidity using 100% of the input assets with the press of a button and see the change reflected in our position and the balance of our tokens. For this guide, the following packages are used: * [`@kingdomdotone/v3-sdk`](https://www.npmjs.com/package/@kingdomdotone/v3-sdk) * [`@uniswap/sdk-core`](https://www.npmjs.com/package/@uniswap/sdk-core) * [`@uniswap/smart-order-router`](https://www.npmjs.com/package/@uniswap/smart-order-router) The core code of this guide can be found in [`swapAndAddLiquidity()`](https://github.com/Uniswap/examples/blob/main/v3-sdk/swap-and-add-liquidity/src/libs/liquidity.ts#L48). This guide assumes you are familiar with our [Minting a Position](./01-minting-position) guide. A minted position is required to add or remove liquidity from, so the buttons will be disabled until a position is minted. Also note that we do not need to give approval to the `RamsesV3PositionManager` to transfer our tokens as we will have already done that when minting our position. ## Setup a router instance The first step is to approve the `SwapRouter` smart contract to spend our tokens for us in order for us to add liquidity to our position: ```typescript theme={null} const tokenInApproval = await getTokenTransferApproval( token0, V3_SWAP_ROUTER_ADDRESS ) const tokenOutApproval = await getTokenTransferApproval( token1, V3_SWAP_ROUTER_ADDRESS ) ``` We described the `getTokenTransferApproval` function [here](./02-minting-position.md#giving-approval-to-transfer-our-tokens). Then we can setup our router, the [`AlphaRouter`](https://github.com/Uniswap/smart-order-router/blob/97c1bb7cb64b22ebf3509acda8de60c0445cf250/src/routers/alpha-router/alpha-router.ts#L333), which is part of the [smart-order-router package](https://www.npmjs.com/package/@uniswap/smart-order-router). The router requires a `chainId` and a `provider` to be initialized. Note that routing is not supported for local forks, so we will use a mainnet provider even when swapping on a local fork: ```typescript theme={null} import { ethers } from 'ethers' import { AlphaRouter } from '@uniswap/smart-order-router' const provider = new ethers.providers.JsonRpcProvider(rpcUrl) const router = new AlphaRouter({ chainId: 1, provider }) ``` For a more detailed example, check out our [routing guide](../trading/03-routing). ## Configuring our ratio calculation Having created the router, we now need to construct the parameters required to make a call to its `routeToRatio` function, which will ensure the ratio of currency used matches the pool's required ratio to add our total liquidity. This will require the following parameters: The first two parameters are the currency amounts we use as input to the `routeToRatio` algorithm: ```typescript theme={null} import { CurrencyAmount } from '@uniswap/sdk-core' const token0CurrencyAmount = CurrencyAmount.fromRawAmount( token0, fromReadableAmount( token0AmountToAdd, token0.decimals ) ) const token1CurrencyAmount = CurrencyAmount.fromRawAmount( token1, fromReadableAmount( token1AmountToAdd, token1.decimals ) ) ``` Next, we will create a placeholder position with a liquidity of `1` since liquidity is still unknown and will be set inside the call to `routeToRatio`: ```typescript theme={null} import { Pool, Position, nearestUsableTick } from '@kingdomdotone/v3-sdk' const placeholderPosition = new Position{ pool, liquidity: 1, tickLower: nearestUsableTick(pool.tickCurrent, pool.tickSpacing) - pool.tickSpacing * 2, tickUpper: nearestUsableTick(pool.tickCurrent, pool.tickSpacing) + poolInfo.tickSpacing * 2 } ``` We then need to create an instance of `SwapAndAddConfig` which will set additional configuration parameters for the `routeToRatio` algorithm: * `ratioErrorTolerance` determines the margin of error the resulting ratio can have from the optimal ratio. * `maxIterations` determines the maximum times the algorithm will iterate to find a ratio within error tolerance. If max iterations is exceeded, an error is returned. The benefit of running the algorithm more times is that we have more chances to find a route, but more iterations will longer to execute. We've used a default of 6 in our example. ```typescript theme={null} import { Fraction } from '@uniswap/sdk-core' import { SwapAndAddConfig } from '@uniswap/smart-order-router' const swapAndAddConfig: SwapAndAddConfig = { ratioErrorTolerance: new Fraction(1, 100), maxIterations: 6, } ``` Finally, we will create an instance of `SwapAndAddOptions` to configure which position we are adding liquidity to and our defined swapping parameters in two different objects: * **`swapConfig`** configures the `recipient` of leftover dust from swap, `slippageTolerance` and a `deadline` for the swap. * **`addLiquidityOptions`** must contain a `tokenId` to add to an existing position ```typescript theme={null} import { SwapAndAddOptions } from '@uniswap/smart-order-router' const swapAndAddOptions: SwapAndAddOptions = { swapOptions: { type: SwapType.SWAP_ROUTER_02, recipient: address, slippageTolerance: new Percent(50, 10_000), deadline: Math.floor(Date.now() / 1000) + 60 * 20, }, addLiquidityOptions: { tokenId: positionId, }, } ``` ## Calculating our currency ratio Having constructed all the parameters we need to call `routeToRatio`, we can now make the call to the function: ```typescript theme={null} import { SwapToRatioResponse } from '@uniswap/smart-order-router' const routeToRatioResponse: SwapToRatioResponse = await router.routeToRatio( token0CurrencyAmount, token1CurrencyAmount, currentPosition, swapAndAddConfig, swapAndAddOptions ) ``` The return type of the function call is [SwapToRatioResponse](https://github.com/Uniswap/smart-order-router/blob/97c1bb7cb64b22ebf3509acda8de60c0445cf250/src/routers/router.ts#L121). If a route was found successfully, this object will have two fields: the status (success) and the `SwapToRatioRoute` object. We check to make sure that both of those conditions hold true before we construct and submit the transaction: ```typescript theme={null} import { SwapToRatioStatus } from '@uniswap/smart-order-router' if ( !routeToRatioResponse || routeToRatioResponse.status !== SwapToRatioStatus.SUCCESS ) { // Handle Failed Transaction } ``` In case a route was not found, we return from the function a `Failed` state for the transaction. ## Constructing and executing our swap-and-add transaction After making sure that a route was successfully found, we can now construct and send the transaction. The response (`SwapToRatioRoute`) will have the properties we need to construct our transaction object: ```typescript theme={null} import { SwapToRatioRoute } from '@uniswap/smart-order-router' const route: SwapToRatioRoute = routeToRatioResponse.result const transaction = { data: route.methodParameters?.calldata, to: V3_SWAP_ROUTER_ADDRESS, value: route.methodParameters?.value, from: address, } const txRes = await wallet.sendTransaction(transaction) ``` If the transaction was successful, our swap-and-add will be completed! We should see our input token balances decrease and our position balance should be increased accordingly. # Getting a Quote Source: https://tech.ramses.xyz/sdk/guides/swaps/01-quoting ## Introduction This guide will cover how to get the current quotes for any token pair on Ramses. The examples use the `@kingdomdotone/v3-sdk` package, Ramses' fork of the Uniswap V3 SDK. If you need a briefer on the SDK and to learn more about how these guides connect to the examples repository, please visit our [background](../01-background) page! In this example we will use `quoteExactInputSingle` to get a quote for the pair **USDC - WETH**. The inputs are the **token in**, the **token out**, the **amount in** and the **fee**. The **fee** input parameter represents the swap fee that is distributed to all in-range liquidity at the time of the swap. It is one of the identifiers of a Pool, along with **tokenIn** and **tokenOut**. The guide will **cover**: 1. Computing the Pool's deployment address 2. Referencing the Pool contract and fetching metadata 3. Referencing the Quoter contract and getting a quote At the end of the guide, we should be able to fetch a quote for the given input token pair and the input token amount with the press of a button on the web application. For this guide, the following packages are used: * [`@kingdomdotone/v3-sdk`](https://www.npmjs.com/package/@kingdomdotone/v3-sdk) * [`@uniswap/sdk-core`](https://www.npmjs.com/package/@uniswap/sdk-core) The core code of this guide can be found in `quote.ts`. ## Example configuration We will use the example configuration `CurrentConfig` in most code snippets of this guide. It has the format: ```typescript theme={null} import { Token } from '@uniswap/sdk-core' interface ExampleConfig { rpc: { local: string mainnet: string } tokens: { in: Token amountIn: number out: Token poolFee: number } } export const CurrentConfig: ExampleConfig = {...} ``` The default config of the example uses a local fork of mainnet. If you haven't already, check out our [local development guide](../02-local-development). To change the RPC endpoint or the Pool used, edit the `CurrentConfig` object. To connect to mainnet directly, set the `mainnet` field in the config: ```typescript theme={null} export const CurrentConfig: ExampleConfig = { rpc: { local: 'http://localhost:8545', mainnet: 'https://mainnet.infura.io/v3/0ac57a06f2994538829c14745750d721', }, tokens: { in: USDC_TOKEN, amountIn: 1000, out: WETH_TOKEN, poolFee: FeeAmount.MEDIUM, }, } ``` The pool used is defined by a pair of tokens in `constants.ts`. You can also change these two tokens and the fee of the pool in the config, just make sure a Pool actually exists for your configuration on Ramses. ## Computing the Pool's deployment address To interact with the **USDC - WETH** Pool contract, we first need to compute its deployment address. If you haven't worked directly with smart contracts yet, check out this [guide](https://docs.alchemy.com/docs/smart-contract-basics) from Alchemy. The SDK provides a utility method for that: ```typescript theme={null} import { computePoolAddress } from '@kingdomdotone/v3-sdk' const currentPoolAddress = computePoolAddress({ factoryAddress: POOL_FACTORY_CONTRACT_ADDRESS, tokenA: CurrentConfig.tokens.in, tokenB: CurrentConfig.tokens.out, fee: CurrentConfig.tokens.poolFee, }) ``` Since each *Ramses V3 Pool* is uniquely identified by 3 characteristics (token in, token out, fee/tick spacing), we use those in combination with the address of the *PoolFactory* contract to compute the address of the **USDC - ETH** Pool. These parameters can be defined in a `constants.ts` file: ```typescript theme={null} const WETH_TOKEN = new Token( 1, '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', 18, 'WETH', 'Wrapped Ether' ) const USDC_TOKEN = new Token( 1, '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', 6, 'USDC', 'USD//C' ) ``` These constants are used in the `config.ts` file, as mentioned in the Introduction. We can find the Pool Factory Contract address for our chain [here](../../../../contracts/reference/deployments/deployments). ## Referencing the Pool contract and fetching metadata Now that we have the deployment address of the **USDC - ETH** Pool, we can construct an instance of an **ethers** `Contract` to interact with it: ```typescript theme={null} import { ethers } from 'ethers' const provider = new ethers.providers.JsonRpcProvider(rpcUrl) const poolContract = new ethers.Contract( currentPoolAddress, IUniswapV3PoolABI.abi, provider ) ``` To construct the *Contract* we need to provide the address of the contract, its ABI and the provider that will carry out the RPC call for us. We get access to the contract's ABI through the [@uniswap/v3-core](https://www.npmjs.com/package/@uniswap/v3-core) package, which holds the core smart contract interfaces (Ramses V3 uses compatible interfaces): ```typescript theme={null} import IUniswapV3PoolABI from '@uniswap/v3-core/artifacts/contracts/interfaces/IUniswapV3Pool.sol/IUniswapV3Pool.json' ``` Having constructed our reference to the contract, we can now access its methods through our provider. We use a batch `Promise` call. This approach queries state data concurrently, rather than sequentially, to minimize the chance of fetching out of sync data that may be returned if sequential queries are executed over the span of two blocks: ```typescript theme={null} const [token0, token1, fee, liquidity, slot0] = await Promise.all([ poolContract.token0(), poolContract.token1(), poolContract.fee(), poolContract.liquidity(), poolContract.slot0(), ]) ``` The return values of these methods will become inputs to the quote fetching function. The `token0` and `token1` variables are the addresses of the tokens in the Pool and should not be mistaken for `Token` objects from the sdk. For the full code, check out the `getPoolConstants()` function in `quote.ts`. In this example, the metadata we fetch is already present in our inputs. This guide fetches this information first in order to show how to fetch any metadata, which will be expanded on in future guides. ## Referencing the Quoter contract and getting a quote To get quotes for trades, Ramses has deployed a **Quoter Contract**. We will use this contract to fetch the output amount we can expect for our trade, without actually executing the trade. Like we did for the Pool contract, we need to construct an instance of an **ethers** `Contract` for our Quoter contract in order to interact with it: ```typescript theme={null} const quoterContract = new ethers.Contract( QUOTER_CONTRACT_ADDRESS, Quoter.abi, getProvider() ) ``` We get access to the contract's ABI through the [@uniswap/v3-periphery](https://www.npmjs.com/package/@uniswap/v3-periphery) package (Ramses uses compatible interfaces): ```typescript theme={null} import Quoter from '@uniswap/v3-periphery/artifacts/contracts/lens/Quoter.sol/Quoter.json' ``` We get the QUOTER\_CONTRACT\_ADDRESS for our chain from the [Ramses contract addresses](https://docs.ramses.xyz/security/contract-addresses). We can now use our Quoter contract to obtain the quote. In an ideal world, the quoter functions would be `view` functions, which would make them very easy to query on-chain with minimal gas costs. However, the Quoter contracts rely on state-changing calls designed to be reverted to return the desired data. This means calling the quoter will be very expensive and should not be called on-chain. To get around this difficulty, we can use the `callStatic` method provided by the **ethers.js** `Contract` instances. This is a useful method that submits a state-changing transaction to an Ethereum node, but asks the node to simulate the state change, rather than to execute it. Our script can then return the result of the simulated state change: ```typescript theme={null} const quotedAmountOut = await quoterContract.callStatic.quoteExactInputSingle( token0, token1, fee, fromReadableAmount( CurrentConfig.tokens.amountIn, CurrentConfig.tokens.in.decimals ).toString(), 0 ) ``` The `fromReadableAmount()` function creates the amount of the smallest unit of a token from the full unit amount and the decimals. The result of the call is the number of output tokens you'd receive for the quoted swap. It should be noted that `quoteExactInputSingle` is only 1 of 4 different methods that the quoter offers: 1. `quoteExactInputSingle` - given the amount you want to swap, produces a quote for the amount out for a swap of a single pool 2. `quoteExactInput` - given the amount you want to swap, produces a quote for the amount out for a swap over multiple pools 3. `quoteExactOutputSingle` - given the amount you want to get out, produces a quote for the amount in for a swap over a single pool 4. `quoteExactOutput` - given the amount you want to get out, produces a quote for the amount in for a swap over multiple pools If we want to trade two tokens that do not share a pool with each other, we will need to make swaps over multiple pools. This is where the `quoteExactInput` and `quoteExactOutput` methods come in. We will dive deeper into routing in the [routing guide](03-routing). For the `exactOutput` and `exactOutputSingle` methods, we need to keep in mind that a pool can not give us more than the amount of Tokens it holds. If we try to get a quote on an output of 100 WETH from a Pool that only holds 50 WETH, the function call will fail. ## Referencing the QuoterV2 contract and getting a quote ```typescript theme={null} const quoterV2Contract = new ethers.Contract( QUOTER_V2_CONTRACT_ADDRESS, QuoterV2.abi, getProvider() ) ``` We get the QUOTER\_V2\_CONTRACT\_ADDRESS for our chain from the [Ramses contract addresses](https://docs.ramses.xyz/security/contract-addresses). We get access to the contract's ABI through the [@uniswap/v3-periphery](https://www.npmjs.com/package/@uniswap/v3-periphery) package (Ramses uses compatible interfaces): ```typescript theme={null} import Quoter as QuoterV2 from '@uniswap/v3-periphery/artifacts/contracts/lens/QuoterV2.sol/QuoterV2.json' ``` Let's get the quote for our tokens, where "Quoter" takes multiple arguments in quoteExactInputSingle(), QuoterV2 takes only one argument in the form of an object ```typescript theme={null} const quote = await quoterContract.callStatic.quoteExactInputSingle( { tokenIn: tokenIn.address, // tokenIn is of type Token tokenOut: tokenOut.address, // tokenOut is of type Token fee: fee, // eg. 3000 amountIn: fromReadableAmount(amountIn, tokenIn.decimals).toString(), sqrtPriceLimitX96: 0, } ); console.log(quote.amountOut); ``` This will return "amountOut", "gasEstimate", "initializedTicksCrossed" and "sqrtPriceX96After": 1. **AmountOut**: The tokens or cryptocurrency received in the swap transaction. 2. **Gas Estimate**: Estimated amount of gas required for executing the transaction. 3. **InitializedTicksCrossed**: Indicates whether liquidity has crossed certain price thresholds within a liquidity range. 4. **SqrtPriceX96After**: Square root of the price after the transaction, essential for determining pricing accuracy. ## Next Steps Now that you're able to make a quote, check out our next guide on [trading](./02-trading) using this quote! # Executing a Trade Source: https://tech.ramses.xyz/sdk/guides/swaps/02-trading ## Introduction This guide will build off our [quoting guide](./01-quoting) and show how to use a quote to construct and execute a trade on the Ramses V3 protocol. The examples use the `@kingdomdotone/v3-sdk` package, Ramses' fork of the Uniswap V3 SDK. If you need a briefer on the SDK and to learn more about how these guides connect to the examples repository, please visit our [background](../01-background) page! To get started with local development, also check out the [local development guide](../02-local-development). In this example we will trade between two ERC20 tokens: **WETH and USDC**. The tokens, amount of input token, and the fee level can be configured as inputs. The guide will **cover**: 1. Constructing a route from pool information 2. Constructing an unchecked trade 3. Executing a trade At the end of the guide, we should be able to create and execute a trade between any two ERC20 tokens using the example's included UI. Included in the example application is functionality to wrap/unwrap ETH as needed to fund the example `WETH` to `USDC` swap directly from an `ETH` balance. For this guide, the following packages are used: * [`@kingdomdotone/v3-sdk`](https://www.npmjs.com/package/@kingdomdotone/v3-sdk) * [`@uniswap/sdk-core`](https://www.npmjs.com/package/@uniswap/sdk-core) The core code of this guide can be found in `trading.ts`. ## Using a wallet extension Like in the previous guide, our example uses a config file to configure the inputs used. The strucuture is similar to the quoting config, but we also have the option to select an environment: ```typescript theme={null} export interface ExampleConfig { env: Environment rpc: { local: string mainnet: string } wallet: { address: string privateKey: string } tokens: { in: Token amountIn: number out: Token poolFee: number } } ``` Per default, the env field is set to `Environment.LOCAL`: ```typescript theme={null} export const CurrentConfig: ExampleConfig = { env: Environment.LOCAL, rpc: { local: 'http://localhost:8545', mainnet: '', }, wallet: { address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', privateKey: '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80', }, tokens: { in: WETH_TOKEN, amountIn: 1, out: USDC_TOKEN, poolFee: FeeAmount.MEDIUM, }, } ``` In this example, we have the option to use a Wallet Extension like Metamask to sign the transactions we are sending. To do so, let's change the Environment to `Environment.WALLET_EXTENSION`: ```typescript theme={null} export const CurrentConfig: ExampleConfig = { env: Environment.WALLET_EXTENSION, rpc: { local: 'http://localhost:8545', }, wallet: { ... }, tokens: { ... }, } ``` Run the example and then add the local network to your wallet browser extension, if you are using Metamask for example, follow [this guide](https://support.metamask.io/hc/en-us/articles/360043227612-How-to-add-a-custom-network-RPC). You should also import a private key to use on your local network, for example `0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80` from Foundry's example wallets. Consider checking out the README of the example. If you cannot see the Tokens traded in your wallet, you possibly have to [import them](https://support.metamask.io/hc/en-us/articles/360015489031-How-to-display-tokens-in-MetaMask). ## Constructing a route from pool information To construct our trade, we will first create an model instance of a `Pool`. We create an **ethers** contract like in the [previous guide](./01-quoting.md#referencing-the-pool-contract-and-fetching-metadata). We will first extract the needed metadata from the relevant pool contract. Metadata includes both constant information about the pool as well as information about its current state stored in its first slot: ```typescript theme={null} async function getPoolInfo() { const [token0, token1, fee, liquidity, slot0] = await Promise.all([ poolContract.fee(), poolContract.liquidity(), poolContract.slot0(), ]) return { fee, liquidity, sqrtPriceX96: slot0[0], tick: slot0[1], } } ``` Before continuing, let's talk about the values we fetched here and what they represent: * `fee` is the fee that is taken from every swap that is executed on the pool in 1 per million - if the `fee` value of a pool is 500, `500/ 1000000` (or 0.05%) of the trade amount is taken as a fee. This fee goes to the liquidity providers of the Pool. * `liquidity` is the amount of liquidity the Pool can use for trades at the current price. * `sqrtPriceX96` is the current Price of the pool, encoded as a ratio between `token0` and `token1`. * `tick` is the tick at the current price of the pool. Check out the [Uniswap V3 whitepaper](https://uniswap.org/whitepaper-v3.pdf) to learn more about how liquidity and ticks work -- Ramses V3 uses the same core concentrated liquidity math. You can find the full code in `pool.ts`. Using this metadata along with our inputs, we will then construct a `Pool`: ```typescript theme={null} const poolInfo = await getPoolInfo() const pool = new Pool( CurrentConfig.tokens.in, CurrentConfig.tokens.out, CurrentConfig.tokens.poolFee, poolInfo.sqrtPriceX96.toString(), poolInfo.liquidity.toString(), poolInfo.tick ) ``` ## Creating a Route With this `Pool`, we can now construct a route to use in our trade. Routes represent a route over one or more pools from one Token to another. Let's imagine we have three pools: ``` - PoolA: USDC/ WETH - PoolB: USDT/ WETH - PoolC: USDT/ DAI ``` We would like to trade from USDC to DAI, so we create a route through our 3 pools: ``` PoolA -> PoolB -> PoolC ``` The `Route` object can find this route from an array of given pools and an input and output Token. To keep it simple for this guide, we only swap over one Pool: ```typescript theme={null} import { Route } from '@kingdomdotone/v3-sdk' const swapRoute = new Route( [pool], CurrentConfig.tokens.in, CurrentConfig.tokens.out ) ``` Our `Route` understands that `CurrentConfig.tokens.in` should be traded for `CurrentConfig.tokens.out` over the Array of pools `[pool]`. ## Constructing an unchecked trade Once we have constructed the route object, we now need to obtain a quote for the given `inputAmount` of the example: ```typescript theme={null} const amountOut = await getOutputQuote(swapRoute) ``` As shown below, the quote is obtained using the `v3-sdk`'s `SwapQuoter`, in contrast to the [previous quoting guide](./01-quoting), where we directly accessed the smart contact: ```typescript theme={null} import { SwapQuoter } from '@kingdomdotone/v3-sdk' import { CurrencyAmount, TradeType } from '@uniswap/sdk-core' const { calldata } = await SwapQuoter.quoteCallParameters( swapRoute, CurrencyAmount.fromRawAmount( CurrentConfig.tokens.in, fromReadableAmount( CurrentConfig.tokens.amountIn, CurrentConfig.tokens.in.decimals ) ), TradeType.EXACT_INPUT, { useQuoterV2: true, } ) ``` The `SwapQuoter`'s `quoteCallParameters` function, gives us the calldata needed to make the call to the `Quoter`, and we then decode the returned quote: ```typescript theme={null} const quoteCallReturnData = await provider.call({ to: QUOTER_CONTRACT_ADDRESS, data: calldata, }) return ethers.utils.defaultAbiCoder.decode(['uint256'], quoteCallReturnData) ``` With the quote and the route, we can now construct a trade using the route in addition to the output amount from a quote based on our input. Because we already know the expected output of our Trade, we do not have to check it again. We can use the `uncheckedTrade` function to create our Trade: ```typescript theme={null} import { Trade } from 'uniswap/v3-sdk' import { CurrencyAmount, TradeType } from '@uniswap/sdk-core' import JSBI from 'jsbi' const uncheckedTrade = Trade.createUncheckedTrade({ route: swapRoute, inputAmount: CurrencyAmount.fromRawAmount( CurrentConfig.tokens.in, fromReadableAmount( CurrentConfig.tokens.amountIn, CurrentConfig.tokens.in.decimals ) ), outputAmount: CurrencyAmount.fromRawAmount( CurrentConfig.tokens.out, JSBI.BigInt(amountOut) ), tradeType: TradeType.EXACT_INPUT, }) ``` This example uses an exact input trade, but we can also construct a trade using exact output assuming we adapt our quoting code accordingly. ## Executing a trade Once we have created a trade, we can now execute this trade with our provider. First, we must give the `SwapRouter` approval to spend our tokens for us: ```typescript theme={null} const tokenApproval = await getTokenTransferApproval(CurrentConfig.tokens.in) ``` You can find the approval function in `trading.ts`. We will use this function or similar implementations in most guides. Then, we set our options that define how much time and slippage can occur in our execution as well as the address to use for our wallet: ```typescript theme={null} import { SwapOptions } from '@kingdomdotone/v3-sdk' import { Percent } from '@uniswap/sdk-core' const options: SwapOptions = { slippageTolerance: new Percent(50, 10_000), // 50 bips, or 0.50% deadline: Math.floor(Date.now() / 1000) + 60 * 20, // 20 minutes from the current Unix time recipient: walletAddress, } ``` The slippage of our trade is the maximum decrease from our calculated output amount that we are willing to accept for this trade. The deadline is the latest point in time when we want the transaction to go through. If we set this value too high, the transaction could be left waiting for days and we would need to pay gas fees to cancel it. Next, we use the `SwapRouter` class, a representation of the Ramses SwapRouter Contract, to get the associated call parameters for our trade and options: ```typescript theme={null} import { SwapRouter } from '@kingdomdotone/v3-sdk' const methodParameters = SwapRouter.swapCallParameters([uncheckedTrade], options) ``` Finally, we can construct a transaction from the method parameters and send the transaction: ```typescript theme={null} const tx = { data: methodParameters.calldata, to: SWAP_ROUTER_ADDRESS, value: methodParameters.value, from: walletAddress, maxFeePerGas: MAX_FEE_PER_GAS, maxPriorityFeePerGas: MAX_PRIORITY_FEE_PER_GAS, } const res = await wallet.sendTransaction(tx) ``` ## Next Steps The resulting example allows for trading between any two ERC20 tokens, but this can be suboptimal for the best pricing and fees. To achieve the best possible price, we use an auto router to route through pools to get an optimal cost. Our [routing](./03-routing) guide will show you how to use routing and execute optimal swaps. # Routing a Swap Source: https://tech.ramses.xyz/sdk/guides/swaps/03-routing ## Introduction This guide will cover how to use smart order routing to compute optimal routes and execute swaps. Rather than trading between a single pool, smart routing may use multiple hops (as many as needed) to ensure that the end result of the swap is the optimal price. If you need a briefer on the SDK and to learn more about how these guides connect to the examples repository, please visit our [background](../01-background) page! In this example we will trade between **WETH and USDC**, but you can configure your example to use any two currencies and amount of input currency. The guide will **cover**: 1. Creating a router instance 2. Creating a route 3. Swapping using a route At the end of the guide, we should be able to create a route and execute a swap between any two currencies tokens using the example's included UI. For this guide, the following packages are used: * [`@kingdomdotone/v3-sdk`](https://www.npmjs.com/package/@kingdomdotone/v3-sdk) * [`@uniswap/sdk-core`](https://www.npmjs.com/package/@uniswap/sdk-core) * [`@uniswap/smart-order-router`](https://www.npmjs.com/package/@uniswap/smart-order-router) The `@kingdomdotone/v3-sdk` is Ramses' fork of the Uniswap V3 SDK, tailored for Ramses V3 pools. The core code of this guide can be found in `routing.ts`. The config, which we will use in some code snippets in this guides has this structure: ```typescript theme={null} import { Token } from '@uniswap/sdk-core' interface ExampleConfig { env: Environment rpc: { local: string mainnet: string } wallet: { address: string privateKey: string } tokens: { in: Token amountIn: number out: Token } } export const CurrentConfig: ExampleConfig = {...} ``` ## Creating a router instance To compute our route, we will use the `@uniswap/smart-order-router` package, specifically the `AlphaRouter` class which requires a `chainId` and a `provider`. Note that routing is not supported for local forks, so we will use a mainnet provider even when swapping on a local fork: ```typescript theme={null} import { AlphaRouter, ChainId } from '@uniswap/smart-order-router' const provider = new ethers.providers.JsonRpcProvider(rpcUrl) const router = new AlphaRouter({ chainId: ChainId.MAINNET, provider, }) ``` ## Creating a route We will use the SwapRouter contract for our trade. The `smart-order-router` package provides us with a `SwapOptionsSwapRouter02` interface, defining the wallet to use, slippage tolerance, and deadline for the transaction that we need to interact with the contract: ```typescript theme={null} import { SwapOptionsSwapRouter02, SwapType } from '@uniswap/smart-order-router' import { Percent } from '@uniswap/sdk-core' const options: SwapOptionsSwapRouter02 = { recipient: CurrentConfig.wallet.address, slippageTolerance: new Percent(50, 10_000), deadline: Math.floor(Date.now() / 1000 + 1800), type: SwapType.SWAP_ROUTER_02, } ``` Like explained in the [previous guide](./02-trading.md#executing-a-trade), it is important to set the parameters to sensible values. Using these options, we can now create a trade (`TradeType.EXACT_INPUT` or `TradeType.EXACT_OUTPUT`) with the currency and the input amount to use to get a quote. For this example, we'll use an `EXACT_INPUT` trade to get a quote outputted in the quote currency. ```typescript theme={null} import { CurrencyAmount, TradeType } from '@uniswap/sdk-core' const rawTokenAmountIn: JSBI = fromReadableAmount( CurrentConfig.tokens.amountIn, CurrentConfig.tokens.in.decimals ) const route = await router.route( CurrencyAmount.fromRawAmount( CurrentConfig.tokens.in, rawTokenAmountIn ), CurrentConfig.tokens.out, TradeType.EXACT_INPUT, options ) ``` The `fromReadableAmount` function calculates the amount of tokens in the Token's smallest unit from the full unit and the Token's decimals: ```typescript title="src/libs/conversion.ts" theme={null} export function fromReadableAmount(amount: number, decimals: number): JSBI { const extraDigits = Math.pow(10, countDecimals(amount)) const adjustedAmount = amount * extraDigits return JSBI.divide( JSBI.multiply( JSBI.BigInt(adjustedAmount), JSBI.exponentiate(JSBI.BigInt(10), JSBI.BigInt(decimals)) ), JSBI.BigInt(extraDigits) ) } ``` `route` and `route.methodParameters` are *optional* as the request can fail, for example if **no route exists** between the two Tokens or because of networking issues. We check if the call was succesful: ```typescript theme={null} if (!route || !route.methodParameters) { // Handle failed request } ``` Depending on our preferences and reason for the issue we could retry the request or throw an Error. ## Swapping using a route First, we need to give approval to the `SwapRouter` smart contract to spend our tokens for us: ```typescript theme={null} import { ethers } from 'ethers' ... const wallet = new ethers.Wallet(privateKey, provider) const tokenContract = new ethers.Contract( CurrentConfig.tokens.in.address, ERC20ABI, wallet ) const tokenApproval = await tokenContract.approve( V3_SWAP_ROUTER_ADDRESS, ethers.BigNumber.from(rawTokenAmountIn.toString()) ) ``` To be able to spend the tokens of a wallet, a smart contract first needs to get an approval from that wallet. ERC20 tokens have an `approve` function that accepts the address of the smart contract that we want to allow spending our tokens and the amount the smart contract should be allowed to spend. We can get the **V3\_SWAP\_ROUTER\_ADDRESS** for our chain from the [Ramses contract addresses](https://docs.ramses.xyz/security/contract-addresses). Keep in mind that different chains might have **different deployment addresses** for the same contracts. The deployment address for local forks of a network are the same as in the network you forked, so for a **fork of mainnet** it would be the address for **Mainnet**. We need to wait one block for the approval transaction to be included by the blockchain. Once the approval has been granted, we can now execute the trade using the route's computed calldata, values, and gas values: ```typescript theme={null} const txRes = await wallet.sendTransaction({ data: route.methodParameters.calldata, to: V3_SWAP_ROUTER_ADDRESS, value: route.methodParameters.value, from: wallet.address, maxFeePerGas: MAX_FEE_PER_GAS, maxPriorityFeePerGas: MAX_PRIORITY_FEE_PER_GAS, }) ``` After swapping, you should see the currency balances update in the UI shortly after the block is confirmed. You can find the full code in `routing.ts`. ## Next Steps Now that you're familiar with trading, consider checking out our next guides on [pooling liquidity](../liquidity/01-position-data) to Ramses! # Overview Source: https://tech.ramses.xyz/sdk/overview # The Ramses V3 SDK > **Welcome to the V3 Ramses SDK!** The Ramses V3 SDK provides abstractions to assist you with interacting with the Ramses V3 smart contracts in a Typescript/Javascript environment (e.g. websites, node scripts). It makes use of the [**Core SDK**](../core/overview) to gain access to abstractions that are common amongst V3-compatible SDKs. With the SDK, you can manipulate data that has been queried from the [EVM](https://ethereum.org/en/developers/docs/evm/) using libraries that assist with needs such as data modeling, protection from rounding errors, and compile time enforced typing. To begin, we recommend looking at our [**Guides**](./guides/01-background) which include walkthroughs of core usages. These guides will help you better understand how to use the SDK and integrate it into your application. For complete documentation of the SDK's offerings, see the [**Technical Reference**](./reference/overview). ## Installation To interact with the V3 SDK we recommend installing though npm: ```bash theme={null} npm i --save @kingdomdotone/v3-sdk npm i --save @uniswap/sdk-core ``` The `@kingdomdotone/v3-sdk` is Ramses' fork of the Uniswap V3 SDK, tailored for Ramses V3 pools. Use it alongside `@uniswap/sdk-core` for core token abstractions. The actual contract addresses will differ -- refer to the [Ramses contract addresses](https://docs.ramses.xyz/security/contract-addresses) for your target chain. ## Developer Links * [**Ramses GitHub**](https://github.com/RamsesExchange) * [**Ramses V3 Contracts**](https://github.com/RamsesExchange/ramses-v3-contracts) * [**V3 SDK NPM Package**](https://www.npmjs.com/package/@kingdomdotone/v3-sdk) * [**Core SDK NPM Package**](https://www.npmjs.com/package/@uniswap/sdk-core) # Ramses API Source: https://tech.ramses.xyz/users-api-reference/overview REST API reference for the Ramses protocol across all supported chains. # Ramses API REST endpoints follow the same schema across deployed chains. The base URL pattern is: ``` https://gateway.kingdom.dev/{chain_slug}/api ``` Subgraph-compatible GraphQL queries use the converter endpoint: ``` https://gateway.kingdom.dev/{chain_slug}/converter/graphql ``` ## Supported chains | Chain | Slug | REST API base | GraphQL converter | API reference | | --------------- | ----------- | ------------------------------------------- | --------------------------------------------------------- | ------------------------------------------------------------ | | HyperEVM | `hyperevm` | `https://gateway.kingdom.dev/hyperevm/api` | `https://gateway.kingdom.dev/hyperevm/converter/graphql` | [Swagger](https://gateway.kingdom.dev/hyperevm/api/swagger) | | Arbitrum | `arbitrum` | `https://gateway.kingdom.dev/arbitrum/api` | `https://gateway.kingdom.dev/arbitrum/converter/graphql` | [Swagger](https://gateway.kingdom.dev/arbitrum/api/swagger) | | Avalanche | `avalanche` | `https://gateway.kingdom.dev/avalanche/api` | `https://gateway.kingdom.dev/avalanche/converter/graphql` | [Swagger](https://gateway.kingdom.dev/avalanche/api/swagger) | | Polygon | `polygon` | `https://gateway.kingdom.dev/polygon/api` | `https://gateway.kingdom.dev/polygon/converter/graphql` | [Swagger](https://gateway.kingdom.dev/polygon/api/swagger) | | Robinhood Chain | `robinhood` | `https://gateway.kingdom.dev/robinhood/api` | `https://gateway.kingdom.dev/robinhood/converter/graphql` | [Swagger](https://gateway.kingdom.dev/robinhood/api/swagger) | | Linea | `linea` | Not currently deployed | `https://gateway.kingdom.dev/linea/converter/graphql` | — | Swagger UI is available for each deployed REST API at: ``` https://gateway.kingdom.dev/{chain_slug}/api/swagger ``` ## Rate limiting * **30 requests per 30 seconds** per client IP address. ## Local development ```sh theme={null} bun install bun run dev ``` Local Swagger UI is available at `http://localhost:3000/swagger`.