diff --git a/docs/btcli/btcli-permissions.md b/docs/btcli/btcli-permissions.md index a87f748d..5116b10f 100644 --- a/docs/btcli/btcli-permissions.md +++ b/docs/btcli/btcli-permissions.md @@ -438,7 +438,7 @@ The `btcli crowd` commands are used to create and manage crowdloans on the netwo ### `liquidity` -The `btcli liquidity` commands are used to provide and manage trading liquidity for specific subnets. For more information, see [Liquidity positions](../liquidity-positions/liquidity-positions.md). +The `btcli liquidity` commands were used to manage user liquidity positions. User LP positions are currently disabled on-chain. Subnet pools now use protocol-owned liquidity managed by the [Balancer weighted pool AMM](../learn/balancer-amm.md). - **`liquidity add`**: Add liquidity to the swap (as a combination of TAO + Alpha). - **`liquidity list`**: Shows a wallet's liquidity positions in given subnet. diff --git a/docs/governance/governance.md b/docs/governance/governance.md index 13a82b08..1c6ddf65 100644 --- a/docs/governance/governance.md +++ b/docs/governance/governance.md @@ -1,66 +1,155 @@ --- -title: "Governance Overview" +title: "Governance" --- -import { SdkVersion } from "../sdk/_sdk-version.mdx"; +# Governance -# Governance Overview +Operational control of Bittensor is governed by the following decentralized protocol. All root calls, including protocol changes, runtime upgrades, and other privileged operations, reach the chain only after passing through both stages. -Bittensor's governance protocol transitions the management of the network from centralization within the foundation to community ownership over time. +:::note +It is critical to note that the governance design depends on the collectives being populated. At initial deploy and until the reviewing collectives are populated, the review stage is a no-op that offers no additional check on the triumvirate. +::: -The first stage of this transition to decentralized management is the creation of a bicameral legislature. In this stage, the [Triumvirate](../resources/glossary.md#triumvirate) creates proposals for the [Senate](./senate.md) to approve. +## Collectives -Triumvirate members are Opentensor Foundation employees, while the Senate is formed from the top K delegate hotkeys. +Governance is organized around five named on-chain collectives managed by `pallet-multi-collective`: -## Proposals +| Collective | Size | Selection | Role | +|---|---|---|---| +| **Triumvirate** | 3 (fixed) | Curated (root-assigned) | First-stage approval | +| **Proposers** | 1–20 | Curated (root-assigned) | Submit proposals | +| **Building** | 16 (fixed) | Rotating every 60 days | Review-stage voting | +| **Economic** | 16 (fixed) | Rotating every 60 days | Review-stage voting | +| **EconomicEligible** | ≤64 | Auto-synced from root registrations | Candidate pool for Economic | -Proposals are encapsulations of other extrinsics and will be executed only after meeting both of the two conditions: +## Proposal Flow -1. The proposal has obtained (50% + 1) approvals from the Senate, and -2. A member of the Triumvirate has closed the proposal. +### Stage 1: Triumvirate track -The above guarantees that the Senate must reach a majority consensus to execute a proposal. +A member of the **Proposers** collective submits a root call. The proposal enters the Triumvirate track: -:::tip Execution of a proposal -When a proposal is executed, the calldata passed to it during its creation are included in the same block as the close extrinsic. -::: +- The three Triumvirate members have **7 days** to vote. +- **2-of-3 aye votes**: proposal advances to the review track. +- **2-of-3 nay votes** or timeout: proposal is rejected and cleaned up. + +### Stage 2: Review track + +On Triumvirate approval, the proposal enters a delay period. The voter set is the **deduplicated union of the Economic and Building collectives** (at most 32 members). The voter set is snapshotted at the moment the review period opens — collective rotations during the delay do not change who may vote or shift the thresholds. + +The delay starts at **24 hours** and can extend to a **2-day maximum** as nay votes accumulate, following an ease-out adjustment curve. When the adjusted delay drops below the time already elapsed, execution begins. + +During the delay period, voters may: + +- **Fast-track**: 75% or more aye votes → executes at the next block. +- **Cancel**: 51% or more nay votes → proposal cancelled and cleaned up. +- Otherwise the proposal executes when the delay period expires. + +### Execution + +The chain dispatches the call with root privilege through an atomic enact wrapper. If the call fails it is not retried and is cleaned up. A stale scheduler entry on a terminated referendum cannot dispatch its inner call. + +![On-Chain Governance: Proposal Flow](/img/docs/proposal-flow.svg) + + -`Bob` has a novel concept for a subnet and wishes to deploy it on the Bittensor network. `Bob` creates a proposal with the calldata: +## Collective Membership - +### Proposers and Triumvirate -```python -SubtensorModule.SudoAddNetwork(netuid, tempo, modality) -``` +Both are curated: members are added, removed, or swapped by root governance. The Triumvirate is fixed at 3 seats. Previously the Triumvirate held sudo access directly; under the new system it is the first stage of the referendum process with no direct sudo. -and sends the transaction to the network in order to broadcast the proposal. +### Economic collective -**Senate** +The Economic collective, likely to represent highly staked validators, is selected from the **EconomicEligible** pool every 60 days. The top 16 EconomicEligible coldkeys by stake EMA value take the seats. If fewer than 16 eligible coldkeys are available, the rotation fails safely and the previous membership remains in place. -- `Dave`, `Eve`, and `Ferdie` all own the nominated delegate hotkeys, and they individually control more than two percent of the network's total stakes. -- Using `btcli`, they can view the proposal and the calldata, which it will execute upon approval. -- `Dave` and `Ferdie` decided they wanted to approve this new subnet, and they both approved the proposal. -- `Eve` disagrees with the concept and disapproves of the proposal. +**EconomicEligible** membership is auto-synced with root registration state. When a coldkey's root-registered hotkey count goes from 0 to 1, the coldkey is added to EconomicEligible. The EMA tracks a combined stake value per coldkey: liquid TAO plus the TAO value of alpha across all owned hotkeys, sampled incrementally each block (8 subnets and ≤256 hotkeys per tick, decay factor alpha=0.02). A 210-sample warmup of approximately 30 days is required before a coldkey becomes eligible for selection. -Even though the Senate may have twelve members at any time, it is not guaranteed that there will be twelve occupied seats. With a Senate size of three, the approval threshold will be two approvals. Since `Dave` and `Ferdie` both approved this proposal, a member of the Triumvirate can now execute it. +### Building collective -**Closing** +The Building collective is selected every 60 days. The top 16 subnet-owner coldkeys by their best subnet's moving price take the seats, subject to: -`Alice` sees Senate has passed the proposal and executes the `close` extrinsic to execute the calldata within the proposal. +- Subnets younger than 180 days are excluded. +- At most one seat per coldkey regardless of how many qualifying subnets they own. -Bittensor now has a new subnet on which `Alice`, `Bob`, or `Charlie` can create further proposals to change hyperparameters, allow or disallow registration, and control any other configuration previously controlled by the `sudo` private key. +If fewer than 16 eligible coldkeys are available, the rotation fails safely and the previous membership remains in place. diff --git a/docs/governance/senate.md b/docs/governance/senate.md index e103388b..7be40add 100644 --- a/docs/governance/senate.md +++ b/docs/governance/senate.md @@ -3,46 +3,3 @@ title: "Senate" --- # Senate - -The Senate is a group of delegates who have elected to participate in proposals, and who control a significant portion of total network stake. - -All members of the network who have delegated stake to any of these Senate members are represented by the party that controls the delegate they've chosen to stake with. This allows any holder within the network to be represented, and to make their opinion known by delegating with organizations who represent their interests. - -## Requirements - -In order to participate in the Senate, a coldkey must: - -- Have registered with any subnetwork as a hotkey-coldkey pair. -- Have a hotkey stake value is greater than 2% of the network's total stake amount, through delegation or self-stake. -- Have elected to participate in the Senate. - - -Once all four of the requirements have been fulfilled by a coldkey-hotkey pair, they can vote on any proposal created by the [Triumvirate](../resources/glossary#triumvirate). - -In the case that the Senate has all twelve seats filled, and a delegate wishes to join, they will replace the lowest stake member as long as they have more stake in the network. - - - -## Viewing proposals - -Anyone can view proposals currently before the senate. This is an unpermissioned request. - -```shell -btcli sudo proposals -``` - -## Voting - -Senators can vote using the following command. You will be prompted for the proposal hash, which can be obtained in the proposals overview using `btcli sudo proposals`. - -After entering a proposal hash, you will then be prompted to either cast an approval or a disapproval. Once confirmed, the vote will be included in the next block and counted in the vote. - -``` -btcli sudo senate-vote -``` diff --git a/docs/learn/balancer-amm.md b/docs/learn/balancer-amm.md new file mode 100644 index 00000000..46c8f396 --- /dev/null +++ b/docs/learn/balancer-amm.md @@ -0,0 +1,172 @@ +--- +title: "Balancer Weighted Pools for Subnet AMMs" +--- + +# Balancer Weighted Pools for Subnet AMMs + +Each Bittensor subnet maintains an automated market maker (AMM) with [reserve pools](../subnets/understanding-subnets#liquidity-pools) of TAO and the subnet's alpha token. + +A constant product AMM can be seen as similar to a scale that sets the price of a swap by weighing the two pools against each other. When the TAO and alpha pools are balanced, the price is even. Staking in, adding TAO and taking alpha from the respective pools, tilts the scale toward TAO (the pool is now heavier). The angle of the scale determines the price: the more people stake TAO and take alpha, the price of alpha (alpha's position in vertical space) goes up. + +In any AMM, the price tends to 'slide' back down toward even, since a higher price exerts sell pressure. In a constant product AMM, the price is determined by the ratio of TAO and alpha, so the balance point is where they are even, i.e. in a 50/50 ratio, by their *value* (i.e. token quantities adjusted by price, so for example 100 TAO and 1000 alpha at a price of 0.1 TAO per alpha are in a 50/50 ratio). + +Balancer AMM allows the balance point of the scale to shift away from even 50/50 to reflect the value of the subnet on the marketplace of alpha tokens within Bittensor. + +:::note Mathematical limits of the analogy +The analogy between an AMM and a scale is helpful but limited, since the scale's behavior is a bit simpler. +A physical balance scale is linear: the angle of tilt is proportional to the mass difference between the two sides. +Price on a constant-product AMM follows a hyperbola (x·y = k), so the same-size trade moves the price much more when reserves are thin than when they are deep. The analogy captures the directional intuition: adding to one side raises that side's price. But it breaks down for slippage, which is a consequence of the hyperbolic curve. +::: + +For a full mathematical treatment, see the [Balancer AMMs whitepaper](https://learnbittensor.org/papers/balancer_amms.pdf). + +## Pool State + +Each subnet pool is defined by three values: + +| Parameter | Description | +|-----------|-------------| +| `alpha_reserve` (x) | Alpha tokens held in the pool | +| `tao_reserve` (y) | TAO held in the pool | +| `w_base`, `w_quote` | Pool weights where `w_base + w_quote = 1` | + +The weights are stored as a single `w_quote` value (18-decimal precision); `w_base = 1 - w_quote`. Both weights are bounded to **[0.01, 0.99]** (the upper bound is implied: `1 - w_quote ≥ 0.01`; there is no separate `MAX_WEIGHT` constant). The default at pool initialization is 0.5/0.5 (equal weight). + +## Price + +The current price of Alpha in TAO (the ideal price for an infinitesimally small trade, before any slippage) is: + +$$ +p = \frac{w_{\text{base}}}{w_{\text{quote}}} \cdot \frac{\tau}{\alpha} +$$ + +With equal weights (0.5/0.5), this simplifies to `p = TAO / alpha`, the same as a constant-product pool. + +## Swap Formulas + +### Selling Alpha to get TAO (unstaking) + +Given an input of `∆alpha` Alpha tokens, the TAO payout is: + +$$ +\Delta\tau = \tau \cdot \left(1 - \left(\frac{\alpha}{\alpha + \Delta\alpha}\right)^{w_{\text{base}}/w_{\text{quote}}}\right) +$$ + +### Buying Alpha with TAO (staking) + +Given an input of `∆TAO`, the Alpha payout is: + +$$ +\Delta\alpha = \alpha \cdot \left(1 - \left(\frac{\tau}{\tau + \Delta\tau}\right)^{w_{\text{quote}}/w_{\text{base}}}\right) +$$ + +With default equal weights (0.5/0.5), the exponent is 1 in both formulas, which reduces to the constant-product result `∆y = y * ∆x / (x + ∆x)`. The weights only diverge from 0.5/0.5 when the protocol has injected liquidity in a proportion that does not match the current price. + +## Weight Updates (moving the balance point) + +When the emissions system injects liquidity into a pool each block, the injection rarely arrives in exactly the current price ratio. The protocol calls `update_weights_for_added_liquidity()` to shift the weights and absorb the injection without moving the price. The new weights are computed from the updated reserves: + +$$ +w_{\text{quote}}^{\text{new}} = \frac{\tau^{\text{new}}}{p \cdot \alpha^{\text{new}} + \tau^{\text{new}}} +$$ + +where `p` is the price before the injection. Adding disproportionate liquidity shifts the weights; the price is unchanged. + +Both weights must remain within [0.01, 0.99]. If a proposed injection would push a weight outside this range, the injection is rejected rather than destabilize the pool math. + +## Limit Orders and Slippage Control + +Swaps can be bounded by a price limit. When a limit price is set, the pool calculates exactly how much can be swapped before the price reaches the limit: + +- **Selling with a floor price `p'`**: `∆alpha_max = alpha * ((p / p')^w_quote - 1)` +- **Buying with a ceiling price `p'`**: `∆TAO_max = TAO * ((p' / p)^w_base - 1)` + +If the requested swap amount would push the price past the limit, only the portion up to the limit executes. See [Price Protection](./price-protection.md) for how to use these limits via the CLI and SDK. + +## Liquidity Ownership + +All pool liquidity is protocol-owned. There are no user liquidity positions or LP tokens. The protocol initializes each pool when a subnet launches, and liquidity grows over time as emissions flow into the pool each tempo. + +## Fees + +A swap fee is charged on each stake and unstake operation. The fee rate is set per subnet (default ≈ 0.05%) and is applied to the input amount before the swap formula is evaluated. The fee goes to the block author. + +To compute the fee on an input amount `a` at fee rate `r` (stored as a `u16` where the full range is 0–65535): + +$$ +\text{fee} = a \cdot \frac{r}{65535} +$$ + +The effective input to the swap formula is `a - fee`. + +## Relationship to Slippage + +Slippage arises because the AMM price changes as reserves move. For a given swap size, slippage is higher when reserves are small relative to the trade. See [Understanding Slippage](./slippage.md) for worked examples. + +--- + +## Blockchain Implementation + +The following traces how the fulcrum-shifting mechanism works in the Subtensor codebase. + +### Every-block entry point + +Each block, `run_coinbase()` fires: + +``` +pallets/subtensor/src/coinbase/run_coinbase.rs — run_coinbase() + └─ emit_to_subnets() + ├─ get_subnet_terms() ← calculates tao_in and alpha_in + └─ inject_and_maybe_swap() ← calls adjust_protocol_liquidity +``` + +### Calculating the injection amounts + +`get_subnet_terms()` (`run_coinbase.rs`) determines how much TAO and Alpha to inject into each subnet pool per block: + +- **`tao_in`** = the subnet's share of this block's TAO emission +- **`alpha_in`** = `tao_in / current_price` — the equivalent Alpha at the current spot price +- If `alpha_in` exceeds the alpha injection cap (min of `alpha_emission` and `tao_block_emission`), both are scaled down and the excess TAO is routed to a buy-swap instead of an injection + +The injection pair `(tao_in, alpha_in)` is always computed at the current price ratio. Whether this shifts the weights depends on whether that price ratio matches the reserve ratio (see below). + +### Calling adjust_protocol_liquidity + +`inject_and_maybe_swap()` (`run_coinbase.rs:70`) makes the following call at line 91: + +```rust +T::SwapInterface::adjust_protocol_liquidity(*netuid_i, tao_in_i, alpha_in_i) +``` + +This routes through the `SwapHandler` trait implementation in `pallets/swap/src/pallet/impls.rs` to `Pallet::adjust_protocol_liquidity()` (`impls.rs:84`), which: + +1. Reads the current `alpha_reserve`, `tao_reserve`, and `SwapBalancer` weight state from storage +2. Calls `balancer.update_weights_for_added_liquidity(tao_reserve, alpha_reserve, tao_delta, alpha_delta)` +3. On success: writes the updated `SwapBalancer` (new weights) back to storage and returns the actual amounts injected +4. On failure (new weight would land outside `[0.01, 0.99]`): logs a warning, injects nothing, returns zeros + +### When the fulcrum actually moves + +`update_weights_for_added_liquidity()` (`balancer.rs:254`) computes new weights as: + +``` +quantity_1 = w_base_old × tao_reserve × new_alpha_reserve +quantity_2 = w_quote_old × alpha_reserve × new_tao_reserve +new_w_quote = quantity_2 / (quantity_1 + quantity_2) +``` + +Weights stay unchanged only when the injection is proportional to the *reserve ratio* (`tao_delta / alpha_delta = tao_reserve / alpha_reserve`). The coinbase injects at the *price ratio* (`tao_delta / alpha_delta = price`). Since `price = (w_base/w_quote) × (tao/alpha)`, these two ratios match only when `w_base = w_quote = 0.5`. When weights have drifted off 0.5/0.5, price-ratio injections nudge them back — a built-in self-correcting tendency. + +### Initialization + +When a subnet first becomes active, `maybe_initialize_palswap()` (`impls.rs:38`) is called. It reads the existing TAO and alpha reserves and the current price (from the migration), then computes the initial weights: + +``` +w_quote = tao_reserve / (price × alpha_reserve + tao_reserve) +``` + +This is stored in `SwapBalancer` and all subsequent price and swap calculations read from there. + +### Storage key + +The balancer state for each subnet is stored in `SwapBalancer` (a `StorageMap` in `pallets/swap/src/pallet/mod.rs`). The `Balancer` struct holds only a single `Perquintill` field named `quote`; `w_base` is always derived as `1 - quote`. diff --git a/docs/learn/slippage.md b/docs/learn/slippage.md index 7f19eac6..639814b1 100644 --- a/docs/learn/slippage.md +++ b/docs/learn/slippage.md @@ -8,60 +8,44 @@ import { SdkVersion } from "../sdk/_sdk-version.mdx"; ## Introduction -When staking and unstaking in Bittensor, _slippage_ refers to a difference between the quantity of tokens actually received, and the amount that would be expected based on a static price. This difference is due to the change in price due to the transaction itself. +When staking and unstaking in Bittensor, _slippage_ refers to the difference between the quantity of tokens actually received and the amount that would be expected at the static spot price. This difference arises because the transaction itself changes the pool's reserves, and therefore the price. -Each Bittensor subnet operates as a _constant product AMM_, meaning that it will accept trades that conserve the product of the quantities of the two tokens in reserve, TAO and alpha. To calculate the price in one token of batch of the other token that a buyer wishes to acquire—alpha if they are staking, or TAO if they are unstaking—the algorithm assumes that the transaction does not change this product, so the product of TAO and alpha is the same before and after. +Each Bittensor subnet operates a **Balancer weighted pool AMM**. The spot price and swap output are determined by the pool's TAO reserves, Alpha reserves, and a pair of pool weights (`w_base`, `w_quote`). See [Subnet AMM: Balancer Weighted Pool](./balancer-amm.md) for the full model. + +For the default case where pool weights are equal (0.5/0.5), the swap formula reduces to a constant-product result, so slippage behaves identically to a `xy = k` AMM. The worked example below uses this default case.
See how it's calculated! - When staking, the product K of TAO in reserve and alpha in reserve is the same before and after the transaction, so the initial product must be equal to the product after the cost in TAO is added to the reserve, and the stake is removed from the reserve and placed in the staked hotkey. - - Before: - $$ - \tau_{\mathrm{in}} \,\alpha_{\mathrm{in}} = k - $$ - - After: - $$ - (\tau_{\mathrm{in}} + \text{cost}) \bigl(\alpha_{\mathrm{in}} - \text{stake}\bigr) = k - $$ - - Equal: - - $$ - (\tau_{\mathrm{in}} + \text{cost}) \bigl(\alpha_{\mathrm{in}} - \text{stake}\bigr) - = \tau_{\mathrm{in}} \,\alpha_{\mathrm{in}} - $$ + The output of a swap is given by the Balancer formula. When staking `∆τ` TAO, the Alpha received is: + $$ + \Delta\alpha = \alpha \cdot \left(1 - \left(\frac{\tau}{\tau + \Delta\tau}\right)^{w_{\text{quote}}/w_{\text{base}}}\right) + $$ - This means that if we choose to stake in a certain amount of TAO (if we specify the cost), then the yielded stake (the quantity of alpha to be removed from reserve and granted to the staked hotkey) is: + With equal weights (0.5/0.5), the exponent is 1 and this simplifies to: - $$ - \text{Stake} = \alpha_{\text{in}} - \frac{\tau_{\text{in}} \alpha_{\text{in}}} {\tau_{\text{in}} + \text{cost}} - $$ + $$ + \Delta\alpha = \alpha - \frac{\tau \cdot \alpha}{\tau + \Delta\tau} + $$ - For example, suppose that a subnet has 100 alpha in reserve and 10 TAO, and we want to stake in 5 TAO. + For example, suppose a subnet has 100 Alpha in reserve and 10 TAO, and you want to stake 5 TAO. - The price at this moment is 10 TAO / 100 alpha, or 10 alpha per TAO, so if we stake 5 TAO, we would expect 50 alpha, without taking slippage into account. + The spot price is 10 TAO / 100 Alpha = 0.1 TAO per Alpha (or 10 Alpha per TAO), so at the static price you would expect 50 Alpha for 5 TAO. - With slippage, the actual alpha received will be less than 50 due to the price impact of the transaction. + With slippage, the actual Alpha received is: - $$ - \text{Stake} = 100 - \frac{ 10 * 100} {10 + 5} - $$ + $$ + \Delta\alpha = 100 - \frac{10 \times 100}{10 + 5} = 100 - \frac{1000}{15} \approx 33.33 + $$ - or 33.333 alpha sent to the hotkey. So in this case, the slippage is the difference between the ideal expectation of 50 and the actual swap value of 33.33333: + The slippage is the gap between the ideal and actual amounts: - $$ - 16.667 = 50 - 33.333 - $$ + $$ + 50 - 33.33 = 16.67 \text{ Alpha} + $$ - This slippage is 50% of the actual swap value, which is extremely high, - because we chose small values for the available liquidity. In general, - slippage is high when available liquidity is limited compared to the - magnitude of the transaction, since the transaction itself is changing the - price significantly. + This is 50% of the actual swap value — extremely high because the trade is large relative to the pool's reserves. In general, slippage increases as trade size grows relative to available liquidity.
diff --git a/docs/liquidity-positions/liquidity-positions.md b/docs/liquidity-positions/liquidity-positions.md deleted file mode 100644 index d79be56e..00000000 --- a/docs/liquidity-positions/liquidity-positions.md +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: User Liquidity Positions (Uniswap) ---- - -import { SdkVersion } from "../sdk/_sdk-version.mdx"; - -# User Liquidity Positions (Uniswap) - -## Overview - -The Liquidity Position feature allows users to provide trading liquidity for specific subnets, within specified price ranges for the subnet $\alpha$ token. This system is based on Uniswap V3's concentrated liquidity model and enables providers to earn fees from trading activity. - -Any TAO holder can contribute to the health of a subnet by creating a Liquidity Position (LP), to provide liquidity for staking/unstaking and stabilizing the subnet's token price. Liquidity positions accumulate fees when users stake and unstake within the defined price range, which the creator of the LP can subsequently withdraw into their wallet. - -Subnet creators can enable/disable the liquidity positions feature on their subnets. - -:::tip -A LP does not accumulate fees for staking operations by the coldkey that owns it. -::: - -See also: - -- [Managing User Liquidity Positions Tutorial](./managing-liquidity-positions.md). - -### Liquidity Positions vs. Staking - -When you stake TAO to a validator, you're essentially voting for that validator's participation in the subnet's consensus mechanism. The validator's total stake (including your delegation) determines their share of emissions and influence in the network. - -Stakers earn emissions off of their stake, which are distributed each tempo. - -Liquidity Positions earn fees when others stake or unstake within the price range defined on the position. - -By providing liquidity to a subnet's trading pool, you're enabling other users to trade between TAO and the subnet's Alpha tokens, creating more liquid market conditions for the subnet and helping to stabilize the subnet's token price. - -### Dynamic token composition - -A liquidity position (LP) can hold TAO, alpha, or both. This depends on the subnet's current token price relative to the range specified for the LP when it was created. - -This compositions represents the token requirements for creating an LP depending, as well as token yield from removing liquidity form the position, depending on the token price relative to the LP's price window, at the block when the transaction executes. - -**Price below range** (`current_price < price_low`): - -- Position becomes **100% Alpha tokens** -- `amount_alpha = liquidity * (1/sqrt_price_low - 1/sqrt_price_high)` -- `amount_tao = 0` - -**Price within range** (`price_low <= current_price <= price_high`): - -- Position maintains **mixed token composition** -- `amount_alpha = liquidity * (1/sqrt_current_price - 1/sqrt_price_high)` -- `amount_tao = liquidity * (sqrt_current_price - sqrt_price_low)` - -**Price above range** (`current_price > price_high`): - -- Position becomes **100% TAO tokens** -- `amount_alpha = 0` -- `amount_tao = liquidity * (sqrt_price_high - sqrt_price_low)` - -[See source code](https://github.com/opentensor/bittensor/blob/master/bittensor/utils/liquidity.py#L28-L58) - -## Liquidity Position Lifecycle - -### Creating Positions - -To create an LP, the user specifies a _liquidity_ parameter, which is converted into some combination of TAO and alpha token balances. TAO are taken from the users coldkey, alpha tokens are taken from the hotkey on which the Liquidity Position was created, and they are locked up in the LP. - -### Modifying a Position - -Its creator can modify an existing LP by adding or removing liquidity. The same formula is applied to determine the required tokens when adding liquidity, and to determine the yield of tokens when exiting liquidity, as when creating the LP. - -### Fee Accumulation - -Fees are generated when users perform swaps (trading TAO for Alpha or vice versa) within their position's price range. - -:::tip -Fees are not added to your position's liquidity, they are tracked separately, in the position's `fees_tao` and `fees_alpha` fields. - -See: [Managing User Liquidity Positions Tutorial: View your LPs](./managing-liquidity-positions.md#view-your-lps) -::: - - - -The blockchain calculates fees for each position based on: - -- Quantity staked/unstaked, tao/alpha respectively -- The the position's liquidity relative to other LPs that have their price range include the transaction. - -[See source code](https://github.com/opentensor/subtensor/blob/master/pallets/swap/src/position.rs#L110-L128) - -#### Fee Distribution - -Fees are not distributed automatically per tempo like emissions. Instead, fees are only distributed to your wallet when you actively withdraw liquidity: - -- **When modifying a position** (adding or removing liquidity): All accumulated fees are automatically collected and sent to your wallet. - [See source code](https://github.com/opentensor/subtensor/blob/master/pallets/swap/src/pallet/mod.rs#L410-L415) - -- **When removing a position entirely**: All accumulated fees are collected along with your position's tokens. - [See source code](https://github.com/opentensor/subtensor/blob/master/pallets/swap/src/pallet/mod.rs#L520-L535) - -This means you must actively manage your positions to claim your earned fees - they remain locked in the position until you perform a position operation (modify or remove). - -### Removing a Position - -When a position is destroyed/removed, the position's liquidity is converted back to tokens based on the current subnet price relative to your position's price range. The position is then deleted from the system. - -[See source code](https://github.com/opentensor/bittensor/blob/master/bittensor/core/extrinsics/asyncex/liquidity.py#L127-L185) - -## The `liquidity` Parameter - - - -The `liquidity` parameter that defines a LP is **not** an amount of TAO or Alpha tokens (or even a sum of the two). Instead, it's a mathematical scaling factor from Uniswap V3's concentrated liquidity model, which calculates the token amounts deducted from your hotkey and coldkey (alpha and TAO respectively) when creating a LP. - -The actual TAO and Alpha amounts that get locked are calculated by the `to_token_amounts()` function, represented below in pseudocode. - -:::note -The composition of the tokens required to create an LP depends on the current token price. -::: - -```python -if current_price < price_low { - # Only Alpha tokens required - alpha_amount = liquidity * (1/√price_low - 1/√price_high) - tao_amount = 0 -} else if current_price > price_high { - # Only TAO tokens required - tao_amount = liquidity * (√price_high - √price_low) - alpha_amount = 0 -} else { - # Both TAO and Alpha required - tao_amount = liquidity * (√current_price - √price_low) - alpha_amount = liquidity * (1/√current_price - 1/√price_high) -} -``` - -See also: - -- [See source code](https://github.com/opentensor/subtensor/blob/master/pallets/swap/src/position.rs#L80-L122) diff --git a/docs/liquidity-positions/managing-liquidity-positions.md b/docs/liquidity-positions/managing-liquidity-positions.md deleted file mode 100644 index acbdbf91..00000000 --- a/docs/liquidity-positions/managing-liquidity-positions.md +++ /dev/null @@ -1,615 +0,0 @@ ---- -title: Managing User Liquidity Positions Tutorial ---- - -In this tutorial we will explore the behavior of Bittensor's Uniswap-style user liquidity positions (LPs). To facilitate this, we'll deploy a Subtensor blockchain locally and create a subnet on it. - -Liquidity positions can be complicated and potentially confusing, as their behavior is sensitive to the subnet price relative to the position's high' and 'low' price boundaries, at several stages of their life-cycle: - -- When a LP is created -- When liquidity is added to an existing LP by modifying it -- During fee accrual -- When liquidity is exited from an existing LP by modifying it -- When liquidity is exited from an existing LP by removing (deleting) the position. - -## Setup - -### Deploy a Bittensor (Subtensor) blockchain locally. - -See: [Deploy a Local Bittensor Blockchain Instance](../local-build/deploy) - -Or try the easy way, by running: - -```bash -docker run --rm --name test_local_chain_ -p 9944:9944 -p 9945:9945 ghcr.io/opentensor/subtensor-localnet:devnet-ready -``` - -### Create a subnet - -Create a subnet managed by the Alice wallet. - -See [Provision wallets: Access the Alice account](../local-build/provision-wallets#access-the-alice-account) - -``` -btcli subnet create \ ---subnet-name awesome-first-subnet \ ---wallet.name alice \ ---network ws://127.0.0.1:9945 -``` - - - -### Start emissions - -First, use the subnet creator key to start emissions on the subnet. Assuming your want to use subnet 2, run: - -```shell -btcli subnet start --netuid 2 \ ---wallet.name sn-creator \ ---network ws://127.0.0.1:9945 -``` - -```console -Are you sure you want to start subnet 2's emission schedule? [y/n]: y -Enter your password: -Decrypting... -✅ Successfully started subnet 2's emission schedule. -``` - -:::tip -After some time has passed, you'll be able to confirm that emissions are flowing by inspecting your subnet's token economy. You'll see a non-zero amount in the _Emissions_ column, indicating, even if no mining activity is occuring, the subnet creator key accumulates emissions. - -If you have only started one subnet, you'll see that it's emissions are always exactly 1 $\tau$. - -See [Emissions](../learn/emissions) - -```shell - btcli view dashboard \ ---wallet.name sn-creator \ ---network ws://127.0.0.1:9945 -``` - -::: - -### Configure the `user_liquidity_enabled` hyperparameter - -Set the `user_liquidity_enabled` hyperparameter to `True` from its default value of `False`. - -```shell -btcli sudo set --netuid 2 \ ---parameter user_liquidity_enabled \ ---value True \ ---wallet.name sn-creator \ ---network ws://127.0.0.1:9945 - -``` - -```console -✅ Hyperparameter user_liquidity_enabled changed to True - - Subnet Hyperparameters - NETUID: 2 (awesome-first-subnet) - Network: custom - - HYPERPARAMETER VALUE NORMALIZED - ──────────────────────────────────────────────────────────────────────── - - (all the hyperparameters...) - - user_liquidity_enabled True True - ──────────────────────────────────────────────────────────────────────── -``` - -:::tip -Confirm the subnet configuration with the following command, checking that `user_liquidity_enabled` is `True`. - -``` -btcli subnet hyperparameters --netuid 2 --network ws://127.0.0.1:9945 -``` - -::: - -### Create and fund a liquidity manager wallet - -Additionally, in order to manage liquidity on a subnet, a user use a hotkey that has some stake on the subnet. Therefore you must register and stake some liquidity into the hotkey. This alpha liquidity will be used for the alpha component when you add liquidity to a position, when creating or modifying it. - -1. Create the wallet - ```shell - btcli w create --wallet.name liquidity-manager --hotkey lp-hotkey - ``` -2. Transfer funds from the Alice account - ``` - btcli wallet transfer \ - --amount 1001 \ - --wallet.name alice \ - --destination "5F7LNFEmsngMV2yaA41WPeYuQmVGcesu5TPJizPDpSUHviVr" \ # Coldkey public key for your liquidity-manager wallet - --network ws://127.0.0.1:9945 - ``` -3. Check your balance in the dashboard - - ```shell - btcli view dashboard \ - --wallet.name liquidity-manager \ - --network ws://127.0.0.1:9945 - ``` - -4. Register your liquidity-manager's hotkey. - - This is the hotkey that will contain alpha stake related to the position. When you add alpha liquidity to the position, it will come from this hotkey, and when you exit it from the position, it will be credited to this hotkey. - - You can either use your wallet's name for the hotkey (as below), or specify the hotkey's ss58 address in interactive mode. If you need to find your hotkey's ss58, use `btcli wallet list`. - - :::tip - On a local blockchain running in fastblocks mode, you will likely need to use the `--period` flag to give you a long enough window before your registration request will expire. - ::: - - ```shell - btcli subnet register \ - --wallet.name liquidity-manager \ - --wallet.hotkey hotsauce \ - --period 20 \ - --network ws://127.0.0.1:9945 - ``` - - ```console - Register to netuid: 2 - Network: custom - - Netuid ┃ Symbol ┃ Cost (Τ) ┃ Hotkey ┃ Coldkey - ━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ - 2 │ β │ τ 0.0913 │ 5DJepbhrkAVdf5L3kXLMvjHu8TBB62AAGN8U4LjTtQYoKG9R │ 5F7LNFEmsngMV2yaA41WPeYuQmVGcesu5TPJizPDpSUHviVr - ────────┼────────┼──────────┼──────────────────────────────────────────────────┼────────────────────────────────────────────────── - │ │ │ │ - Your balance is: 1,001.0000 τ - The cost to register by recycle is 0.0913 τ - Do you want to continue? [y/n] (n): y - Enter your password: - Decrypting... - Balance: - 1,001.0000 τ ➡ 1,000.9087 τ - ✅ Registered on netuid 2 with UID 1 - ``` - -## Creating liquidity positions - -The token input when creating a LP depends on whether the current token price is above, below, or within the window between the high and low price that define the position. Therefore you should always check the current token price when creating, removing, or modifying positions, so you correctly anticipate the behavior. - -To observe the token input behavior of liquidity positions, let's create attempt to create 3 LPs, such that the current price is below, within, and above, the positions' respective price windows. - -If we attempt to create an LP with high window, i.e. with its low price above the current token price, or if we attempt to create one with a window that spans the current price, it will fail. That is because the token composition for a LP with a high window is entirely alpha, and for a LP with a window that spans the current price, it is mixed TAO and alpha. Therefore, to create the LP requires some alpha to be staked into the hotkey, and currently the hotkey has no stake. - -However, if we attempt to create a LP with a low window relative to the current price, i.e. with its high price below the current price, it will succeed, because the LP is composed entirely of TAO. - -See [Liquidity Positions: Dynamic token composition](./#dynamic-token-composition). - -### Check the price - -Always check the token price prior to creating LPs so you can predict their behavior. - -To easily view token prices on your local chain, as well as your TAO balance and alpha stakes, use the BTCLI dashboard: - -``` -btcli view dashboard \ ---wallet.name liquidity-manager \ ---network ws://127.0.0.1:9945 -``` - -You can also check the price with the following: - -``` -btcli subnet list --network ws://127.0.0.1:9945 - - Subnets - Network: custom - - - ┃ ┃ Price ┃ Market Cap ┃ ┃ ┃ ┃ ┃ - Netuid ┃ Name ┃ (Τ_in/α_in) ┃ (α * Price) ┃ Emission (Τ) ┃ P (Τ_in, α_in) ┃ Stake (α_out) ┃ Supply (α) ┃ Tempo (k/n) -━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━ - 0 │ τ root │ 1.0000 τ/Τ │ τ 0.00 │ τ 0.0000 │ -, - │ Τ 0.00 │ 0.00 Τ /21M │ -/- - 2 │ β awesome-first-subnet │ 1.0001 τ/β │ τ 13.02k │ τ 1.0000 │ τ 7.00k, 7.00k β │ 6.02k β │ 13.02k β /21M │ 3/10 - 1 │ α apex │ 0.0000 τ/α │ τ 0.00 │ τ 0.0000 │ τ 10.00, 10.00 α │ 1.00 α │ 11.00 α /21M │ 21/100 -────────┼────────────────────────┼─────────────┼─────────────┼──────────────┼─────────────────────────┼───────────────┼───────────────┼───────────── -``` - -### High and spanning window - -These requests are bound to fail, because we have not yet staked any alpha to the hotkey: - -``` -btcli liquidity add --netuid 2 --network ws://127.0.0.1:9945 --wallet.name liquidity-manager --hotkey hotsauce - -Enter the amount of liquidity: 10 -Enter liquidity position low price: 1.1 -Enter liquidity position high price (must be greater than low price): 1.3 - -You are about to add a LiquidityPosition with: - liquidity: 10.0000 τ - price low: 1.1000 τ - price high: 1.3000 τ - to SN: 2 - using wallet with name: liquidity-manager -Would you like to continue? [y/n]: y -Error: Subtensor returned `InsufficientBalance(Module)` error. This means: `The caller does not have enough balance for the operation. - -btcli liquidity add --netuid 2 --network ws://127.0.0.1:9945 --wallet.name liquidity-manager --hotkey hotsauce --liquidity 10 --price-low .5 --price-high 1.5 - -You are about to add a LiquidityPosition with: - liquidity: 10.0000 τ - price low: 0.5000 τ - price high: 1.5000 τ - to SN: 2 - using wallet with name: liquidity-manager -Would you like to continue? [y/n]: y -Error: Subtensor returned `InsufficientBalance(Module)` error. This means: `The caller does not have enough balance for the operation. -``` - -### If the current price is below the window - -However, the following position can be created, because its high price is below the current token price. - -```shell -btcli liquidity add --netuid 2 --network ws://127.0.0.1:9945 --wallet.name liquidity-manager -``` - -```console -Enter the amount of liquidity: 10 -Enter liquidity position low price: .5 -Enter liquidity position high price (must be greater than low price): .7 -Enter your password: -Decrypting... -You are about to add a LiquidityPosition with: - liquidity: 100.0000 τ - price low: 0.5000 τ - price high: 0.7000 τ - to SN: 2 - using wallet with name: liquidity-manager -Would you like to continue? [y/n]: y -LiquidityPosition has been successfully added. -``` - -View the position by running: - -```shell -btcli liquidity list --netuid 2 --network ws://127.0.0.1:9945 --wallet.name liquidity-manager -``` - -```console - - Liquidity Positions of liquidity-manager wallet in SN #2 - Alpha and Tao columns are respective portions of liquidity. -┏━━━━┳━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━┓ -┃ ID ┃ Liquidity ┃ Alpha ┃ Tao ┃ Price low ┃ Price high ┃ Fee TAO ┃ Fee Alpha ┃ -┡━━━━╇━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━┩ -│ 2 │ 10.0 │ 0.0000 β │ 1.2956 τ │ 0.5000 τ │ 0.7001 τ │ 0.0000 τ │ 0.0000 β │ -└────┴───────────┴──────────┴──────────┴───────────┴────────────┴──────────┴───────────┘ - -``` - -### Add alpha to the liquidity manager hotkey - -Next, stake into your hotkey so you'll be able to create those other LPs. - -:::note notes -Use `--partial` to make things easier; this option allows you to specify a large staking amount, and an amount will be staked up to your tolerance threshold. - -If you don't use partial (or unsafe-staking mode), you'll have to find a staking amount that will be tolerated by your slippage limit. -::: - -```shell -btcli stake add --netuid 2 \ ---hotkey hotsauce --amount 10 \ ---wallet.name liquidity-manager \ ---partial \ ---network ws://127.0.0.1:9945 -``` - -```console -Safe staking: enabled (from config). -Rate tolerance: 0.005 (0.5%) by default. Set this using `btcli config set` or `--tolerance` flag -Partial staking: enabled. - - - Wallet Coldkey Balance - Network: custom - - Wallet Name Coldkey Address Free Balance Staked Value Total Balance - ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ - liquidity-manager 5F7LNFEmsngMV2yaA41WPeYuQmVGcesu5TPJizPDpSUHviVr 1,000.9100 τ 0.0000 τ 1,000.9100 τ - - - - Total Balance 1,000.9100 τ 0.0000 τ 1,000.9100 τ - ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ - -Amount to stake (TAO τ): 10 - - Staking to: - Wallet: liquidity-manager, Coldkey ss58: 5F7LNFEmsngMV2yaA41WPeYuQmVGcesu5TPJizPDpSUHviVr - Network: custom - - Netuid ┃ Hotkey ┃ Amount (Τ) ┃ Rate (per Τ) ┃ Received ┃ Fee (τ) ┃ Rate with tolerance: (0.5%) ┃ Partial stake enabled -━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━ - 2 │ 5DJepbhrkAVdf5L3kXLMvjHu8TBB62AAGN8U4LjTtQYoKG9R │ 10.0000 τ │ 0.666633241675929 β/Τ │ 6.6663 β │ Τ 0.0299 │ 0.6633 β/Τ │ True -────────┼──────────────────────────────────────────────────┼────────────┼────────────────────────┼──────────┼──────────┼─────────────────────────────┼─────────────────────── - │ │ │ │ │ │ │ - -Description: -The table displays information about the stake operation you are about to perform. -The columns are as follows: - - Netuid: The netuid of the subnet you are staking to. - - Hotkey: The ss58 address of the hotkey you are staking to. - - Amount: The TAO you are staking into this subnet onto this hotkey. - - Rate: The rate of exchange between your TAO and the subnet's stake. - - Received: The amount of stake you will receive on this subnet after slippage. - - Rate Tolerance: Maximum acceptable alpha rate. If the rate exceeds this tolerance, the transaction will be limited or rejected. - - Partial staking: If True, allows staking up to the rate tolerance limit. If False, the entire transaction will fail if rate tolerance is exceeded. - -Would you like to continue? [y/n]: y -Enter your password: -Decrypting... -✅ Finalized. Stake added to netuid: 2 -Balance: - 1,000.9100 τ ➡ 990.9100 τ -Subnet: 2 Stake: - 0.0000 τ ➡ 6.6299 β -``` - -If you now view your dashboard, you'll see that your TAO balance has reduced by the staked amount, plus the amount of $\tau$ locked into the liquidity position. - -``` - btcli view dashboard \ ---wallet.name liquidity-manager \ ---network ws://127.0.0.1:9945 -``` - -Now let's try again to create the positions that previously we could not. - -#### High window position - -```shell - -btcli liquidity add --netuid 2 --network ws://127.0.0.1:9945 --wallet.name liquidity-manager --hotkey hotsauce --liquidity 10 --price-low 1.1 --price-high 1.3 -``` - -#### Spanning window position - -```shell -btcli liquidity add --netuid 2 --network ws://127.0.0.1:9945 --wallet.name liquidity-manager --hotkey hotsauce --liquidity 10 --price-low .5 --price-high 1.5 -``` - -### View your LPs - -Now we can see all LPs listed. - -:::note -The `liquidity` parameter you specify is **not** the amount of TAO/Alpha tokens that will be locked up. Instead, it's a mathematical scaling factor from Uniswap V3's concentrated liquidity model, which calculates the token amounts deducted from your hotkey and coldkey (alpha and TAO respectively) when creating a LP. - -Hence you are not charged 10 TAO to create a LP with a magnitude of 10, in this case note that the quantity is 1.295 -::: - -```shell -btcli liquidity list --netuid 2 --network ws://127.0.0.1:9945 --wallet.name liquidity-manager - - Liquidity Positions of liquidity-manager wallet in SN #2 - Alpha and Tao columns are respective portions of liquidity. -┏━━━━┳━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━┓ -┃ ID ┃ Liquidity ┃ Alpha ┃ Tao ┃ Price low ┃ Price high ┃ Fee TAO ┃ Fee Alpha ┃ -┡━━━━╇━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━┩ -│ 5 │ 10.0 │ 1.8226 β │ 2.9407 τ │ 0.5000 τ │ 1.4999 τ │ 0.0000 τ │ 0.0000 β │ -│ 4 │ 10.0 │ 0.7638 β │ 0.0000 τ │ 1.1000 τ │ 1.2999 τ │ 0.0000 τ │ 0.0000 β │ -│ 2 │ 10.0 │ 0.0000 β │ 1.2956 τ │ 0.5000 τ │ 0.7001 τ │ 0.0000 τ │ 0.0000 β │ -└────┴───────────┴──────────┴──────────┴───────────┴────────────┴──────────┴───────────┘ -``` - -## - -Now let's see what happens when we stake and unstake within the trading window of liquidity positions. - -Create a validator coldkey if you don't have one, (See [Provision Wallets for Local Deploy](../local-build/provision-wallets) and [Mine and Validate (Locally): Register](../local-build/mine-validate)) then transfer a small amount of TAO to it from the Alice wallet. - -Then register a hotkey for it on subnet 2. - -Now, let's stake to it from the Alice wallet. - -``` -btcli stake add --netuid 2 \ ---network ws://127.0.0.1:9945 --wallet.name alice --partial --amount 1000 - -Safe staking: enabled (from config). -Rate tolerance: 0.005 (0.5%) by default. Set this using `btcli config set` or `--tolerance` flag -Partial staking: enabled. - - -Enter the wallet hotkey name or ss58 address to stake to (or Press Enter to view delegates): -Using the wallet path from config: /Users/michaeltrestman/.bittensor/wallets - - - - Subnet 2: awesome-first-subnet - Network: custom - - UID ┃ Stake (β) ┃ Alpha (β) ┃ Tao (τ) ┃ Dividends ┃ Incentive ┃ Emissions (β) ┃ Hotkey ┃ Coldkey ┃ Identity -━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━ - 0 │ 11.35k β │ 11.35k β │ τ 0.00 │ 0.000000 │ 0.000000 │ 0.000000 β │ 5Grwva │ 5Grwva │ (*Owner controlled) - 2 │ 751.95 β │ 751.95 β │ τ 0.00 │ 0.000000 │ 0.000000 │ 9.020050 β │ 5CffqS │ 5EEy34 │ ~ - 1 │ 10.84 β │ 10.84 β │ τ 0.00 │ 0.000000 │ 0.000000 │ 0.000000 β │ 5DJepb │ 5F7LNF │ ~ -─────┼───────────┼───────────┼─────────┼───────────┼───────────┼───────────────┼────────┼─────────┼───────────────────── - │ 12.12k β │ 12.12k β │ 0.00 β │ 0.000 │ │ 9.0201 β │ │ │ - - - -Enter the UID of the delegate you want to stake to (or press Enter to cancel): 2 - -Selected delegate: 5CffqSVhydFJHBSbbgfVLAVkoNBTsv3wLj2Tsh1cr2kfanU6 - - Staking to: - Wallet: alice, Coldkey ss58: 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY - Network: custom - - Netuid ┃ Hotkey ┃ Amount (Τ) ┃ Rate (per Τ) ┃ Received ┃ Fee (τ) ┃ Rate with tolerance: (0.5%) ┃ Partial stake enabled -━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━ - 2 │ 5CffqSVhydFJHBSbbgfVLAVkoNBTsv3wLj2Tsh1cr2kfanU6 │ 1,000.0000 τ │ 0.9926136629572226 β/Τ │ 992.6137 β │ Τ 2.9908 │ 0.9877 β/Τ │ True -────────┼──────────────────────────────────────────────────┼──────────────┼─────────────────────────┼────────────┼──────────┼─────────────────────────────┼─────────────────────── - │ │ │ │ │ │ │ - -Description: -The table displays information about the stake operation you are about to perform. -The columns are as follows: - - Netuid: The netuid of the subnet you are staking to. - - Hotkey: The ss58 address of the hotkey you are staking to. - - Amount: The TAO you are staking into this subnet onto this hotkey. - - Rate: The rate of exchange between your TAO and the subnet's stake. - - Received: The amount of stake you will receive on this subnet after slippage. - - Rate Tolerance: Maximum acceptable alpha rate. If the rate exceeds this tolerance, the transaction will be limited or rejected. - - Partial staking: If True, allows staking up to the rate tolerance limit. If False, the entire transaction will fail if rate tolerance is exceeded. - -Would you like to continue? [y/n]: y -✅ Finalized. Stake added to netuid: 2 -Balance: - 996,967.4407 τ ➡ 996,934.4742 τ -Partial stake transaction. Staked: - 32.9665 τ instead of 1,000.0000 τ -Subnet: 2 Stake: - 420.9182 β ➡ 457.4970 β -``` - -So now, examining the liquidity positions, we can see that some small amount of fees have accumulated to the LP whose window spans the current price, but not the others. - -Note that the fees have accumulated to `Fee TAO`, but not to `Fee Alpha`. - -```shell - btcli liquidity list --netuid 2 --network ws://127.0.0.1:9945 --wallet.name liquidity-manager - - Liquidity Positions of liquidity-manager wallet in SN #2 - Alpha and Tao columns are respective portions of liquidity. -┏━━━━┳━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━┓ -┃ ID ┃ Liquidity ┃ Alpha ┃ Tao ┃ Price low ┃ Price high ┃ Fee TAO ┃ Fee Alpha ┃ -┡━━━━╇━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━┩ -│ 4 │ 10.0 │ 1.7729 β │ 2.9908 τ │ 0.5000 τ │ 1.4999 τ │ 0.0001 τ │ 0.0000 β │ -│ 3 │ 10.0 │ 0.7638 β │ 0.0000 τ │ 1.1000 τ │ 1.2999 τ │ 0.0000 τ │ 0.0000 β │ -│ 2 │ 10.0 │ 0.0000 β │ 1.2956 τ │ 0.5000 τ │ 0.7001 τ │ 0.0000 τ │ 0.0000 β │ -└────┴───────────┴──────────┴──────────┴───────────┴────────────┴──────────┴───────────┘ -``` - -Now let's unstake and see what happens - -```shell -btcli stake remove --netuid 2 \ ---partial \ ---wallet.name alice \ ---network ws://127.0.0.1:9945 -``` - -```console -Safe staking: enabled (from config). -Rate tolerance: 0.005 (0.5%) by default. Set this using `btcli config set` or `--tolerance` flag -Partial staking: enabled. - -Enter the hotkey name or ss58 address to unstake from (or Press Enter to view existing staked hotkeys): - - Hotkeys with Stakes for Subnet 2 - - Index ┃ Identity ┃ Netuids ┃ Hotkey Address -━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ - 0 │ 5Grw...utQY │ 2 │ 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY - 1 │ 5Cff...anU6 │ 2 │ 5CffqSVhydFJHBSbbgfVLAVkoNBTsv3wLj2Tsh1cr2kfanU6 -───────┼─────────────┼─────────┼────────────────────────────────────────────────── - │ │ │ - -Enter the index of the hotkey you want to unstake from [0/1]: 1 - - - - Stakes for hotkey - 5Cff...anU6 -5CffqSVhydFJHBSbbgfVLAVkoNBTsv3wLj2Tsh1cr2kfanU - 6 - - Subnet ┃ Symbol ┃ Stake Amount ┃ Rate (Τ/α) -━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━ - 2 │ β │ 3,067.5744 β │ 1.012479 τ/β -────────┼────────┼──────────────┼────────────── - │ │ │ - - -Unstake all: 3,067.5744 β from 5Cff...anU6 on netuid: 2? [y/n/q] (n): y - - Unstaking to: - Wallet: alice, Coldkey ss58: 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY - Network: custom - - Netuid ┃ Hotkey ┃ Amount (α) ┃ Rate (Τ/α) ┃ Fee (α) ┃ Received (Τ) ┃ Rate with tolerance: (0.5%) ┃ Partial unstake enabled -━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━ - 2 │ 5Cff...anU6 │ 3,067.5744 β │ 1.012479(Τ/β) │ 9.1744 β │ 3,105.8531 τ │ 1.007416 Τ/β │ True -────────┼─────────────┼──────────────┼───────────────┼──────────┼──────────────┼─────────────────────────────┼───────────────────────── - │ │ │ │ │ 3,105.8531 τ │ │ - -Description: -The table displays information about the stake remove operation you are about to perform. -The columns are as follows: - - Netuid: The netuid of the subnet you are unstaking from. - - Hotkey: The ss58 address or identity of the hotkey you are unstaking from. - - Amount to Unstake: The stake amount you are removing from this key. - - Rate: The rate of exchange between TAO and the subnet's stake. - - Fee: The transaction fee for this unstake operation. - - Received: The amount of free balance TAO you will receive on this subnet after slippage and fees. - - Slippage: The slippage percentage of the unstake operation. (0% if the subnet is not dynamic i.e. root). - - Rate Tolerance: Maximum acceptable alpha rate. If the rate reduces below this tolerance, the transaction will be limited or rejected. - - Partial unstaking: If True, allows unstaking up to the rate tolerance limit. If False, the entire transaction will fail if rate tolerance is exceeded. - -Would you like to continue? [y/n]: y -✅ Finalized -Balance: - 996,934.4742 τ ➡ 997,054.1796 τ -Partial unstake transaction. Unstaked: - 118.8823 β instead of 3,067.5744 β -Subnet: 2 Stake: - 3,075.3541 β ➡ 2,956.4718 β -Unstaking operations completed. -``` - -Now, viewing our LP again, we can see that fees have accumulated to the position's `Fee Alpha` attribute. - -```shell -btcli liquidity list --netuid 2 --network ws://127.0.0.1:9945 --wallet.name liquidity-manager - - Liquidity Positions of liquidity-manager wallet in SN #2 - Alpha and Tao columns are respective portions of liquidity. -┏━━━━┳━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━┓ -┃ ID ┃ Liquidity ┃ Alpha ┃ Tao ┃ Price low ┃ Price high ┃ Fee TAO ┃ Fee Alpha ┃ -┡━━━━╇━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━┩ -│ 4 │ 10.0 │ 1.7978 β │ 2.9657 τ │ 0.5000 τ │ 1.4999 τ │ 0.0001 τ │ 0.0001 β │ -│ 3 │ 10.0 │ 0.7638 β │ 0.0000 τ │ 1.1000 τ │ 1.2999 τ │ 0.0000 τ │ 0.0000 β │ -│ 2 │ 10.0 │ 0.0000 β │ 1.2956 τ │ 0.5000 τ │ 0.7001 τ │ 0.0000 τ │ 0.0000 β │ -└────┴───────────┴──────────┴──────────┴───────────┴────────────┴──────────┴───────────┘ -``` - -## Remove liquidity from the position - -Let's remove the LP and recover the liquidity inside. To see how this affects our balance, run the `dashboard` command once before the `liquidity remove` command, and once after. You will see a small increase in your token balances. - -:::tip -You can find the required LP ID with `btcli liquidity list`, as seen above. -::: - -```shell -btcli liquidity remove --netuid 2 --network ws://127.0.0.1:9945 --wallet.name liquidity-manager -``` - -```console -Enter the liquidity position ID: 5 -Enter the SS58 of the hotkey to use for this transaction.: 5DJepbhrkAVdf5L3kXLMvjHu8TBB62AAGN8U4LjTtQYoKG9R - -You are about to remove LiquidityPositions with: - Subnet: 2 - Wallet name: liquidity-manager - Position id: 5 -Would you like to continue? [y/n]: y -Enter your password: -Decrypting... -Position 5 has been removed. -``` diff --git a/docs/navigating-subtensor/swap-stake.md b/docs/navigating-subtensor/swap-stake.md index 0f1293c8..dd957790 100644 --- a/docs/navigating-subtensor/swap-stake.md +++ b/docs/navigating-subtensor/swap-stake.md @@ -8,6 +8,8 @@ This page provides a detailed examination of how staking is implemented in the S Each subnet maintains its own AMM pool with TAO and Alpha reserves. When you stake, your TAO enters the subnet's TAO reserve and you receive Alpha tokens that represent your stake in that specific subnet. Alpha stake determines consensus weight and emission share for validators within a given subnet. +The pool uses a **Balancer weighted pool AMM** (`pallets/swap/src/pallet/balancer.rs`). Swap output is computed via the weighted exponentiation formula rather than a simple constant product. See [Subnet AMM: Balancer Weighted Pool](../learn/balancer-amm.md) for the math. + See [Staking/Delegation Overview](../staking-and-delegation/delegation) :::tip Key Concept diff --git a/docs/resources/glossary.md b/docs/resources/glossary.md index dda0f03d..d5b418af 100644 --- a/docs/resources/glossary.md +++ b/docs/resources/glossary.md @@ -805,7 +805,9 @@ The Bittensor SDK offers the [`bittensor.core.subtensor`](pathname:///python-api ### Sudo -A privileged key for administrative actions, replaced by governance protocol for enhanced security. +A privileged role required for administrative actions, such as changing the values of chain state variables, and subnet hyperparameters that are not accessible to subnet owners. + +On Bittensor mainnet ('finney'), sudo is controlled by the triumvirate. **See also:** [Governance](../governance/governance.md), [btcli Permissions](../btcli/btcli-permissions.md) @@ -843,7 +845,7 @@ The process of sending TAO tokens from one wallet address to another in the Bitt ### Triumvirate -A group of three Opentensor Foundation employees responsible for creating proposals. +A group of three Opentensor Foundation employees that controls the sudo key. **See also:** [Governance](../governance/governance.md), [Senate](../governance/senate.md) diff --git a/docs/sdk/index.md b/docs/sdk/index.md index 796dbe51..00b63a71 100644 --- a/docs/sdk/index.md +++ b/docs/sdk/index.md @@ -36,8 +36,6 @@ Manage your TAO stake across validators and subnets. - How to move stake between validators - How to transfer stake - [Managing Root Claims](../staking-and-delegation/root-claims/managing-root-claims.md): Claim root network positions -- [Managing Liquidity Positions](../liquidity-positions/managing-liquidity-positions.md): Add and remove liquidity on Uniswap - ## Proxy Operations Use proxies to delegate account permissions securely while keeping your coldkey offline. diff --git a/docusaurus.config.js b/docusaurus.config.js index 00f994ee..16a184ff 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -93,10 +93,6 @@ const config = { to: "/subnets/understanding-multiple-mech-subnets", from: "/subnets/understanding-sub-subnets", }, - { - to: "/liquidity-positions/", - from: "/liquidity-provider", - }, { to: "/staking-and-delegation/staking-polkadot-js", from: "/staking/staking-polkadot-js", @@ -237,6 +233,14 @@ const config = { from: "/subtensor-nodes/using-source", to: "/subtensor-nodes/run/using-source", }, + { + from: "/liquidity-positions/liquidity-positions", + to: "/learn/balancer-amm", + }, + { + from: "/liquidity-positions/managing-liquidity-positions", + to: "/learn/balancer-amm", + }, ], }, ], diff --git a/sidebars.js b/sidebars.js index 216d961b..93e38a93 100644 --- a/sidebars.js +++ b/sidebars.js @@ -141,7 +141,8 @@ const sidebars = { ], }, "learn/price-protection", - "learn/slippage", + "learn/balancer-amm", + "learn/slippage", "staking-and-delegation/staking-polkadot-js", "staking-and-delegation/using-ledger-hw-wallet", ], @@ -169,16 +170,6 @@ const sidebars = { "validators/validators-btcli-guide", ], }, - { - type: "category", - label: "Liquidity Positions (Uniswap)", - collapsible: true, - collapsed: true, - items: [ - "liquidity-positions/liquidity-positions", - "liquidity-positions/managing-liquidity-positions", - ], - }, { type: "category", label: "Managing Subnets", diff --git a/static/img/docs/proposal-flow.svg b/static/img/docs/proposal-flow.svg new file mode 100644 index 00000000..36779c32 --- /dev/null +++ b/static/img/docs/proposal-flow.svg @@ -0,0 +1 @@ +On-Chain Governance: Proposal FlowProposers CollectiveTriumvirateReview CollectiveChainProposers Collective(1-20 members)Proposers Collective(1-20 members)Triumvirate(3 members)Triumvirate(3 members)Review Collective(Economic ∪ Building, ≤32)Review Collective(Economic ∪ Building, ≤32)ChainChainProposal SubmissionA member of the Proposers collective submits a root call(protocol change, runtime upgrade, or other privileged operation).submit_proposal(call)Proposal enters Triumvirate track.Triumvirate Track (7 days)7-day decision window2-of-3 ayes advance · 2-of-3 nays rejectvote(aye/nay)opt[2-of-3 ayes reached]advance to review track[2-of-3 nays reached OR 7-day timeout]rejectReview Track24h initial delay / 2-day maxVoter set: deduplicated union of Economic and Buildingvote(aye/nay)opt[Fast-track]75% or more aye votes → execute at next blockopt[Cancel]51% or more nay votes → proposal cancelledopt[Delay adjustment]recompute delay (ease-out curve) as nay votes accumulateVoter eligibility is snapshotted at review-track open.Collective rotations during the period do not changewho may vote or shift the thresholds.When the adjusted delay drops below elapsed time,execution begins.ExecutionAfter the delay period expires (and if not cancelled),the chain executes the call with root privilege.If execution fails, it is not retried and is cleaned up.execute(call as Root)alt[success]cleanup[failure]cleanup (no retry) \ No newline at end of file